Comparing a string to JSON values?

I have an incoming filename and I want to be able to glean and pass along helpful information to the user.

The filename will come through as something resembling: XYZStatsSyllabus2023.docx

I’m trying to analyze incoming filenames to figure out 1) what class it might belong to and 2) what document type it may be.

I have a JSON file with just about 150 classes, each with a short name (ex: Stats) as the key, a long name (ex: Statistics), a course code (ex: MT105), and an acronym (ex: STAT). The JSON information is as shown below.

{
    "Course":{
        "Stats":{
            "name": "Statistics",
            "code": "MT105",
            "acronym": "STAT"
        },
        "Lit":{
            "name": "Literature",
            "code": "EN102",
            "acronym" : "LITR"
        },
        "Hist":{
            "name": "History",
            "code": "HT101",
            "acronym": "HIST"
        }, 
        "Gov":{
            "name": "Government",
            "code": "PS101",
            "acronym": "GOVT"
        }
    }
}

The information contained in the filename will always contain one of the three entries. I want to be able to regex the filename to see if it matches any of the name, code, or acronym and if it does, then I want to be able to pass to the user the key of the total course information. If a filename contains MT105, I want to tell the user that it belongs to “Stats”, if it contains “History”, I want to return “Hist”.

I have experience iterating through an object like “Course” and then picking a match and iterating through that, but how would I go about matching a string to JSON when I essentially need to iterate through “Course” and then I’d have to iterate through its children and if I find a match, then I return the key value. Surely there has to be a better way?

I have tried iterating through “Course” and then through each child’s children. It is a very round about way to go about it and it doesn’t always work.

RTK QUERY add params to query only if not null

I have query with several params, and I want to add params to query only if is not null.

Only thing I came up with create params object and conditionally add properties, but adding this for every query feels like wrong way. I searched about this in documentation, nothing find
My solution:

query: (category: string | null) => {
        const params: { [key: string]: string } = {};
        if (category !== null) params.category = category;

        return {
          url: "/products",
          params: params,
        };
      },

Microsoft Entra ID Adding Handlers/Data to Request/Response Payload using MSAL

I’ve been pondering a few things on how to use Microsoft Entra, MSAL with an external REST API via Custom Authentication Extension.

My current flow is I want a user to use some JavaScript SPA or something and with MSAL sign-in and auth via Microsoft Entra. Now my question is, what would be the best way in JS code to intercept that request JSON payload to add some data to the payload before it gets sent off to an external REST API for a custom claims provider?

For example the external REST API requires basic authentication via user id/password but it also requires a JSON payload with two specific handlers. How do I best setup my JavaScript SPA via MSAL or other tool to wrap that the request from Entra to the external REST API so it will be properly authenticated?

Prisma’s orm post doesnt work when doing post, see error below

Makinga simple prisma app with express and node, querying a mysql local database.
When doing await prisa.list.create(), it raises and error, see below.

script.js of the html page:

  addItemForm.addEventListener('submit', async (event) => {
    event.preventDefault();
    const itemName = itemNameInput.value.trim();
    console.log(JSON.stringify({ itemName: itemName }))
    if (itemName) {
      try {
        await fetch('/backend/api/add-person', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ itemName: itemName })
        });
        fetchData(); // Refresh the list after adding an item
        itemNameInput.value = ''; // Clear input field
      } catch (error) {
        console.error('Error adding item:', error);
      }
    }
  });

api.js:

  router.post('/add-person', async (req, res) => {
    const  itemName  = req.body.itemName;
    
    try {
      await prisma.list.create({
        data: {
          name: itemName
        }
      });
      res.redirect('/');
    } catch (error) {
      console.error(error);
      res.status(500).send('Error adding item to database');
    }
  });

