Node js sending thousands of requests and handle data the most performance way

I had express server with service which is doing legal scrapping. He is sending many requests , then handle data , parse it and give it to another service.

I heard about that fastify is much faster than express so i changed to fastify , added some perfomance now- logging, but i dont see any diffrence. I was trying to change fetch to axios but still i don’t see diffrence. In my case there is simple for in loop with pages number index. Any idea how i can can more performance in fetching data?

Overlay play button doesn’t show/disappears (Vimeo iframe)

Stackoverflow forced me to copy/paste my code from CodePen but as you can it’s not working properly here so please go to CodePen to see what I mean.

This is my CodePen and I’m in a pickle…

It’s all about my OVERLAY PLAY BUTTON.

  1. When loading the page for the first time, my Vimeo iframe works ok.

    a) You can press ‘play’/’pause’ Vimeo button and my OVERLAY PLAY BUTTON shows/disappears

    b) You can click wherever you want to play/pause and my OVERLAY PLAY BUTTON shows/disappears

    c) You can click on my OVERLAY PLAY BUTTON and it’ll start video (and disappears itself) and when you click one more time, it’s again visible and pauses video.

  2. And now the problem: When you go from main video and click for example on VIDEO ONE (I’m replacing .src to a new video):

    a) You can press ‘play’/’pause’ Vimeo button but my OVERLAY PLAY BUTTON doesn’t disappear

    b) You can click wherever you want to play/pause but my OVERLAY PLAY BUTTON doesn’t disappear

    c) You can click on my OVERLAY PLAY BUTTON and it’ll start video and disappears itself but it won’t show up again.

And same thing happens when you go to VIDEO TWO/THREE.
Any advice appreciated!

PS. Unfortunately I couldn’t copy/paste my code here in the Javascript/html/css snippet because it wasn’t showing properly (and I added external libraries but still didn’t work).

const player = document.getElementById("myFrame");
const vimeoPlayer = new Vimeo.Player(player);
const videoPlayer = document.querySelector("#videoPlayer");
const playButton = document.getElementById("playButton");


playButton.onclick = function () {
    playButton.style.visibility = "hidden";
    vimeoPlayer.play();
}

vimeoPlayer.on("pause", function () {
    playButton.style.visibility = "visible";
});
vimeoPlayer.on("play", function () {
    playButton.style.visibility = "hidden";
});


function video1() {
  playButton.style.visibility = "visible";
    player.src = "https://player.vimeo.com/video/103825397?h=96ccc46aec";
}

function video2() {
  playButton.style.visibility = "visible";
    player.src = "https://player.vimeo.com/video/120445953?h=60ce266812";
}

function video3() {
  playButton.style.visibility = "visible";
    player.src = "https://player.vimeo.com/video/19095427?h=e953238ac5";
}
#videoContainer {
  background-color: black;
  border: none !important;
  display: flex;
  flex-flow: row wrap;
  justify-items: center;
  align-items: center;
}

#playButtonContainer {
  border: none !important;
  width: 100vw;
  position: absolute;
  z-index: 2;
  cursor: pointer;
  background-color: transparent !important;
}

#playButton {
  max-width: 150px;
  visibility: visible;
  position: absolute;
  left: 50%;
  top: 10%;
  transform: translate(-50%, -100%);
}

.containerItems {
  overflow: hidden;
}

.video_thumbnails {
  width: 100%;
  transition: 0.5s ease all;
  display: block;
  width: 100%;
  height: auto;
}

#videoPlayer {
  margin: 0 auto;
  width: 50%;
  background-color: black;
}

.containerOverlay {
  position: relative;
  width: 33.333%;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  transition: 0.5s ease;
  background-color: black;
  cursor: pointer;
}

.containerOverlay:hover .overlay {
  opacity: 0.8;
}

