How can I “augment” a JS class with methods from another class, without extending it?

I’m writing an app that manages playlists.
Basically, my actual logic looks like

//define playlist props
class Playlist{
    public tracks = [];
}

class ApiPlaylist extends Playlist{
    //fill playlist withs (single page) data from API
    public async loadPage(paginationSettings){
        const pageTracks = await...
        this.tracks = [...this.tracks,...pageTracks]; //concat tracks
    }
}

class Paginated extends ApiPlaylist{
    private iterations = 0;
    private endReached = false;
    public async loadAll(){
        while (!this.endReached){
            this.loadNext();
        }
    }
    public async loadNext(){
        this.iterations++;
        await this.loadPage(); //call ApiPlaylist method
        if(...){
            this.endReached = true; //stop iterating
        }
    }

}

const playlist = new Paginated();
playlist.loadAll();

It works.

But what if I have different others paginated datas to get, that are not related to playlists ?

I would like to use the mechanism from PaginatedPlaylist with another classes, without having to duplicate it.

Acually, Paginated extends ApiPlaylist.
Is there a simple way to implement the methods from Paginated to ApiPlaylist without using extends ?

Something like

class ApiPlaylist [implements] Paginated{}
class ApiPost [implements] Paginated{}
class ApiPage [implements] Paginated{}

Thanks for your help !

What can do to compile my Chrome Extension js files?

I’m developing a Chrome extension , and the problem I’m facing is that it needs a content.js file and in that i con;t import from other files.

This means that i have to write the entire extension code in one file , which makes it very hard to read and maintain.

What con i do? How can i break my files into different files in development and compile them all into one single file for production?

IntelliSense for SQL from UI

When user starts typing on the UI I want to provide sql commands suggestions such as select, from, where etc
And I want this intellisense to be smart enough to know when It has to suggest tables names, columns names, and sql commands.

is there any way to achieve this?
any library etc.

Im working with javascript on frontend, and node.js on backend.

show values on top of bars on each colmnin chart.js

I have tried a lot to show values on top of char but I couldn’t do it please could you help me with this
i have also add plugins to show data.

<canvas id="myChart" width="200" height="100" aria-label="Hello ARIA World" role="img"></canvas>
<script>
  const ctx = document.getElementById('myChart');
  console.log({{sales_performance|safe}})
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      datasets: [{
        label: 'Sales',
        data: [1, 10, 10, 11, 1, 10, 10, 11, 1, 10, 11, 16],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          display: false, // Hide the y-axis label
          beginAtZero: true
        }
      },
      plugins: {
        datalabels: {
          color: 'black', // Set the color of the data labels
          font: {
            weight: 'bold'
          },
          formatter: function(value, context) {
            return value; // Display the value on the bars
          }
        }
      }
    }
  });



</script>

I want to show values on top of each bar column.

Authentication system generating a token which is already expired

I am generating a token with express for my react app. Which is hosted is vercel. When I click in login button my express.js generate token and send it to frontend .


const loginEditorialController = async (req,res) =>{
    try{
        const db = getDb()
        const { email , password } = req.body

        if(!email || !password){
            return res.status(404).json({ 
                message : `No empty field allowed!`
            })
        }

        if (!/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(email)) {
            return res.status(400).json({
              message: 'Invalid email format!',
            });
        }

        const query = { email : email }
        const user = await db.collection('editorial').findOne(query)
        
        if(!user){
            return res.status(403).json({
                message: 'Invaid email or password!',
                suggest : 'Please try again or create account.'
            })
        }

        if (!user.password) {
            return res.status(403).json({
                message: 'Invalid email or password!',
                suggest: 'Please try again or create an account.'
            });
        }

        const matched = await bcrypt.compare(password, user?.password)
        
        if(!matched){
            return res.status(403).json({ 
                message : 'Invalid email or password!',
            })
        }

        const jwt_user_data = {
            email:email,
            role: user.role
        }

        const access_token = jwt.sign({
            data: jwt_user_data
          }, process.env.ACCESS_TOKEN_SECRET, 
          { expiresIn: '1h' }
        )

        res.status(200).json({
            message: 'User found!',
            additional : 'Login successfull',
            access_token
        })
    }
    catch(err){
        console.log(err)
    }
}