Error:

   try {
   const  { name }  = req.body
   await prisma.list.create({
         data: {
       +   name: String
         }
       })

Argument name is missing.

Client-side site search using combobox, most performant way to get the indexed results

I’m implementing a site search in a site I have built. The site uses the JAM stack (11ty & Netlify) and I’m unsure which strategy to use for grabbing the query data.

It’s a basic combobox pattern, user types n characters, I filter the Post titles and also Categories against their input string (I’ve merged these two collections), When they click on an item after filtering, it navigates to the page they want.

I have a Nunjucks file where I have built a simple JS array of HTML strings.

The Nunjucks file outputs a JS file which is stored in the project root. Each item in that array is basically like so

<li><a href="/my-first-post/">My first post<span class="search__item-type"> Post</span></a></li>
<!-- Several attributes omitted for brevity -->

I append those items to a <ul> element on an input event, I will limit how many are displayed in the list to something sensible, perhaps 10.

Currently, there are around 120 items in the generated JS file and this will of course grow steadily over time.

I’ve tried 2 ways thus far (both work):

Initially it was a JS object, without HTML strings, I used template literals in the search.js file and pushed them to a new array, but I kinda figured it would be more performant to let the template do that, to take some weight of the client???

So, I ended up with my current array, which I export into my search.js file

I’m fine with actually building the search functionality, I’ve done a few before, but they have either been just practice efforts where I’m grabbing the data from an array in the same JS file or I’ve been using temporary mock data and then other teams have added the integration, I’ve just built the frontend and functionality, they have dealt with the API.

I need this to be as performant as possible, so ideally I don’t want the user downloading this file unnecessarily if I can avoid that, as not all users will want to use the search. As it is a module, I can see it is still downloaded in the Network tab, so perhaps this isn’t the way to go???

I also need full access to this locally, whilst I’m building it, as accessibility is the priority and I need to test it to death, before it ever sees the light of day.

So, what would be the best way:

  • Continue down my current path, a large array of HTML list items with all the attributes I need and just insertAdjacentHTML should a user trigger an input event, then do my string comparison and everything else
  • Revert back to my initial idea, just store it as an object and build the items’ HTML on the fly, that would of course reduce the imported file size, but I’d still be building those strings anyway, so I dunno :/
  • Use an interchange format, such as JSON or something else
  • Something else entirely

Thanks for reading

Why isn’t event.preventDefault not working

This question has been asked, and answered before, none of the preivous answers given here seems to fix my situation however and therefore I need to ask, once again, why isn’t the event prevented correctly?

document.addEventListener("input", event => {
   if(event.data == '#' || event.data == '+' || event.data == '.' || event.data == ';'){
       event.preventDefault();
       alert("Non-allowed character detected: " + event.data);
       return false;
    }
});

I have tried different versions, for example I added the event.stopPropagation() and event.stopImmediatePropagation() but nothing changed. What am I doing wrong and how do I fix it?

It might help to know that I’m simply trying to stop the input of certain characters.

Thanks in advance

React State returns empty array when accessed within a specific function, but a full array when accessed immediately before and after

I am creating a web app that allows you to search for Spotify tracks and add them to a playlist. I have created an array of <Track /> components called playlistTracks using useState. In my addSong function, I am trying to implement a check to see if the track already exists in the playlist so you can’t add a duplicate, so I am calling playlistTracks.some() to iterate through the array and set trackExiststo true if the track already exists in the playlist. My problem is that the playlistTracks state is always empty when this function is called, even when I have already added songs and they are visibly rendered on the playlist section of the web app. I know it is empty because I call console.log("Current playlist tracks:", playlistTracks.map(track => track.props.accessKey)); inside the method and it returns an empty array.

addSong is called from the onClick event of a <p> component on each Track.

Here is a snippet of my code with all irrelevant lines removed.

function App() {

const [playlistTracks, setPlaylistTracks] = useState([]);

useEffect(() => {
  console.log("Current playlist tracks after update:", playlistTracks.map(track => track.props.accessKey));
  setAccuratePlaylistTracks(playlistTracks);
}, [playlistTracks]);

const addSong = useCallback((name,artist,album, albumCover, songId) =>{

  console.log("Current playlist tracks:", playlistTracks.map(track => track.props.accessKey));

const trackExists = playlistTracks.some((track) => 
  track.props.accessKey ===songId
)

if(!trackExists){
  setPlaylistTracks((prev) => [
    ...prev,
    <Track 
    key = {songId} 
    accessKey = {songId} 
    song = {name} 
    artist = {artist} 
    album = {album} 
    albumCover = {albumCover} 
    isAdd = {false} 
    removeSong = {removeSong}
    />
  ]);
  }else{
    console.log('track already in playlist');
  }
},[playlistTracks]);

return (
    
      <ResultsSection trackList = {trackList} playlistTracks = {playlistTracks} />
  );
}

const ResultsSection = ({trackList, playlistTracks}) => {
    
    return(
            <Playlist playlistTracks = {playlistTracks}/>
    );
}
const Playlist = ({playlistTracks}) =>{

    return (
            <ul className = {styles.playlistTracks}>{playlistTracks}</ul>
    )
}

const Track = (props) =>{
    
const [trackName, setTrackName] = useState(props.song)

    const [artist, setArtist] = useState(props.artist)
    const [album, setAlbum] = useState(props.album)
    const [albumPic, setAlbumPic] = useState(props.albumCover)
    const [isAdd, setAdd] = useState(true);
    const [songId, setSongId] = useState(props.accessKey);
   
useEffect(()=>{
    if(!props.isAdd){
        
        setAdd(false);
    }
},[])
    

    const addHandler = () =>{
        console.log('ADD HANDLER');
        props.addSong(trackName, artist, album, albumPic, songId)
    }

    return(
            {isAdd
            ?<p id = {styles.add} onClick={addHandler}>+</p>
            : <p id={styles.add} onClick={() => props.removeSong(props.accessKey)}>-</p>
}
    );
}

I suspected it might be an asynchronous issue, so I created a useEffect that prints the current state of the playlistTracks array after each rerender of the app component. It prints a full array immediately before and after the addSong method is called. Per the advice of chatGPT, I also tried using useCallback on the addSong function, which did not change anything (this is the current state of the code, I was having the same issue before I made it a useCallback). There is no where else in my code where I set the state of playlistTracks. The current functionality of the code is that it will add the track to the playlist and render it on the screen even if it already exists in the array, and give me a warning that two elements in the array have the same key.

Thank you for the help and please let me know if there is any way I can improve this question.

Passing data from the active tab in chrome extension

I am a newbie creating an extension.

I wanted to send window.document from an active tab to my react app. I am doing it like below:

manifest.json

{
  "manifest_version": 3,
  "name": "UI ",
  "description": "test",
  "version": "1.0",
  "action": {
    "default_popup": "index.html"
  },
  "permissions": ["activeTab", "storage"],
  "content_security_policy": {
    "extension_pages": "default-src 'self'; connect-src https://* data: blob: filesystem:;"
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

// content.js

// Send the document content to the background script
chrome.runtime.sendMessage({
  action: "getDocumentContent",
  content: document.documentElement.outerHTML,
});

// background.js

// Function to handle messages from content script
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.action === "getDocumentContent") {
    // Update the state with the document content received from content script
    chrome.storage.local.set({ documentContent: message });
  }
});

