Implementing TLV in javascript

I am trying to implement TLV for e-invoice in Javascript. I am able to convert the values to hex and from hex to base64. When I add the base64 value to the QRcode and try to test it, I get an error telling me there is something wrong with my data. Below is my implementation

const  __toString = (tag, value) => {
    const tagToHex = "0"+(tag).toString(16)
    const valueLengthToHex = value.length <= 15 ? "0" + (value.length).toString(16) :(value.length).toString(16)
    const valueToHex = this.toHex(value)

    return `${tagToHex}${valueLengthToHex}${valueToHex}`;
}

const toHex = (str) => {
    let result = '';
    for (let i=0; i<str.length; i++) {
      result += str.charCodeAt(i).toString(16);
    }
    return result;
}

Entry point

const generateString = [
    __toString(1, 'Bobs Records'),
    __toString(2, '310122393500003'),
    __toString(3, '2022-04-25T15:30:00Z'),
    __toString(4, '1000.00'),
    __toString(5, '150.00'),
];

return btoa(generateString.join(''))

MDEwYzQyNmY2MjczMjA1MjY1NjM2ZjcyNjQ3MzAyMGYzMzMxMzAzMTMyMzIzMzM5MzMzNTMwMzAzMDMwMzMwMzE0MzIzMDMyMzIyZDMwMzQyZDMyMzU1NDMxMzUzYTMzMzAzYTMwMzA1YTA0MDczMTMwMzAzMDJlMzAzMDA1MDYzMTM1MzAyZTMwMzA=

I get the base64 string above. When I set it as the value of the qrcode and try to scan it, I get errors and I do not know where I am missing it.

Can I use async/await in Jest, when the tested function is not using async/await?

I have a simple controller for adding new users. After the successful resolution (user added), the controller sends a 202 response. As you can see, the function is promise based and is not using async/await.

const addUserController = function (req, res, next) {
    Users.addOne(req.userid, req.body.email)
    .then(() => {
      res.status(202).send();
    })
    .catch((err) => {
      console.log(err);
      res.status(500).json({ message: "Internal server error." });
    });
};

When I am testing this function in Jest with the, the function executes immediately, without going to the then() part, resulting in a mistaken 200 code, instead of 202, so the following test fails:

it("Should add a user", () => {
    let req, res, next, pool;
    pool = new Pool();
    req = httpsMocks.createRequest();
    res = httpsMocks.createResponse();
    res.next = null;
    req.userid = 1;
    req.body = {
      id: 2
    }
    pool.query.mockResolvedValue({rows:[], rowCount: 1});
    apiController.addUserController(req, res, next);
    expect(res.statusCode).toBe(202);
    expect(pool.query).toBeCalledTimes(1);
});

However, when I make it like that:

it("Should add a user", async () => {
    let req, res, next, pool;
    pool = new Pool();
    req = httpsMocks.createRequest();
    res = httpsMocks.createResponse();
    res.next = null;
    req.userid = 1;
    req.body = {
      id: 2
    }
    pool.query.mockResolvedValue({rows:[], rowCount: 1});
    await apiController.addUserController(req, res, next);
    expect(res.statusCode).toBe(202);
    expect(pool.query).toBeCalledTimes(1);
});

that is I add async/await, it works alright – the response status code is 202, meaning the function was awaited and the test passes.
But why? When I hover over the newly added ‘await’ VS code is suggesting that

‘await’ has no effect on the type of this expression.

Well it makes sense – it should have no effect, as the tested function is not async, so it shouldn’t work, but well, it works – only when I add the async/await to the Jest function it works fine.

Could someone explain this to me?

Play/Pause doesn’t work with useEffect and using setInterval

Here is my code. Whenever I play the start button, it spasms out. Any help would be appreciated! I’m wanting to, whenever I press the button, a timer for 1 second to count down based on the truthiness of isPlaying.

const [onBreak, setOnBreak] = useState(false) 
  const [isPlaying, setIsPlaying] = useState(false)

  useEffect(() => {
    const timerFunc = setInterval(() => {
    setIsPlaying(!isPlaying)
    if (!onBreak) {
      if (sessionSec === 0 && sessionMin !== 0) {
        setSessionSec(59)
        setSessionMin(sessionMin - 1)
      } else if (sessionSec !== 0 && sessionMin !== 0)  {
         setSessionSec(sessionSec - 1)
      } else if (sessionSec === 0 && sessionMin === 0) {
        setOnBreak(true)
      }
    } else if (onBreak) {
        if (breakSec === 0 && breakMin !== 0) {
        setBreakSec(59)
        setBreakMin(breakMin - 1)
      } else if (breakSec !== 0 && breakMin !== 0) {
         setBreakSec(breakSec - 1)
      } else if (breakSec === 0 && breakMin === 0) {
        setOnBreak(false)
      }
    } else {
  clearInterval(timerFunc)
  }
  }, 100);
  }, [isPlaying]);

    <button onClick={() => setIsPlaying(!isPlaying)}>{isPlaying ? 'Pause': 'Play'}</button>