.text {
  font-size: 1.5rem;
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
    <script src="https://player.vimeo.com/api/player.js"></script>

<div id="videoContainer">
        <button id="playButtonContainer">
            <img src="https://i.etsystatic.com/10919371/r/il/155a7d/1563938723/il_fullxfull.1563938723_1rmr.jpg" id="playButton">
        </button>
        <div id="videoPlayer" class="ratio ratio-16x9">
            <iframe id="myFrame" src="https://player.vimeo.com/video/187793661?h=583b79a3b7"
                title="Vimeo video player" frameborder="0" autoplay=1
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                allowfullscreen></iframe>
        </div>
    </div>

<div class="containerItems text-center">
    <div class="row g-0">
        <figure class="containerOverlay">
            <img src="https://wallpapers.com/images/high/720p-9wear5v9icennc9q.webp" class="video_thumbnails">
            <button class="overlay" onclick="video1()">
                <div class="text">Video One</div>
            </button>
        </figure>
        <figure class="containerOverlay">
            <img src="https://wallpapers.com/images/high/720p-xdq1aa1akvqrswa4.webp" class="video_thumbnails fade-in">
            <button class="overlay" onclick="video2()">
                <div class="text">Video Two</div>
            </button>
        </figure>
        <figure class="containerOverlay">
            <img src="https://wallpapers.com/images/high/720p-n2mogpb8nf78saq2.webp" class="video_thumbnails">
            <button class="overlay" onclick="video3()">
                <div class="text">Video Three</div>
            </button>
        </figure>
    </div>
</div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8" crossorigin="anonymous">
        </script>

Exporting a GLB model out of three.js that is in an Electron application:

I am not even sure if exporting out of THREE in an Electron app is possible.

I cannot find any other instances of people trying it and having issues. My code, I believe is the most up to date as of right now that should work and it does work in the examples on the THREE site.

And this exact code has worked in a stand alone THREE deployment on a site. So I am thinking I am missing something having to do with it being embedded in an Electron app.

Here is my code.

The *exportButton *is a html button the page/window that is referencing the THREE code.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//    Export the model
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
exportButton.addEventListener('click', download);

//exportButton.click = 
function download() 
{
    const exporter = new THREE.GLTFExporter();

    exporter.parse(
        scene,
        function (result) {
            console.log(result);
            saveArrayBuffer(result, 'scene.glb');
        },
        function ( error ) {
        console.log( 'An error happened' );
        },
        { 
            binary: true 
        }
    );
}

function saveString( text, filename ) 
{
    save( new Blob( [ text ], { type: 'text/plain' } ), filename );
}

function saveArrayBuffer(buffer, filename) 
{
    save(new Blob([buffer], { type: 'application/octet-stream' }), filename);
    //save(new Blob([buffer]), filename);
}

const link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link); // Firefox workaround, see #6594 

function save(blob, filename) 
{
    link.href = URL.createObjectURL(blob);
    link.download = filename;
    link.click();

    // URL.revokeObjectURL( url ); breaks Firefox...
}

Property ‘create’ does not exist on type ‘typeof Completions’

I am trying to build something using ChatGPT and I have installed version 4.8.0 (which is the latest).

I am using NextJS.

Last month I built something with v3.something and it worked fine, but now I can’t make this work.

Here is my code:

import OpenAI from "openai";

const instructionMessage = {
    role: "system",
    content:
        "Some instructions",
};

const configuration = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
});

const prompt = "Prompt";
const temperature = 0.7;
const response = await OpenAI.Chat.Completions.create({ //issue lies in this line
        model: "gpt-3.5-turbo",
        message: [instructionMessage, prompt],
        temperature,
        max_tokens: 1000,
    });

I followed every possible documentation (in official docs they have almost the same example) and whatever I do it says “create is not a function”. I tried lowercase also (uppercase is suggested by TS as you may have expected), but nothing is working. I am a bit desperate right now…

Do you have any idea what is wrong here?

Set Leaflet marker to always stay in the middle of the map

I’m working on a SvelteKit project where we’re moving from Google Maps to Open Street Maps using Leaflet.js. With Google Maps we have a marker that always stays in the center of the map even when panning around.

I want to do the same thing with Leaflet. But the marker always stays on the default location on the map.

I currently have the marker defined as such

currentPositionMarker = new L.marker(map.getCenter(), {
  icon: icon // icon is defined earlier in the code
}).addTo(map)

...

function centerMarkerOnMap(map) {
  currentPositionMarker.setLatLng(map.getCenter())
}

...

map.on('moveend', centerMarkerOnMap)

Currently I get Uncaught TypeError: map.getCenter is not a function in the console. I’m not sure why, since I’m using map.getCenter() to set the original marker position with no issues.

I’m open to any and all suggestions. Thanks in advance.

Add a delay before sound is played

