Why is this Map object showing empty when trying to access it?

Long time listener, first time caller…would appreciate any help because I am at a loss!

I’m working on a node.js project using libp2p for peer discovery. I have my codebase running on 2 machines connected to my local network. They discover each other, connect to each other, and store the connection details in a Map object called discoveredPeers. I have several console log statements to track the value of discoveredPeers. The Map contains exactly what I would expect it to UNTIL I try to access that Map object from a secondary module. Then it immediately shows that it is empty, despite a log statement immediately prior showing that it holds 3 entries.

Modules in question:

peerState – Declares the discoveredPeers Map

console.log('Initializing peerState...');

export const discoveredPeers = new Map();
export const connectedPeers = new Map();

peerStateManager – Imports peerState where discoveredMaps object is declared. Contains various getter/setter methods for peerState

export const getAllDiscoveredPeers = async () => discoveredPeers;

export  const updatePeerPublicKey = async (peerId, publicKey) => {
    if (discoveredPeers.has(peerId)) {
        discoveredPeers.get(peerId).publicKey = publicKey;
        console.log('Updated peer publicKey');
        console.log('Discovered Peers @ updatePeerPublicKey: ', discoveredPeers)
    }
};

export  const getPeerByPublicKey = async (publicKey) => {
    console.log('Discovered Peers @ getPeerByPublicKey:', discoveredPeers);
    for (const [peerId, peerData] of discoveredPeers) {
        if (peerData.publicKey === publicKey) {
            return {peerId, ...peerData}; // Return the whole peer object
        }
    }
    return null; // Return null if no peer with that publicKey is found
};

messenger – Imports peerStateManager to access and update the values of peerState

case MESSAGE_TYPES.PEER.RESPONSE:
            console.log('Received PEER_RESPONSE');
            if (message.actionType === ACTION_TYPES.PEER.RESPONSE_PUBLIC_KEY) {
                console.log('Received PEER_RESPONSE_PUBLIC_KEY: ', message.payload.publicKey);
                const peerId = message.meta.sender;
                const publicKey = message.payload.publicKey;
                **await peerStateManager.updatePeerPublicKey(peerId, publicKey);**
            }
            break;

synapseController – Imports getAllDiscoveredPeers and getPeerByPublicKey from peerStateManager

exports.getSynapseUserPosts = async (req, res) => {
    **console.log('Discovered Peers in getSynapseUserPosts: ', await getAllDiscoveredPeers());**
    const handle = req.query.handle;
    const synapsePublicKey = req.query.publicKey;
    const {peerId} = await getPeerByPublicKey(synapsePublicKey);

...more definition

}

A call from messenger causes peerStateManager to update discoveredPeers. It logs 3 entries in discoveredPeers. Immediately after, a call via synapseController to getAllDiscoveredPeers() shows its empty, which subsequently causes getPeerByPublicKey() fail.

CONSOLE OUTPUT:

Updated peer publicKey
Discovered Peers @ updatePeerPublicKey:  Map(3) {
  '12D3KooWM2YGTyBb11aPdWHbDarzpmDLp3FpAPQbqFKHWjAtJrpm' => {
    publicKey: '0315e1f282db55a243b70c8030dc4e4a1fe9fff45dbe82f1e5f1ae6638b6e3ff49',
    multiaddrs: [
      '/ip4/192.168.1.188/tcp/4001'
    ]
  },
  '12D3KooWJtLJ3Z5YM855gxsWDnEFHhATAPTGMBQDQGYjh3icFsbs' => {
    publicKey: null,
    multiaddrs: [
      '/ip4/192.168.1.253/tcp/4001/p2p/12D3KooWJtLJ3Z5YM855gxsWDnEFHhATAPTGMBQDQGYjh3icFsbs'
    ]
  },
  '12D3KooWEESBm7xFdo35dGnbjY5LZVnWvbn1JS51Kc71ooGkcWNr' => {
    publicKey: null,
    multiaddrs: [
      '/ip4/192.168.1.188/tcp/4001/p2p/12D3KooWEESBm7xFdo35dGnbjY5LZVnWvbn1JS51Kc71ooGkcWNr'
    ]
  }
}
Discovered Peers in getSynapseUserPosts:  Map(0) {}
Discovered Peers @ getPeerByPublicKey: Map(0) {}
/Users/enki/Developer/Repositories (Version Controlled)/meNexus-platform/synapse/api/src/controllers/synapseController.js:14
    const {peerId} = await getPeerByPublicKey(synapsePublicKey);
           ^