Axios request returning undefined

So I have made a custom hook for fetching and I’m trying to use that hook and filter some stuff from it using my params. But the fetch returns undefined firstly which actually breaks my code.

Custom Hook code

import axios from "axios";
import { useState, useEffect } from "react"

export const useFetch = (url) => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    const [error, setError] = useState('')


    const getData = () => {
        setLoading(true)
        try {
            axios.get(url)
                .then(response => {
                    setData(response.data);
                    setLoading(false)
                })
          } catch (error) {
            setError(error)
          }
    };

    useEffect(() => {
        getData()
    }, [url])

    return {loading, data, error}

}

Code where I’m trying to use the fetch

import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useFetch } from '../custom_hooks/useFetch';

const PersonDetails = () => {

    const { loading, data , error } = useFetch('https://randomuser.me/api?results=20');
    const { results } = data;
    const { id } = useParams();

    const [person, setPerson] = useState({})

    useEffect(() => { 
        const newPerson = results?.find(person => parseInt(person.login.uuid) === parseInt(id))
        console.log(newPerson)
        setPerson(newPerson)
    }, [])

    return (
        <div>
            Testing
        </div>
    )
}

export default PersonDetails

Mirage JS json data is console logging but not rendering on the page in React

I am working on a coding assessment and running into a problem when it comes to rendering dummy data from Mirage JS on my page. When I console log the data I’m looking for it shows up fine in the console but I can’t figure out why it’s not rendering on the page.

Here’s the server.js

import { createServer, Model } from "miragejs";
import faker from "faker";
import avatar from "./avatar.png";

export function makeServer({ environment = "test" } = {}) {
  let server = createServer({
    environment,
    models: {
      employee: Model,
    },
    seeds(server) {
      for (let i = 0; i < 10; i++) {
        server.create("employee", {
          id: faker.datatype.uuid(),
          firstName: faker.name.firstName(),
          lastName: faker.name.lastName(),
          email: faker.internet.email(),
          phone: faker.phone.phoneNumber(),
          bio: faker.lorem.paragraph(),
          avatar: avatar,
          address: {
            streetAddress: `${faker.address.streetAddress()} ${faker.address.streetName()}`,
            city: faker.address.city(),
            state: faker.address.stateAbbr(),
            zipCode: faker.address.zipCode(),
          },
        });
      }
    },
    routes() {
      this.namespace = "api";
      this.get(
        "/employees",
        (schema) => {
          return schema.employees.all();
        },
        { timing: 1000 }
      );
      this.patch(
        "/employees/:id",
        (schema, request) => {
          const attrs = JSON.parse(request.requestBody);
          const employee = schema.employees.find(request.params.id);
          employee.update(attrs);
        },
        { timing: 300 }
      );
      this.delete(
        "/employees/:id",
        (schema, request) => {
          const employee = schema.employees.find(request.params.id);
          employee.destroy();
          return new Response();
        },
        { timing: 300 }
      );
    },
  });
  return server;
}

and here’s the app.js

import { makeServer } from "./server";
import { useEffect, useState } from "react";

if (process.env.NODE_ENV === "development") {
  makeServer({ environment: "development" });
}

function App() {
  const [employees, setEmployees] = useState([])

  useEffect(() => {
    fetch('/api/employees')
    .then(res => res.json())
    .then(json => setEmployees(json.employees)
    )
  }, [])
  return (
    <div>
      <header>
        <h1>Employees</h1>
      </header>
      {employees.length > 0 ? (
        <table>
          <thead>
            <tr>
              <th>id</th>
              <th>first name</th>
              <th>last name</th>
            </tr>
          </thead>
          <tbody>
            {employees.map(({id, firstName, lastName}) => {
              <tr key={id}>
                <td>{id}</td>
                <td>{firstName}</td>
                <td>{lastName}</td>
              </tr>
          console.log(firstName)
            })}
          </tbody>
        </table>
      ) : (
        <p>No employees</p>
        )}
  </div>
  );
}
export default App;

Create a styling rule for clsx for React + Typescript

Having this clsx method which works fine:

const getLinkClasses = (disabled: boolean) => {
  return clsx('flex whitespace-nowrap', {
    'text-gray-500': !disabled,
    'text-gray-300 cursor-not-allowed': disabled
  });
};

There are two other optional variables, one for disabled and one for !disabled that are strings and can add new rules to the above method. Let’s call them disabledValue and notDisabledValue.

For example,

const disabledValue = 'bg-red-100'; 
const notDisabledValue = 'bg-green-100';

In order to add those variables, I’ve made the following changes:

export interface MyProps {
  disabledValue?: string;
  notDisabledValue?: string;
}

const getLinkClasses = (disabled: boolean, style: MyProps) => {
  const notDis = `text-gray-500 ${style.notDisabledValue ?? ''}`;
  const dis = `text-gray-300 cursor-not-allowed ${style.disabledValue ?? ''}`;

  return clsx('flex whitespace-nowrap', {
    notDis: !disabled,
    dis: disabled
  });
};