And then in my react hook:

import { useEffect, useState } from "react";
import { displayChildTagNames } from "./utils";

export const useNodes = (setActiveTag: any) => {
  const [nodes, setNodes] = useState<string | null>(null);

  useEffect(() => {
    if (chrome.storage) {
      // extension
      chrome.storage.local.get("documentContent", function (data) {
        setNodes(data.documentContent.content || "");
      });
    } else {
      // locally
      setNodes(document.documentElement.outerHTML || "");
      console.error("chrome.storage is not available.");
    }

    return () => {
      setNodes(null);
    };
  }, []);

  const jsxTags = displayChildTagNames(nodes ?? "", setActiveTag);

  return jsxTags;
};

It is more or less working but not as I expect. It is sending the window.document but only from the 1st tab I open. Even if I switch the tab and open the extension I see window.document from the 1st opened tab.

It means that the content.js run only once? How to sync to that to send it every time I switch the tab?

Why is my browser not setting the cookie it receives from my backend?

I am trying to set a cookie that contains a jwt token after a successful login to the client but when the browser receives it, it doesn’t get set. I know that the response contains a cookie is received because part of the response headers is “Set-Cookie”.

This is my code from the backend that sets the cookie:

res.cookie('jwtToken', token, {
      httpOnly: true,
      secure: true,
      sameSite: 'None',
      maxAge: 3600000
    })