TypeError: Cannot destructure property 'peerId' of '(intermediate value)' as it is null.

I tried declaring discoveredPeers in its own separate file that gets managed by a peerStateManager module because some of my reading suggested that discoveredPeers was being re-initialized when synapseController tried to access the Map because the file was imported again…so I tried to make sure that discoveredPeers was a global/singleton object. The same behavior persists where the Map shows empty as soon as synapseController tries to access it. I also have a log statement in peerState that shows (‘Initializing peerState…’) and that only fires once. I do not see that firing again when synapseController tries to access the discoveredPeers Map.

Any assistance would be greatly appreciated as I’m simply stuck on this one.
I am happy to answer any clarifying questions if needed. Struggling to ask my question gracefully so I apologize in advance if my post is gibberish. Thank you.

parse relative times in javascript (e.g. “2 hours ago”) [closed]

I want to parse a relative time in javascript. e.g.

let relative_timestamp1 = '2 hours ago';
let relative_timestamp2 = '3 weeks ago';
let relative_timestamp3 = '1 year and two months ago';

let datetime_object = parseRelativeTime(relative_timestamp1); // Date() object

I checked libraries like moment.js and chrono, but did not find a solution for this problem. The parsing seems like quite a complex problem and i did not find any answere here or elsewhere. Thanks for your help 🙂

Pulling custom css values within HTA application

I have the following .hta simple application:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" http-equiv="X-UA-Compatible" content="IE=11">
<style>
  .someClass::after {
    content:" HTA";
  }