I’ve got a bit of Javascript to play an audion on clicking an element:


    const btn1 = document.querySelectorAll(".btn-sound-1");
    let audio1 = new Audio('https://nullsieben.co.uk/74.mp3');

    btn1.forEach(btn => {
        btn.addEventListener("click", () => {
            audio1.play();
        });
    });
   

https://jsfiddle.net/wjq0ydhz/

I’d like to add the following:

  1. Delay from clicking the button until the mp3 starts paying
  2. Is there a way with this code to pre-load the sound so that it definately will when it’s supposed to, regardless of bandwidth etc.?

Png Margin or Border Issue

me and my friends are trying to make a “risk!” tipe of game with a world map and everything on a html page (css js and jq included), we wanted to separate each of the “countries” by using polygons but we found that really long to do and pretty hard, so we thought of using png without background images to do the sections and the borders, problem is, even if an image has no background it still has a “margin” or a trasparent background that makes the “hitbox” of the country way bigger than it should be.
i searched all over the internet but couldnt find nothing

we tried to put the images toghether but ofc it didnt work out.

Json.stringify outputs both index array and default

I am trying to stringify json input file using JSON.stringify method.

Input: [ { “serviceName”: “S1”, “operationName”: “GET /v1/path1/”, “requestJsonPaths”: [], “responseJsonPaths”: [] }, { “serviceName”: “S2”, “operationName”: “POST /v1/path2/”, “requestJsonPaths”: [], “responseJsonPaths”: [] } ]

Output of the stringify method has both indexed array and actual input as default.

{“0”: {“serviceName”:”S1″,”operationName”:”GET /v1/path1/”,”requestJsonPaths”:[],”responseJsonPaths”:[]},
“1”:{“serviceName”:”S2″,”operationName”:”POST /v1/path2/”,”requestJsonPaths”:[],”responseJsonPaths”:[]},
“default”:[{“serviceName”:”S1″,”operationName”:”GET /v1/path1/”,”requestJsonPaths”:[],”responseJsonPaths”:[]},{“serviceName”:”S2″,”operationName”:”POST /v1/path2/”,”requestJsonPaths”:[],”responseJsonPaths”:[]}]}

Above input will be placed in an file called sample.json and string conversion will be done as JSON.stringify(“sample.json”)

My expected output is similar to input instead of adding indexed array. Why stringify method adds index array ? Do I need to set any configuration?

Ayuda con este problema de firebase implementada con un proyecto de ionic [closed]

enter image description hereERROR Error: Uncaught (in promise): FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created – call initializeApp() first (app/no-app).
FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created – call initializeApp() first (app/no-app).
Al intentar hacerle una peticion al firebase me sale ese error, pero si registro un usario por defecto el correo y contraseƱa no me da error

Creo que tiene que ver con la importacion actual de firebase

How to call Shopify metafields for a variant in .js?

Is there any way to call metafields image positions in variants? It works fine in liquid obviously, but I have one function which needs the data as well, but can only be loaded from javascript. I don’t have a problem getting variant.id or featured_image, however metafields I just don’t know what to do.
The liquid code (simplified) which fetches image positions is:

                      {%- for variant in product.variants -%}
                    <option data-image-positions="{{variant.metafields.variant.image_position}}">
                    </option>
                  {%- endfor -%}

Would appreciate some pointers.

Cookies I sent from my nodejs and Express backend are not being added to network requests from the front-end tho they’re visible in the browser

I sent a jwt token as cookies after login. It is visible in the cookies section of the browser but when I make network requests, the cookies is not added to the request as such I’m unable to access protected routes from my frontend. But when I use something like Postman or insomnia, I’m able to access the cookies and access protected routes

My backend login

const login = async (req, res, next) => {
  let { email, password } = req.body;

  email = email.trim();

  if (!email || !password)
    return next(errorHandler(400, "All fields are required"));

  if (email === "" || password.trim() === "")
    return next(errorHandler(400, "No field can be left blank"));
  try {
    const user = await UserSchema.findOne({ email });
    if (!user)
      return next(
        errorHandler(
          404,
          "Incorrect username or password, would you like to sign up instead?"
        )
      );

    if (user.fromGoogle)
      return next(
        errorHandler(403, "You already signed in with a different method")
      );

    const checkPassword = bcrypt.compareSync(password, user.password);

    if (!checkPassword) return next(errorHandler(400, "Wrong password"));

    const accessToken = jwt.sign(
      { id: user._id, fromGoogle: user.fromGoogle, accType: user.accountType },
      process.env.JWT_SECRET
    );

    const { _id, ...others } = user._doc;

    res
      .cookie("access_token", accessToken, {
        httpOnly: true,
        secure: true,
        sameSite: "none",
      })
      .status(200)
      .json(_id);
  } catch (error) {
    return next(error);
  }
};