Here’s the response headers:

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: https://localhost:3000
Vary: Origin
Access-Control-Allow-Credentials: true
Set-Cookie: jwtToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY1Zjg0NjFhMzYwZmU3MjlmZjIxMzVmYiIsInVzZXJuYW1lIjoidGVzdCIsImlhdCI6MTcxMDc3Mjk2OCwiZXhwIjoxNzEwNzc2NTY4fQ.oV49HPeJZtk3Vsc__xTecU8yWbcD_QJdCubtD3Ppgs0; Max-Age=3600; Path=/; Expires=Mon, 18 Mar 2024 15:42:48 GMT; HttpOnly; Secure; SameSite=None
Content-Type: application/json; charset=utf-8
Content-Length: 294
ETag: W/"126-2EE1HbPx1KFS/evxa+82EKfejss"
Date: Mon, 18 Mar 2024 14:42:48 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Some details that might be important:

  1. I’m using express for the backend and react the frontend.

  2. My backend and frontend have different ports but I have made sure to setup CORS properly along with a credentials: include option.

  3. I have the cookie-parser middleware setup to enable me to set cookies.

  4. I check for the cookie through another route that is supposed to parse the cookie from the req headers however the it always ends up being undefined. (I’ve made sure to include credentials when making the request)

Initially I though the problem could be related to my frontend and backend not being ran over https so I have created certificates for it using mkcert however this does not fix the issue.

How can I display input from a to an html page that mimics the format of a word document?

Main problem: Convert a word document template into a responsive webpage that can be viewed on any device and keep the formatting. Sections of the template must be hidden from those who are not authorized to see some of the content and be able to download a copy of the report for future reference.

I have completed the log-in page, menu and submit form. I would like to get the input from that form to appear on a page that looks like the word document (but responsive), have a page displaying links to the reports and be able to download them for whoever wishes to for future reference.

I am not savvy with PHP, or Javascript or other such languages. In fact, I am not sure if even what I require is even possible.

I am trying to make this as plug and play as possible, then hand over to the company’s IT department with specific instructions to add it to our online presence that that it can be viewed while not connected to the internal network.

how to achieve msal azure ad b2c in react native

  const config = {
    issuer:
      'https://zoomonlineb2c.b2clogin.com/zoomonlineb2c.onmicrosoft.com/B2C_1_MobileSignup_in/v2.0',
    clientId: '83c5579e-d55b-4647-8c93-b66ee2961f49',
    redirectUrl:
      'com.ztg.zoomonline://com.ztg.zoomonline/android/callback/', // the redirectUrl must end with a slash
    scopes: ['openid', 'offline_access'],
  };

  const auth = await authorize(config);
  console.log('auth :>> ', auth);

Need to handle the azure ad b2c in react native

i am tring the build an authentication system with node.js but the veriable storing verification codes sundenly becomes an empty object

i am trying to build and authentication system and when i save the generated otp in a veriable called verificationcodes it will save, but will become an empty object of verifyOTP function is called. this doesnt happen when testing with postman. but it hapens when testing with react-native andriod emulator

const nodemailer = require( 'nodemailer' );
const speakeasy = require( 'speakeasy' );
require( 'dotenv' ).config();




const verificationCodes = {};





const transporter = nodemailer.createTransport( {
    host: 'smtp-relay.brevo.com',
    port: 587,
    secure: false,
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
    }
} );

const sendEmail = async ( emailOptions ) =>
{
    try
    {
        await transporter.sendMail( emailOptions );
        console.log( 'Email sent successfully' );
    } catch ( error )
    {
        console.error( 'Error sending email:', error );
        throw new Error( 'Failed to send email' );
    }
};

const generateOTP = () =>
{
    return speakeasy.totp( {
        secret: speakeasy.generateSecret().base32,
        digits: 6,
        step: 300,
    } );
};


const sendVerificationCode = async ( email, whatToVerify ) =>
{
    const otp = generateOTP();

    const emailOptions = {
        from: '[email protected]',
        to: email,
        subject: 'OTP Verification',
        text: `Hello dear,

Thank you for signing up with TripTrack! Your OTP for email
verification is: ${ otp }.

This OTP will expire in 10 minutes. If you didn't request this, you can safely ignore this email.

Best regards,
The TripTrack Team`,
    };


    verificationCodes[ email ] = {
        otp,
        expiry: Date.now() + 600000,
        whatToVerify: whatToVerify
    };

    await sendEmail( emailOptions );
    console.log( verificationCodes );
};