</style>
<script language="JScript">
window.onload = function () {
  var element = document.querySelector('.someClass');
  var cssContent = window.getComputedStyle(element, '::after').content;
  cssContent = cssContent.replace(/^["']|["']$/g, '');
  alert(someId.innerText + cssContent);
}
</script>
</head>
<body>
  <div id="someId" class="someClass">Testing</div>
</body>
</html>

This code successfully makes an alert window with the message “Testing HTA” inside.

But when I try to define --custom-align:" HTA"; for example instead of using the content keyword, it fails. In general I want to pull custom css values with the Jscript, but until now I seem to only be able to do this with the custom keyword

Error when displaying “Hello world” three times on the Console screen [closed]

I would like to know, please, why when trying to view the “Hello world” message three times on the “Console” screen, this error message appears, shown below?

676718f2f590508f5fe195f8:92 Refused to execute inline script because it violates the following Content Security Policy directive: “script-src ‘self’ ‘nonce-u+K4rc97E2TANhHXhHeoAA==’ https://code.jquery.com https://cdn.jsdelivr.net”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-A70QUc2Kse21wsA4D7Pq5ITbT/jYO221ulMbeKG0p3A=’), or a nonce (‘nonce-…’) is required to enable inline execution.

I hope my question is resolved in the best way possible.

How can I resolve issues when installing specific versions of testing libraries and web-vitals with npm? [duplicate]

this is my first time working with this and I faced multiple issues and errors
C:UserslenovoOneDriveDesktopreact-course>npx create-react-app .

Creating a new React app in C:UserslenovoOneDriveDesktopreact-course.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template…

added 1323 packages in 1m

267 packages are looking for funding
run npm fund for details

Initialized a git repository.

Installing template dependencies using npm…
npm error code ERESOLVE
npm error ERESOLVE unable to resolve dependency tree
npm error
npm error While resolving: [email protected]
npm error Found: [email protected]
npm error node_modules/react
npm error react@”^19.0.0″ from the root project
npm error
npm error Could not resolve dependency:
npm error peer react@”^18.0.0″ from @testing-library/[email protected]
npm error node_modules/@testing-library/react
npm error @testing-library/react@”^13.0.0″ from the root project
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with –force or –legacy-peer-deps
npm error to accept an incorrect (and potentially broken) dependency resolution.
npm error
npm error
npm error For a full report see:
npm error C:UserslenovoAppDataLocalnpm-cache_logs2025-01-14T20_11_41_009Z-eresolve-report.txt
npm error A complete log of this run can be found in: C:UserslenovoAppDataLocalnpm-cache_logs2025-01-14T20_11_41_009Z-debug-0.log
npm install --no-audit --save @testing-library/jest-dom@^5.14.1 @testing-library/react@^13.0.0 @testing-library/user-event@^13.2.1 web-vitals@^2.1.0 failed

I want solve to this issue.
Thanks guys

How to add multiple images on a piechart using highcharts?

I am creating a piechart using highcharts. I want to display image on top of each pie and one next to the pie chart? How can I do this? I looked at the example below, but it only has one image – https://jsfiddle.net/BlackLabel/Lwk9m0a4/

Here is my code-

        Highcharts.chart('chart1', {
            chart: {
                type: 'pie',
                backgroundColor: null
            },
            title: {
                text: '',
                align: 'left',
                verticalAlign: 'middle',
                style: {
                    fontSize: '20px',
                    fontWeight: 'bold',
                    color: '#333333'
                }
            },
            plotOptions: {
                pie: {
                    innerSize: '50%',
                    startAngle: 0,
                    endAngle: 180,
                    
                    dataLabels: {
                        enabled: true,
                        connectorShape: 'crookedLine',
                        crookDistance: '70%',
                        format: '{point.name}',
                        style: {
                            fontSize: '14px',
                            color: '#333333'
                        },
                        distance: 20
                    }
                }
            },
            series: [{
                name: 'ABCk',
                data: [
                    { name: 'test1', y: 25, color: '#6BAED6' },
                    { name: 'test2', y: 25, color: '#4292C6' },
                    { name: 'test3', y: 25, color: '#2171B5' },
                    { name: 'test4', y: 25, color: '#112e51' }
                ]
            }]
        });
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="chart1" style=" width: 600px; height: 400px; margin: 0 auto;"></div>

Website Not Working Properly on Different Devices and Issues with Responsiveness [closed]

I’ve been having some problems with my website not working properly on different devices. After making a few tweaks, the site appears with items labeled “item 0”, “item 1”, etc., after the footer. Additionally, some users I’ve asked to test the site can’t even open it.

I’ve made some adjustments to the CSS and JavaScript with the help of AI, but I’m still facing issues. I would appreciate any help with fixing these problems and improving the website’s responsiveness across all devices.

I will post the code in the comments

Javascript – bitwise manipulate in JS to generate unique IDs combining bytes from Date.now() and random bytes?

I want to create an 8 bytes ID so that the higher 5 bytes will be the first 5 bytes of Date.now() and the lower 3 bytes will be random bytes.

I examined the result of Date.now and saw that I only lose the 40th bit If I shift it 3 bytes to the left. Then I want to set 3 random bytes on the lower bytes.

  1. What is the most efficient way in JS (It is ok if it uses node.js special types) to achieve this?
    How do I get the numeric value into a buffer in the first place so I can use buffer.set to copy it to the appropriate location? the write64BigInt with the big-endian little-endian feels dangerous to me and copying byte after byte feels stupid.

  2. I want a method to extract back the time stamp from it.
    It means >>> of 24 and then switching the 40th bit back on (It will work for the next 30+ years and that is enough for us)
    But what is the way to do that in JS without implicitly or explicitly allocating unnecessary buffers Dataviews Bigints?

  3. Bonus – After creation, should I pass it around as a buffer? a BigInt? I guess a buffer because then it is easiest to convert to the others (like hex string)

Subgrid not displaying data in jqGrid

After two days of trying to fix this issue and, reviewing virtually very post on here I could find, I’m still stuck. I’m using jqGrid and the main grid is loading fine. I have an identity column so I’m referencing it using a key. My issue is the subgrid is not loading data.

Here’s a sample of my json:

[
   {
      "ID":212,
      "ScientificName":"Abronia fragrans",
      "PreviousNames":"Abronia fragrans var. glaucenscens, Abronia latifolia, Abronia turbinata, Abronia villosa",
      "Family":"Nyctaginaceae",
      "CommonNames":"Fragrant Sand Verbena, Fragrant Sand-verbena, Fragrant Verbena, Fragrent White Sand Verbena, Hearts Delight, Prairie Snowball, Sand Verbena, Snowball Sand Verbena, Snowball Verbena, Sweet Sand-verbena, Wild Lantana",
      "ToxictoDogs":0,
      "ToxictoCats":0,
      "ImageName":"",
      "ToxicPrinciples":null,
      "ClinicalSigns":null
   },
   {
      "ID":1,
      "ScientificName":"Abrus precatorius",
      "PreviousNames":null,
      "Family":"Fabaceae",
      "CommonNames":"Buddhist Rosary Bead, Crabs Eyes, Indian Bead, Jequirity Bean, Love Bean, Prayer Bean, Precatory Bean, Rosary Pea, Seminole Bead",
      "ToxictoDogs":1,
      "ToxictoCats":1,
      "ImageName":"",
      "ToxicPrinciples":"Abrin (lectin or a toxalbumin) and abric acid (a glycoside)",
      "ClinicalSigns":"Severe vomiting and diarrhea (sometimes bloody), tremors, high heart rate, fever, shock, death. Seeds are very toxic (seed coat must be broken)."
   },
   {
      "ID":213,
      "ScientificName":"Acalypha hispida",
      "PreviousNames":"Acalypha densiflora, Acalypha sanderi",
      "Family":"Euphorbiaceae",
      "CommonNames":"Bristly Copperleaf, Chenille Plant, Foxtail, Philippines Medusa, Red Hot Cats Tail, Red-hot Cat Tail, Red-Hot Cattail",
      "ToxictoDogs":0,
      "ToxictoCats":0,
      "ImageName":"",
      "ToxicPrinciples":null,
      "ClinicalSigns":null
   }
]

And my JS:

$(document).ready(function () {
    $("#jqGrid").jqGrid({
        url: "scripts/dbconfig.php",
        mtype: "GET",
        datatype: "json",
        colNames: ["ID", "ScientificName", "Family", ""],
        colModel: [
            { name: "ID", key: true},
            { name: "ScientificName", width: 550, cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal;"' } },
            { name: "Family"},
            { name: "ImageName", align: "center", width: 300}
        ],
        rowNum: 10,
        rowList: [5, 10, 20],
        pager: "#pager",
        gridview: true,
        ignoreCase: true,
        rownumbers: true,
        sortname: "ScientificName",
        viewrecords: true,
        height: "100%",
        subGrid: true,
        subGridRowExpanded: function (subgridId, rowid) {
            var subgridTableId = subgridId + "_t";
            $("#" + subgridId).html("<table id='" + subgridTableId + "'></table>");
            $("#" + subgridTableId).jqGrid({
                datatype: "local",
                data: $(this).jqGrid("getLocalRow", rowid).data,
                colNames: ["ToxicPrinciples", "ClinicalSigns"],
                colModel: [
                  {name: "ToxicPrinciples", width: 130},
                  {name: "ClinicalSigns", width: 130}
                ],
                height: "100%",
                rowNum: 10,
                sortname: "ToxicPrinciples",
                idPrefix: "s_" + rowid + "_"
            });
        }
    });
    $("#jqGrid").jqGrid("navGrid", "#pager", {add: false, edit: false, del: false});
});

Now I if I were to change ‘subGridRowExpanded’ to something simple like the following, I am getting the correct ID from my main grid showing:

subGridRowExpanded: function(subgridId, rowid) {
    var html = "<span>rowid=" + rowid + "</span><br/>";
    $("#" + subgridId).append(html);
}

I’m fairly certain, my issue is on the data: line of my subgrid, but I’m not positive, nor sure how to fix. I also explored the option of reloading my data in the subgrid, instead of using local, but that seems redundant.

I also tried another approach for my subgrid like the following, which also did not load any data.

subGridRowExpanded: function (subgridDivId, rowid) {
    var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
        $subgridDiv = $("#" + subgridDivId),
        subgridData = $(this).jqGrid("getLocalRow", rowid).details;

    $subgridDiv.closest(".subgrid-data").prev(".subgrid-cell").remove();
    var colspan = $subgridDiv.closest(".subgrid-data").attr("colspan");
    $subgridDiv.closest(".subgrid-data").attr("colspan", parseInt(colspan, 10) + 1);
    $subgridDiv.append($subgrid);
    $subgrid.jqGrid({
        idPrefix: rowid + "_",
        data: subgridData,
        colModel: [
            { name: "ToxicPrinciples", label: "ToxicPrinciples" },
            { name: "ClinicalSigns", label: "ClinicalSigns" },              
        ],
        sortname: "ToxicPrinciples"
    });
    $subgrid.jqGrid("setGridWidth", $subgridDiv.width() - 1);
}

I should also mention that I have the console window open in my browser under Developer Tools and there are no errors being thrown for any of the above code shown here.

How to use html/css tags in JSON data to populate React component

I have a JSON file of recipes, and I am creating a React app using a specific flipbook library. The intricacies of that library aren’t really relevant, but I am creating its Page components dynamically from the JSON file.

Essentially, I want my JSON file to be able to hold html and CSS data such as <h3 className=”class” Header!> and actually have that rendered in the dynamically generated Page components. Is this possible?

React page:

export default function RecipeBook() {
  const searchParams = useSearchParams();
  const book = useRef();
  const [pages, setPages] = useState([]);

  useEffect(() => {
    const recipeElems = Object.entries(recipes).map((element, i) => (
      // checks if page should be cover and/or if the page has a link to reference
      element[1].cover ? 
      <PageCover key={i} side={i%2==0 ? "L" : "R"}> {element[1].header} </PageCover>
      :
      element[1].link !== "" ? 
      <Page key={i} src={element[1].src} side={i%2==0 ? "L" : "R"} header={element[1].header}> 
      {element[1].content} Inspired by this <a href={element[1].link}>recipe.</a> 
      </Page> 
      :
      <Page key={i} src={element[1].src} side={i%2==0 ? "L" : "R"} header={element[1].header}> 
      {element[1].content}
      </Page> 
    ));
    setPages(recipeElems);
  }, [])  

  return (
    <div className="bookContainer">
      <HTMLFlipBook
      className="book"
      ref={book}
      width={350} height={450}
      maxWidth={350} maxHeight={450}
      size="stretch"
      maxShadowOpacity={0}
      >
        {pages}
      </HTMLFlipBook>
    </div>
  );
}

The JSON looks like this:

[
    {
        "header": "Desserts",
        "src": "",
        "cover": true
    },
    {
        "header": "Fl-Earl Gray Cake",
        "content": "Earl gray and marzipan-chunks sponge cake (1:1:1 b:s:f ratio, 3 eggs) soaked with çiçek suyu and rose syrup. n Rose cream cheese frosting. n Rose marmalade to decorate.",
        "link": "https://theclovecoterie.substack.com/p/nosferatu-cake",
        "src": "/kitchen/cake.jpg",
        "cover": false
    },
...
]

Vercel Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource

I recently deployed both backend and frontend of my application to Vercel, which uses clerk authentication. When trying to make api calls, I get the following error in my console:
‘backend (on different domain)’ from origin ‘frontend’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

here is my server.js file:

const express = require('express');
const cors = require('cors');
const connectDB = require('./config/db');
const expenseRoutes = require('./routes/expenseRoutes');
require('dotenv').config();
const { ClerkExpressRequireAuth } = require('@clerk/clerk-sdk-node');

const app = express();

connectDB();

app.use(cors({
    origin: ['https://www.pennypilot.dev', 'https://pennypilot.dev'],
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],  
    allowedHeaders: ['Authorization'],
    credentials: true, 
}));


app.use((req, res, next) => {
  if (req.method === 'OPTIONS') {
    return res.status(200).end();  
  }
  next();
});


app.use(ClerkExpressRequireAuth());

app.use(express.json());


app.use('/api/expenses', expenseRoutes);

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
    console.log(`http://localhost:${PORT}`);
});