Which has a expiration time of 1 hour. In front end I have a hook that perform some operation based on time .But every time when I login the token got deleted just after setting up it in the local storage. I copied the token decoded it in their website . Found out the token is already expired . That’s my condition become true and delete the token from local storage. I have faced the problem both in local check and after deployment. Here is my frontend code :

import { jwtDecode } from "jwt-decode";
import { useState, useEffect } from "react";

const useUserdata = () => {
    const [loading, setLoading] = useState(false);
    const [u_email, setU_email] = useState('');
    const [u_role, setU_role] = useState('');

    const checkLocalStorage = () => {
        const token = localStorage.getItem('access_token');
        setLoading(true)
        try {
            const decoded = jwtDecode(token);

            if (Date.now() >= decoded.exp * 1000) {
                localStorage.removeItem('access_token');
                setU_email('');
                setU_role('');
            } else {
                const { email, role } = decoded.data;
                setU_email(email);
                setU_role(role);
            }
        } catch (error) {
            localStorage.removeItem('access_token');
            setU_email('');
            setU_role('');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        checkLocalStorage();
    }, []);

    const forceCheckLocalStorage = () => {
        setLoading(true);
        checkLocalStorage();
    };

    return { loading, u_email, u_role, forceCheckLocalStorage, setU_email, setU_role };
};

export default useUserdata;


I have tried several ways but nothing works.
Sorry for my bad English skill. Thanks.

Showing json data from javascript fetch request from browser to different url

I have a website loading from example.com that will attempt to grab data from url example.net

(I own example.net and website example.com, and remember for this question to be answered correctly its critical to understand that the webpage after it loads from example.com is requesting data from a different domain name example.net)

I am attempting to use safe simple cors headers, so my response from example.net returns stringified data like this:

var data = {
             "status": false,
             "cool":"cool"
             "yes":"yes"
}
var json = JSON.stringify(data)
const init_no_authresponse = { headers: {
 "content-type": "text/plain", 
 "Access-Control-Allow-Origin": "*",
 "Cache-Control": "no-store, max-age=0"
}, status: 200 }
        
return new Response(json, init_no_authresponse)

I have tried a number of different method to fetch, for instance:

const getstuff = fetch("https://example.net")
        .then((response) => response.text())
        .then((data) => {
            console.log("here is the new printAddress 1st response");
            return data;// return user.address;
        }
    );


const dostuff = () => {
    getstuff.then((a) => {
         console.log(a);  // will result in test
         console.log(JSON.parse(a).cool);    // will result in undefined
     })
}

dostuff();

If I paste this code into the console it runs fine, if I load this from the website load, it will not show the parsed data: ie console.log(a).cool instead will show undefined while just console.log(a) will show the total response

Anybody understand how I am treat his promise or CORS issue improperly? Appreciate it!

Nextjs App Route api giving initial data on run build, normally in run dev

I have a Next.js page with App Router. The page get the data from it’s route API. Data obtained from MQTT. In development (run dev), when we send request to api/getLocation it will return updated data from MQTT. But in production, data returned was initial data (not updated from MQTT).
I can’t figure where is the mistakes

This is route file on handling user data request “app/api/realtimeLocation/route.ts

import mqttSubscriber from './mqtt-subscriber'

export async function GET(req: any, res: any) {
   const { data } = mqttSubscriber
   let validateData = data ? JSON.parse(data) : null
   try {
      return Response.json({
         status: 'OK',
         data: validateData
      })
   } catch (err) {
      console.error('Something wrong happen')
   }
}

and it’s my mqtt configure “mqtt-subscriber.js” in same directory