//verify

const verifyOTP = ( email, otp ) =>
{
    console.log( "here====>", verificationCodes );

    if (
        !verificationCodes[ email ] ||
        verificationCodes[ email ].otp !== otp ||
        verificationCodes[ email ].expiry < Date.now()
    )
    {

        return { status: false };
    }

    //delete verificationCodes[ email ];
    const whatToVerify = verificationCodes[ email ].whatToVerify;
    return { status: true, whatToVerify };
};

module.exports = { sendEmail, sendVerificationCode, verifyOTP };

i tried using postman and it worked but wont work on android device or emulator

Regex to limit numbers between 0 and 100, and with up to 2 decimals

I’m unable to do or find a regex that allows me to insert in an input numbers between 0 and 100, and also allow to insert up to 2 decimals.

I can have them for separated but can’t merge them. I’m starting to think that there is an inconsistence

  const VALIDATION = {
    ONLY_NUMS: (value: string) => /^[0-9]*$/.test(value),
    BETWEEN_0_AND_100: (value: string) => /^(d{0,2}([.,]d{1,2})?|100([.,]0{1,2})?)$/.test(value),
    FLOAT_NUMS: (value: string) => /^-?[0-9]*((?<=d).(?=d))?[0-9]*$/.test(value) && value !== '-',
  };

Passing id params to backend MySQL results in undefined value

i’ve been developing a blog website, and now, putting the comments system. The comments sends to a backend mysql, with an ID as a foreign key of the corresponding blog Id. The ID is extracted of the useParam hook, when i click to a blog, the url changes to the blog ID, and the commens system use that param to send it, with name and the comment, to the backend.
This is managed by a POST request, that works perfectly when i try to do this with the vs code extension thunder client. But when i do with the web, pass to the backend, the name, comment, but the id, sets undefined.
The useParams hook works perfectly, console.log shows the ID, but pass undefined to the backend.
Here some proofs:
thunder client post request

pass name, comment, but id undefined

Here is my Fullpost code, that shows the particular blog:

function Fullpost() {
  var { id } = useParams();

  const [name, setName] = useState('')
  const [comment, setComment] = useState('')

  const handleSubmit = async (e) => {
    e.preventDefault()
    await createCommentRequest(targeted)
  }
  const targeted = {id: id, name: name, comment: comment}

  return (
    <>
        {blogs.filter(e => e.id == id).map(e => (
            <div className="blogs">
                <h1>{e.post}</h1>
                <h2>{e.name}</h2>
                <p><small>{e.createAt}</small></p>
            </div>
        ))}
        <hr />
        <form className="comment" onSubmit={handleSubmit}>
          <input type="text" placeholder="nombre..." onChange={(e) => setName(e.target.value)}/>
          <input type="text" placeholder="comenta..." onChange={(e) => setComment(e.target.value)}/>
          <button type="submit">comentar</button>
        </form>
    </>
  )
}

The createCommentRequest():

import axios from 'axios'

export const createCommentRequest = async (comment, id) => {
    await axios.post(`http://localhost:4000/blogs/${id}`, comment)
}

The create comment function:

export const addComment = async(req, res) => {
    const {name, comment} = req.body
    const [result] = await pool.query(`INSERT INTO comments (id, name, comment) VALUES (?, ?, ?)`,[
        req.params.id, name, comment
    ])
    return res.json({
        id: result.insertId, name, comment,
    })
    console.log(result)
    res.send('creando comentario')
}

Any response will be received

Creation of a google sheets file with an integrated script from google apps script

Hi everyone

So what I’m trying to do, or even know if it is possible, would be to have an Apps Script file that generates a Sheets file (this part is easy) with an integrated Apps Script, or an Apps Script file that would be linked to it.

By hand, without using apps script this is pretty simple:

  • Create a new sheets file

  • Extension > Apps Script

  • Paste code here

But I need this to be automated inside a “mother” Apps Script so I can deploy it at a large scale, and generate a bunch of sheets with scripts in it.

The integrated apps script would be pretty simple, just a few lines, to gather some data and send e-mails, with a trigger “on edit”, but that’s not the issue. What’s hard is to create an apps script from apps script.

Thanks a lot!