Do I need to add options to my controllers as well? or does cors handle that

Setting product quantity and adding it to the cart using Playwright

I am a complete beginner in coding. I want to create a script that works on the website www.kosarbolt.hu. The script should:

Search for a product by its SKU (this SKU will vary).
Open the product page.
Set the desired quantity.
Add the product to the cart.
I have tried implementing this in both JavaScript and Python, but I keep running into issues, and the project fails.

In the future, I want to enhance this script to handle multiple SKUs provided in an XML file and add all those products to the cart.

Could someone guide me on how to achieve this or share an example to get started? Any help would be greatly appreciated!

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  try {
    // 1. Oldal megnyitása
    console.log("1. Oldal megnyitása...");
    await page.setViewportSize({ width: 1280, height: 720 });
    await page.goto('https://www.kosarbolt.hu');

    // 2. Oldal nagyításának csökkentése
    console.log("2. Oldal nagyításának csökkentése...");
    await page.evaluate(() => {
      document.body.style.zoom = "0.5";
    });

    // 3. Cikkszám beírása és keresés
    console.log("3. Cikkszám beírása és keresés...");
    await page.fill('#filter_keyword', '6614');
    await page.press('#filter_keyword', 'Enter');
    console.log("Keresés elküldve.");
    await page.waitForTimeout(2000); // Várakozás a keresési eredmények megjelenésére
    await page.screenshot({ path: 'step3_search_sent.png' });

    // 4. Cookie sáv elfogadása (ha van)
    console.log("4. Cookie sáv kezelése...");
    const cookieButton = await page.locator('.cookie-accept-button');
    if (await cookieButton.isVisible()) {
      await cookieButton.click();
      console.log("Cookie elfogadva.");
    }

    // 5. Várakozás a termékoldal betöltésére
    console.log("5. Várakozás a termékoldal betöltésére...");
    await page.waitForSelector('input[name="quantity"]', { timeout: 20000 });

    // 6. Görgetés a mennyiség mezőhöz és kitöltés
    console.log("6. Görgetés a mennyiség mezőhöz...");
    const quantityInput = await page.locator('input[name="quantity"]');
    await quantityInput.scrollIntoViewIfNeeded();
    console.log("Darabszám beállítása...");
    await quantityInput.fill('3');
    await page.screenshot({ path: 'step6_quantity_set.png' });

    // 7. Görgetés a kosárba helyezés gombhoz
    console.log("7. Görgetés a kosárba helyezés gombhoz...");
    const addToCartButton = await page.locator('.btn-add-to-cart');
    await addToCartButton.scrollIntoViewIfNeeded();
    console.log("Kosárba helyezés...");
    await addToCartButton.click();

    // 8. Ellenőrzés, hogy a kosárba került a termék
    console.log("8. Kosár állapotának ellenőrzése...");
    await page.waitForSelector('.cart-items', { timeout: 10000 });
    await page.screenshot({ path: 'step8_added_to_cart.png' });
    console.log("Termék sikeresen kosárba helyezve!");

  } catch (error) {
    console.error('Hiba történt:', error);
    await page.screenshot({ path: 'error_screenshot.png' });
    const htmlContent = await page.content();
    require('fs').writeFileSync('error_page.html', htmlContent);
  } finally {
    await browser.close();
  }
})();