import * as mqtt from 'mqtt'

const client = mqtt.connect(`mqtt://${process.env.NEXT_PUBLIC_IP_MQTT}:1883`, {
   username: 'my-user',
   password: 'my-password',
})
// subscribe
client.on('connect', () => {
   const topic = 'fms/liveLocations'
   // subscrive
   client.subscribe(topic, err => {
      if (err) {
         console.log(err)
      } else {
         console.log(`Subscribe to topic: ${topic}`)
      }
   })
})
client.on('error', err => console.log('MQTT Error: ', err))
const receivedData = { data: null }
client.on('message', (receivedTopic, message) => {
   receivedData.data = message.toString()
})

export default receivedData

Await vs immediately-invoked async function expression

Can someone help me understand the difference between the two blocks of code below? When I call await in the listener, the caller receives undefined.

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
    // (async () => {
        const response = await executeScript(request);
        if (response) {
            console.log('Content script received message:', response);
            sendResponse(response[0].result);
        }
    // })();
    return true;
});

However, when I use the immediately-invoked async function expression, the returned value is what is returned by executeScript.

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    (async () => {
        const response = await executeScript(request);
        if (response) {
            console.log('Content script received message:', response);
            sendResponse(response[0].result);
        }
    })();
    return true;
});

When I call await executeScript, I am assuming that it stops the execution of the async function and suspends it until the awaited promise is resolved or rejected. How is this different from the immediately-invoked async function expression?

How to made field type ‘Document (filename)’ can only be opened and viewed on other tab? [Scriptcase]

I’m using Scriptcase. I have field type ‘Document (filename)’, field name is attachment. When it have document on it, I want when I clicked the doc, it only can be opened in new tab and viewed it. The default setting is when you clicked the file, it will be opened in new tab and automatically downloaded it. I don’t want it to be downloaded. Is there any method how to do it?

attachment

Server recieves empty object from multer fetch post request

I’m trying to set up a form on this webpage that sends a file to my Node server without leaving the page the form is on. I have mutler listening for file uploads, and I think I’ve set up the fileStorageEngine properly. The client-side JS is seeing the right file, and presumably sending it, but the server is only getting an empty object. I’m sure there’s something I’ve done wrong in the fetch request or the mutler setup, but I can’t seem to figure out what it is.

The form’s HTML

<form id="file-selection" action="/files" method="POST" enctype="multipart/form-data">
    <input type="file" id="tcg-original" accept=".csv" name="givenFilename"></input>
    <input type="submit" id="start-button" value="Start"></input>
</form>

The function called when the start button is clicked

function process(e) {
    e.preventDefault();

    const form = document.getElementById("file-selection");
    const formData = new FormData(form);

    fetch(form.action, {method: form.method, body: form.body});
}

The server JS file

import express from "express";
import multer from "multer";

const app = express();
app.listen(3000, () => console.log("Listening at 3000"));
app.use(express.static("site"));
app.use(express.json({limit: "100mb"}));

const fileStorageEngine = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "uploads");
    },
    filename: (req, file, cb) => {
        console.log(file);
        cb(null, "uploadedFile");
    }
});

const upload = multer({ storage: fileStorageEngine });

app.post("/files", upload.single("givenFilename"), (request, response) => {
    console.log(request.body);
    console.log(request.file);
});

Docker-compose: how to specify the download for the package.json file?

In docker-compose when I rebuild the node container, how do I specify the download for specific packages in package.json file?

For example : If I added nodemon recently and I don’t want it to redownload any other package in the package.json file or prevent some packages from being copied to the container and downloaded, (like express and redis in the code below), how to specify “nodemon” only for the install when I rebuild the container using “–build” flag without any other packages?

Dockerfile:

FROM node:alpine
WORKDIR /app
COPY package.json .
ARG NODE_ENV

RUN npm install
COPY . .
ENV PORT 4001

CMD [ "npm","start" ]

package.json file:

{
  "devDependencies": {
    "@types/express": "^4.17.21",
    "typescript": "^5.2.2"
  },
  "name": "project",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^4.18.2",
    "nodemon": "^3.0.1",
    "redis": "^4.6.10"
  }
}

How do I update an object within an array using findIndex?

I have an array of strings. I want to loop through this array and create a new array that houses each string and the frequency it appears. So, if the string appears more than once the frequency value in the new array gets updated.

From an array that looks like:

let strArr = ["Apple", "Orange", "Banana", "Apple", "Pear", "Banana"];

The desired result would be:

termsArr = [
  {term: "Apple", frequency: 2},
  {term: "Orange", frequency: 1},
  {term: "Banana", frequency: 2},
  {term: "Pear", frequency: 1}
]

I am trying to use findIndex() to check if the termsArr has a matching term in it already (and if yes update the frequency value), but it is failing saying term is not defined. I don’t know why this is.

My full code:

let strArr = ["Apple", "Orange", "Banana", "Apple", "Pear", "Banana"];
let termsArr = [];

for (let i = 0; i < strArr.length; i++) {
  let arrItem = strArr[i];
  let objIndex = termsArr.findIndex((obj => obj.term == arrItem));

  if (objIndex > 0) {
    termsArr[objIndex].frequency = termsArr[objIndex].frequency + 1;
  }
  else {
    termsArr[i] = {
      term: arrItem,
      frequency: 1
    };
  }
}

Would anyone know what I’m doing wrong here?

I thought it might be failing initially because the termsArr is empty, so modified it as such:

  let objIndex = 0;
  if (i < 1) {
    objIndex = termsArr.findIndex((obj => obj.term == arrItem));
  }

But that did not make any difference.

Problems in rendering Gantt Chart in angular 15 using d3

Trying to implement gantt chart using d3 in angular 15, problem with the rendering. Data flow is correct, svg and rectangles are created with my dummy data.

private data = [
    { task: 'Task 1', startTime: '2013-01-01', endTime: '2013-01-10' },
    { task: 'Task 2', startTime: '2013-01-05', endTime: '2013-01-15' },
  ];

private drawChart(): void {
    const margin = { top: 20, right: 30, bottom: 30, left: 40 };
    const width = 800 - margin.left - margin.right;
    const height = 400 - margin.top - margin.bottom;
    console.log('margin', margin);
    const svg = d3
      .select('#gantt-container')
      .append('svg')
      .attr('width', width + margin.left + margin.right)
      .attr('height', height + margin.top + margin.bottom)
      .append('g')
      .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

    console.log('SVG created:', svg);

    svg
      .selectAll('rect')
      .data(this.data)
      .enter()
      .append('rect')
      .attr('x', (d) => this.calculateXPosition(new Date(d.startTime), width))
      .attr('y', (d, i) => i * 30)
      .attr('width', (d) =>
        this.calculateWidth(new Date(d.startTime), new Date(d.endTime), width)
      )
      .attr('height', 20)
      .style('fill', 'steelblue');

    console.log('Rectangles created:', svg.selectAll('rect').nodes());
  }

  private calculateXPosition(date: Date, width: number): number {
    return (date.getTime() / this.getMaxMilliseconds()) * width;
  }

  private calculateWidth(
    startDate: Date,
    endDate: Date,
    width: number
  ): number {
    return (
      ((endDate.getTime() - startDate.getTime()) / this.getMaxMilliseconds()) *
      width
    );
  }

  private getMaxMilliseconds(): number {
    const maxDate = d3.max(this.data, (d) => new Date(d.endTime) as Date);
    return maxDate ? maxDate.getTime() : 0;
  }

scaleTime().doamin() also not accepting the parameters that’s why calculating scale and width manually.

Nothing is displayed on the page
Here’s my template:

<div id="gantt-container"></div>

and css:

#gantt-container { width: 100%; height: 400px; }

Also tried the @viewChild but still no success. Please help!