The problem is that those two variables, notDis and dis aren’t read:

‘notDis’ is declared but its value is never read.ts(6133)

‘notDis’ is assigned a value but never
used.eslint@typescript-eslint/no-unused-vars

Is there a way to fix it?

Pass Javascript Array containing multiple files to PHP

I would like to send Javascript array containing files to PHP using AJAX

The following are 3 files that I want to send to the php side. (These outputs come from console.log(document.getElementById("id").files[0]);

File { name: "img1.svg", lastModified: 1641853737982, webkitRelativePath: "", size: 2506, type: "image/svg+xml" }
File { name: "img2.svg", lastModified: 1641853677323, webkitRelativePath: "", size: 1060, type: "image/svg+xml" }
File { name: "img3.svg", lastModified: 1641853656789, webkitRelativePath: "", size: 1845, type: "image/svg+xml" }

In this case there are 3 files (There can be more or less than that).

The 3 files are in a variable arrFiles.
So console.log(arrFiles) outputs:
Array [ File, File, File]

JQuery file

var form_data = new FormData();
var arrFiles = JSON.stringify(arrFiles)
form_data.append("imgs", arrFiles);

$.ajax({
    url:url,
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    success:function(data)
    {
        alert(data);
    }
}); 

php file

if(isset($_POST["imgs"])){
    //Would like to handle each image separately.
    $imgs = json_decode($_POST['imgs']);


    //May be something like :
    foreach($_POST["imgs"] as $img){
        $movePath = "images/".$img['name'];
        move_uploaded_file($img["tmp_name"], $movePath);
    }
    return;
}

Is there a way to handle this ?

Best way to Search ALL Terms in Array of Objects

I’m trying to filter out objects based on whether ALL the given search terms exist in SOME of the property values of EACH object in the array.
But I also don’t want to search within the deviceId property.

But is there a way to do it with less code?

So I do the following:

  1. Convert the objects into iterable arrays
  2. Filter out the array to remove arrays withdeviceId
  3. Convert the arrays back into the Key/Value pair objects
let DeviceDtoArrayOfArray = [];

DeviceDtos.forEach((indiv) => {
  DeviceDtoArrayOfArray.push(Object.entries(indiv));
});
let DeviceDtoArrayOfArrayFiltered = [];
DeviceDtoArrayOfArray.forEach((indiv) =>
  DeviceDtoArrayOfArrayFiltered.push(
    indiv.filter((indiv) => indiv[0] !== "deviceId")
  )
);

let DeviceDtoArrayOfArrayFilteredObjects = [];

DeviceDtoArrayOfArrayFiltered.forEach((indiv) => {
  DeviceDtoArrayOfArrayFilteredObjects.push(Object.fromEntries(indiv));
});
  1. Define sample search term array
  2. For each object from Step 3, create an array of it’s property values
  3. Filter each Object in the array by searching each Search Term, check to see if it exists within some of the property values from Step 5, if it exists, then the object is returned to a new array, if not, it’s filtered out

Sample Array containing the objects with deviceId

const DeviceDtos = [
  {
    deviceId: 1,
    deviceName: "Device0000",
    hwModelName: "Unassigned",
    deviceTypeName: "Unassigned",
    serviceTag: "A1A"
  },...

Sample Search Terms

const searchTerms = ["HwModel", "A1A"];

Filter out objects based on Search Terms

const results = DeviceDtoArrayOfArrayFilteredObjects.filter((indiv) => {
  const propertiesValues = Object.values(indiv); // all property values

  return searchTerms.every((term) =>
    propertiesValues.some(
      (property) => property.toLowerCase().indexOf(term.toLowerCase()) > -1
    )
  );
});

console.log(results);

SMTP mails going to spam folder

I am using JavaScript to automate sending emails on my website, with SMTP and a gmail email address however the emails are sent directly to the receivers spam folder. Is there a way around this?

Here is my code:

   function sendEmail() {

      Email.send({
        Host: "smtp.gmail.com",
        Username: "[email protected]",
        Password: "pass",
        To: document.getElementById('email').value,
        From: "[email protected]",
        Subject: "Subject",
        Body: "hooray",
      })
        .then(function (message) {
          alert("mail sent successfully")
        });
    }

Is there an efficient way to show images based on a route and file name using javascript?

Right now I have something like

const route = '/Images/Banner/'
const slides = [
  {
      name: "banner-01",
      url: `${route}banner-01.png`
  },
  {
      name: "banner-02",
      url: `${route}banner-02.png`
 
  },
  {
      name: "banner-03",
      url: `${route}banner-03.png`
  },
]
]

In this, I’m manually adding each image and it’s properties because there are only 3 images, but i want to dynamically add them based on the quantity of images with the same name (they’ll always are going to be named banner-NN).

Is there an efficient way to iterate through images with the same pattern of name (‘banner-‘) and place them in an array of objects?