Caching API responses server side across routes in NextJS

I am trying to cache data between routes. I have tried several options but I can’t fathom how to do it. It seems such a simple and obvious task. My use case is a Profile section of a website which allows the updating of data via a (client side) form. There are numerous pages on [lang]/foo/bar routes. I am currently calling my API on every route change.

I start with this file, it is called from numerous pages and server components:

"use server"

export const getData = async () => {
  const data = await fetch("http://foo/getProfileData", {
    next:{ revalidate: 60 }
  });
  
  return data.json()
}

But this does not dedupe the calls and I see a lot of requests on my API.

So I try React’s cache wrapper:

"use server"
import { cache } from "react";

export const getData = cache(async () => {
  const data = await fetch("http://foo/getProfileData", {
    next:{ revalidate: 60 }
  });
  
  return data.json()
})

Some progress, I have reduced my requests on a per-route basis, but switching routes calls the Foo API again.

So I try to be a bit more clever and take advantage of Node’s module caching:

import "server-only";

export class ServerCache<T> {
  private data: null | T = null;
  private expirationMs: number;
  private timestamp: null | number = null;

  constructor(expirationMs: number) {
    this.expirationMs = expirationMs;
  }

  get(): null | T {
    const shouldRevalidate =
      !this.data || this.getElapsedMs() > this.expirationMs;

    if (shouldRevalidate) {
      return null;
    }
    return this.data;
  }