My React frontend

const submitHandler = async (e) => {
    e.preventDefault();

    if (!email || !password || email.trim() === "" || password.trim() === "") {
      dispatch(loginFailure(null));
      return setInputError("All fields are required");
    }

    dispatch(loginStart());

    try {
      const res = await backendConnection.post("/auth/login", inputValue, {
        withCredentials: true,
        credentials: "include",
      });
      dispatch(loginSuccess());
      localStorage.setItem("clientId", JSON.stringify(res.data));
      window.location.href = "/";
    } catch (error) {
      dispatch(
        loginFailure(
          error.response.data
            ? error.response.data.message
            : "Something went wrong"
        )
      );
    }
  };

Please I’ll be very glad if someone helps me out

Access WordPress Properties/Attributes of Custom Block in PHP

I have created my first WordPress Block using the npm package. It is an FAQ setup that takes a string for a question and InnerBlocks for the content.

As well as rendering this block, I want to create an JSON Schema for search engines that outputs the JSON Schema in the <head>. It should take each one of these FAQ blocks on any given post and place the value of the question attribute and the content of the inner block in the relevant question and answer field of the JSON Schema.

I can do this dynamically with javascript but I don’t think that is the correct approach as this JSON Schema should be output directly in the <head>.

So I thought I should extract these attribute values in PHP and create a function that would inject the JSON schema to wp_head. But I found this equally impossible. I can’t access these attributes in PHP. I tried creating a custom render.php but found that the HTML attributes were not included in $attributes. The only way I can see to do this is with an OB_Clean using add_filter to examine and extract what I want from the HTML.

Surely there is a way to extract the attribute values in PHP then create a global that accumulates all these, builds the <script> and adds it to wp_head?

Or am I overthinking this? I can’t find documentation on reading the attribute values in php at all. What am I missing?

Cannot connect to MongoDb client

I am not being able to connect to MongoDB.
The error i am getting is

 |         options.includeResultMetadata ??= false;
20:46:01 0|app    |                                       ^^^
20:46:01 0|app    | SyntaxError: Unexpected token '??='

Node version when i am running the project is
node -v => v20.7.0

MongoDB version
mongod –version => db version v6.0.8

package.json

"dependencies": {
    "compression": "^1.7.4",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "helmet": "^7.0.0",
    "http-status": "^1.7.0",
    "mongodb": "^6.1.0",
    "xss-clean": "^0.1.4"
  }
}

What am i missing

The code

const { MongoClient } = require('mongodb');


const uri = 'mongodb://localhost/testDatabase';

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function connectToDatabase() {
  try {
    await client.connect();
    console.log('Connected to the MongoDB database');
  } catch (err) {
    console.error('Error connecting to the MongoDB database:', err);
  }
}

module.exports = {
  connectToDatabase,
  getDatabase: () => client.db(),
};

Tryin responsive with chartjs

I’m using chartjs on my React project and I’m trying to make it responsive (I’m also working with material UI) I was wondering if someone can help me.

Here is part of my code. This is how I create my chart on my component

const createChart = (containerId, data, chartType) => {
    const ctx = document.getElementById(containerId).getContext("2d");
    new Chart(ctx, {
      type: chartType,
      data: {
        labels: data.labels,
        datasets: [
          {
            label: chartType === "radar" ? "Ajuste Cultural" : "KPIS",
            data: data.values,
            backgroundColor: data.colors,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
      },
    });
  };

and this is how I apply it to the MUI BOX

<Box
        // class="chart-container"
        // style={{ position: "relative" }}
          border={"5px solid blue"}
          flex={1}
          marginLeft={{ sm: "10px", xs: "0px" }}
        >
          <canvas id="culturalFitChart" width="200" height="100"></canvas>
        </Box>
        <Box border={"5px solid blue"} flex={1}>
          <canvas id="kpisChart" width="200" height="100"></canvas>
        </Box>

 
thank you