  getElapsedMs() {
    return this.timestamp ? Date.now() - this.timestamp : Infinity;
  }

  getRemainingSeconds() {
    return (this.expirationMs - this.getElapsedMs()) / 1000;
  }

  invalidate() {
    this.data = null;
    this.timestamp = null;
  }

  set(data: T) {
    this.data = data;
    this.timestamp = Date.now();
  }
}

and

"use server"

const cache = new ServerCache(60*1000)

export const getData = async () => {

  if (cache.get()) return data;

  const data = await fetch("http://foo/getProfileData", {
    next:{ revalidate: 60 }
  });

  const updatedData = await data.json();

  cache.set(updatedData)
  
  return updatedData
}

export const revalidate = () => cache.invalidate()

This again works but now I cannot invalidate the cache manually because each time this file is imported it creates a new instance so you can never clear the “correct” cache.

So I tried to take advantage of a global state:

declare global {
  // eslint-disable-next-line no-var
  var meCache: ServerCache<any> | undefined;
}

if (!global.meCache) {
  console.log("Initializing globalCache module");
  global.meCache = new ServerCache<MeResponse>(GET.me.revalidate * 1000);
}

export const me = global.meCache;

and import this into my getData file, but the same happens, I see the log multiple times and so cannot manually clear the cache.

This seems such a usual use case for a Server to Client relationship, but I cannot fathom how to create a cache between routes which I can clear when needed.

Url in jQuery ajax call from javascript in different directory than file with endpoint

I have made a Python Flask application in which the directory structure uses different blueprints and a dedicated directory for several javascript modules (used within different html template files), essentially:

/app/main/routes.py
/app/main/templates/main/afile.html
/app/static/javascript/ascript.js
  • within afile.html:
<script type="module" src="{{url_for('static', filename='javascript/ascript.js')}}"></script>
  • within routes.py:
@bp.route("/ajax_func", methods=["GET", "POST"])
def ajax_func():
    return jsonify( {'data': 'hello'} )
  • within ascript.js:
    $.ajax({
        url: "{{ url_for('main.ajax_func') }}",
        type: "POST",
        data: "whatever",
        success: function (data) { alert(data); }
    });

afile.html is a html template rendered from a different function within routes.py. Then I am trying to do a jQuery ajax call from ascript.js to the endpoint ajax_func within the main
blueprint, but I am unable to get the right URL (always getting 404 html response).

How do I correctly specify the URL in the ajax call ?

How do I fix Error: EPERM: operation not permitted from a gulp task?

[13:04:33] Finished 'deploy_resource_packs' after 10 ms
[13:04:33] 'watch_scripts' errored after 2.21 s
[13:04:33] Error: EPERM: operation not permitted, watch
    at FSWatcher._handle.onchange (node:internal/fs/watchers:207:21)
    at FSEvent.callbackTrampoline (node:internal/async_hooks:130:17)

After completing the last task in the series (deploy_resource_packs), watch-scripts errors with EPERM.

I don’t understand why this is happening or how to fix it, given that it seems to be coming from gulp. I’ve looked up similar issues and tried every solution I could find, but nothing has worked thus far. Any ideas?