connect a servise worker to a contect script

In short, I want that when you press my extension button from the context menu, the content script (contect-script) will be added to the web page temporarily. I tried to use sendMessage() but it just didn’t work.

Any help will be appreciated:)

//This is the servise worker (eventPage)

chrome.runtime.onInstalled.addListener(() => {
 chrome.contextMenus.create({
   id: 'select',
   title: 'select',
   type: 'normal',
   contexts: ['all']
 });

})
chrome.contextMenus.onClicked.addListener(function (clickDate) {
 if (clickDate.menuItemId == 'select') {
   //send massege to make content-script start operate
  chrome.runtime.sendMessage('start');

 }
});



-------------------------------------------------------------------------


//lets say that this is the content-script
chrome.runtime.onMessage.addListener(function(response,sender,sendResponse){

if(response == 'start'){

// js code that is inserted into the site
}
});
{
"manifest_version": 3,

"name": "SendFast",
"description": "This extension makes it easier to send information",
"version": "1.0",
"icons": {
  "128": "16-nahum.png",
  "48": "64-nahum.png",
  "16": "16-nahum.png"
},

"action": {
  "default_icon": "16-nahum.png",
  "default_popup": "popup.html"
},
"permissions":["contextMenus","activeTab"],


"background":{
  "service_worker": "eventPage.js"
},
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content-script.js"]
  }
]

}

change day by clicking on buttom

i want each time that im clickig on button that show me the Next day from day array list , can some one help me ?( the only way that i could get a answer is Math.random() to have difference result each time i am clicking on button , but i want that show me the next day each time i am clicking on it .


<button onclick='day()'>Click to see</button>
<script>
    function day(){
       var days =['Monday','Thuesady','Wensday','Thursday','Friday','Saturday','Sunday']
        document.getElementById("demo").innerHTML = days[Math.floor(Math.random() *7)];} 
        
    }
</script>

CSS Grid spacing increases on click

I am using a grid display for the body, and in one of my grid template containers, I have a nested grid template to organize my projects. however, whenever I click on a project and it expands it doubles the spacing between the body grid container elements causing the website to double in length.

body{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
    grid-template-areas: 
    "text text text"
    ". picture ."
    "text text text "
    ". resume . "
    "text text text "
    "projects projects projects"
    "text  text text "
    ". text  ."
    ;
    

}

.projects{
    grid-area: projects;    
    align-items: center;
    display: grid;
    grid-template-columns: 2fr 2fr 2fr;
    grid-template-rows: 2fr 2fr 2fr;
    grid-template-areas:
    "project project project"
}   

Here is the Javascript Function to open the project

function openproject(){
    var text = document.getElementById("project") 
    var project = document.getElementById("project")
    var project2 = document.getElementById("project 2")
    if (text.style.display=="none"){
        text.style.display ="inline"
        project.style.backgroundColor = "hsl(49 37% 94%)"
        project.style.color ="var(--bg-color)"
        project2.style.display ="none" 
         
    }else{
        text.style.display ="none" 
        project.style.textDecoration="none"
        project.style.backgroundColor="var(--bg-color)"
        project.style.color="hsl(49 37% 94%)"
        project2.style.display ="inline" 
        
    }
}

and the HTML is essentially just variations of this

 <div class="projects">
        <div class="project" id="project" onclick="openproject()">
          Project Name! 
          <span id="projectText" class="projectText" style="display: none">
            <p>
              Text
            </p>
            <a
              href=link
              target="_blank"
              style="text-decoration: none; color: var(--bg-color)"
            >
              <strong> Check Out the Project! </strong>
            </a>
          </span>
        </div>

Thank You in advance!

is the any function that converts to lowerCase and at the same time Capitalizes the first chars in the given strings? [closed]

Hello! all Engineers and programmers! There should be a function to make all characters in a given line of string or even list convert to lowerCase and at the same time Capitalize the first chars in the given strings. I found it very useful and have used my own functions in a variety of places such as search and delete, functions, where the user might write the wrong spelling name, mixed capitalized and lowercase.

Why there is not a built-in function that converts to lowerCase and at the same time Capitalizes the first chars in the given strings and removes punctuations?

I know how to solve it, However, I think there should be a generalized algorithm for this implication. Since we use it frequently, Don’t you agree?

If you know any, please share with us here! for future users!

Thanks!

Javascript, maximun call stack size exceeded

I was writing some code for a widget in “Scriptable” that shows random word at a certain time. The widget calls itself with a timeout, on iPad. But it’s exceeding the stack size. How do I solve this? I am using Javascript within “Scriptable” framework, so I don’t have much freedom.

kanjiObj: Object; kanjiKeys: List; Timer().schedule(timeinterval, repeat, callback)

var randomNum = Math.floor(Math.random()*150)+1
var kanji = kanjiKeys[randomNum]
var kanjiMeaning = kanjiObj[kanjiKeys[randomNum]]

if(config.runsInWidget){
  let widget = createWidget()
  Script.setWidget(widget)
  Script.complete()
  
function createWidget(){
  let widget = new ListWidget()
  widget.addText(kanji + "=>" + kanjiMeaning)
  widget.wait = new Timer().schedule(1000*60*60, 150, createWidget())

Navigation .a and help understand

Need help understanding if what my wicked mind has stumbled across and what thought I put back into universe has done any justice for my keenly thought out plan? Navigation is needed to assure my Renaissance..a

how to run this code using phantomjscloud

this e Node js script is a web crawler using puppeteer + a rotating IP using proxyrack but I need to run this code in phantomjscloud I need each browser to have its own IP address, how can I do that ??
this e Node js script is a web crawler using puppeteer + a rotating IP using proxyrack but I need to run this code in phantomjscloud I need each browser to have its own IP address, how can I do that ??

const puppeteer = require('puppeteer');
const langBtns = require('./langBtns');
const proxy = require('./proxy');
const { promisify } = require('util');
const sleep = promisify(setTimeout);
const devices = Object.values(puppeteer.devices);       //Set of mobile devices provided by puppeteer

//Array of all objects found in the langBtns.JSON file
let choices = Object.values(langBtns);
let goodBtnSelector;
let windows = 1000000;       //The total number of windows to be opened throughout the execution of the code
let concurrency = 10;    /* The number of windows running concurrently.
                           This variable acts like a semaphore, whenever a window is running, it is decremented;
                           and whenever a window finishes execution, it is incremented to allow more windows to open */
let flags = [];
flags.fill(true);

let startTime;
let endTime;
let elapsedTime;
let counter = 0;

class BrowserHandler{
    constructor(index) {
        const launch_browser = async () => {
            this.index = index;
            this.browser = false;
            this.browser = await puppeteer.launch({
                headless: false,
                slowMo: 10,
                executablePath:
                "C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
                args: [
                    `--proxy-server=${proxy.proxyProvider}`,
                    "--no-sandbox",
                    "--disable-setuid-sandbox",
                    "--disable-dev-shm-usage",
                    "--disable-accelerated-2d-canvas",
                    "--no-first-run",
                    "--no-zygote",
                    "--disable-gpu",
                    "--disable-notifications"]
            });
            this.browser.on('disconnected', async() => {
                if(this.status === 0){
                    console.log("Browser ", this.index, " disconnected.");
                    concurrency++;
                    doStuff(index).catch(e => {
                        console.log('Error happened, Oops: ', e);
                    });
                }
            });
        };
        (async () => {
            await launch_browser();
            console.log("Browser", this.index, "connected.");
        })();
    }
    setStatus(status){
        this.status = status;
    }
}

const wait_for_browser = browser_handler => new Promise((resolve, reject) => {
    const browser_check = setInterval(() => {
        if (browser_handler.browser !== false) {
            clearInterval(browser_check);
            resolve(true);
        }
    }, 100 );
});



async function start(){
    startTime = performance.now();
    for (let i = 0; i < windows; i++) {
        if(concurrency !== 0){
            doStuff(i).catch(e => {
                console.log('Error happened, Oops: ', e);

            });
        }
        while(concurrency === 0) {
            await sleep(100);
        }
    }
}

start();

async function checkCounter() {
    if (counter === windows) {
        endTime = performance.now();
        elapsedTime = (endTime - startTime)*0.001;  //To seconds
        if(elapsedTime < 60){
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(2), " seconds");
        }else if(elapsedTime < 3600){
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(2) / 60, " minutes");
        }else{
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(3) / 3600, " hours");
        }
        process.exit();
    }
}

async function doStuff(index) {
    concurrency--;
    const browser_handler = new BrowserHandler(index);
    await browser_handler.setStatus(0);
    await wait_for_browser(browser_handler);
    const [page] = await browser_handler.browser.pages();
    await page.setDefaultNavigationTimeout(0);
    const randInt = Math.floor(Math.random() * 25001);
    if(randInt % 2 === 0){      //Choose mobile
        const device = devices[Math.floor(Math.random() * devices.length)];
        console.log("");
        console.log("Browser ", index, " Device: " , device.name);
        await page.emulate(device);
    }
    else{
        console.log("Browser ", index, " Device: Desktop");
    }
    try{
        await page.authenticate({
            username: proxy.username,
            password: proxy.password,
        }).then(async () => {
            let randObj = choices[Math.floor(Math.random() * choices.length)];
            let lang = randObj.language;
            goodBtnSelector = randObj.goodButtonSelector;
            await page.goto(`https://coinmarketcap.com/${lang}/`, {"waitUntil":["load", "networkidle2"], timeout: 60000})
                .then(async () => {
                    try {
                        {
                            const frame = page.mainFrame();
                            const promise = page.waitForNavigation();
                            const element = await frame.waitForSelector(".dQjfsE");
                            await element.click();
                            const element2 = await page.waitForSelector(".bzyaeu-3", {timeout: 5000});
                            await element2.type("Tiger22" , {timeout: 5000});
                            await element2.press('Enter' , {timeout: 5000});
                            await promise;
                        }
                        {
                            const frame = page.mainFrame();
                            await autoScroll(page);
                            const element = await page.waitForSelector(goodBtnSelector);
                            await page.waitForTimeout(2000);
                            await element.click();
                            await page.waitForTimeout(5000);
                            await autoScrollUp(page);
                            console.log("     Browser ", index, "Done ");
                            await browser_handler.setStatus(1);
                            await browser_handler.browser.close();
                            concurrency++;
                            counter++;
                            checkCounter();
                        }
                    }catch(e){
                        browser_handler.status = 0;
                        browser_handler.index = index;
                        await browser_handler.browser.close();
                    }
                })
        })
    }catch(e){
        browser_handler.status = 0;
        browser_handler.index = index;
        await browser_handler.browser.close();
    }
}

async function autoScroll(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}

async function autoScrollUp(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, -distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}



const puppeteer = require('puppeteer');
const langBtns = require('./langBtns');
const proxy = require('./proxy');
const { promisify } = require('util');
const sleep = promisify(setTimeout);
const devices = Object.values(puppeteer.devices);       //Set of mobile devices provided by puppeteer

//Array of all objects found in the langBtns.JSON file
let choices = Object.values(langBtns);
let goodBtnSelector;
let windows = 1000000;       //The total number of windows to be opened throughout the execution of the code
let concurrency = 10;    /* The number of windows running concurrently.
                           This variable acts like a semaphore, whenever a window is running, it is decremented;
                           and whenever a window finishes execution, it is incremented to allow more windows to open */
let flags = [];
flags.fill(true);

let startTime;
let endTime;
let elapsedTime;
let counter = 0;

class BrowserHandler{
    constructor(index) {
        const launch_browser = async () => {
            this.index = index;
            this.browser = false;
            this.browser = await puppeteer.launch({
                headless: false,
                slowMo: 10,
                executablePath:
                "C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
                args: [
                    `--proxy-server=${proxy.proxyProvider}`,
                    "--no-sandbox",
                    "--disable-setuid-sandbox",
                    "--disable-dev-shm-usage",
                    "--disable-accelerated-2d-canvas",
                    "--no-first-run",
                    "--no-zygote",
                    "--disable-gpu",
                    "--disable-notifications"]
            });
            this.browser.on('disconnected', async() => {
                if(this.status === 0){
                    console.log("Browser ", this.index, " disconnected.");
                    concurrency++;
                    doStuff(index).catch(e => {
                        console.log('Error happened, Oops: ', e);
                    });
                }
            });
        };
        (async () => {
            await launch_browser();
            console.log("Browser", this.index, "connected.");
        })();
    }
    setStatus(status){
        this.status = status;
    }
}

const wait_for_browser = browser_handler => new Promise((resolve, reject) => {
    const browser_check = setInterval(() => {
        if (browser_handler.browser !== false) {
            clearInterval(browser_check);
            resolve(true);
        }
    }, 100 );
});



async function start(){
    startTime = performance.now();
    for (let i = 0; i < windows; i++) {
        if(concurrency !== 0){
            doStuff(i).catch(e => {
                console.log('Error happened, Oops: ', e);

            });
        }
        while(concurrency === 0) {
            await sleep(100);
        }
    }
}

start();

async function checkCounter() {
    if (counter === windows) {
        endTime = performance.now();
        elapsedTime = (endTime - startTime)*0.001;  //To seconds
        if(elapsedTime < 60){
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(2), " seconds");
        }else if(elapsedTime < 3600){
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(2) / 60, " minutes");
        }else{
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(3) / 3600, " hours");
        }
        process.exit();
    }
}

async function doStuff(index) {
    concurrency--;
    const browser_handler = new BrowserHandler(index);
    await browser_handler.setStatus(0);
    await wait_for_browser(browser_handler);
    const [page] = await browser_handler.browser.pages();
    await page.setDefaultNavigationTimeout(0);
    const randInt = Math.floor(Math.random() * 25001);
    if(randInt % 2 === 0){      //Choose mobile
        const device = devices[Math.floor(Math.random() * devices.length)];
        console.log("");
        console.log("Browser ", index, " Device: " , device.name);
        await page.emulate(device);
    }
    else{
        console.log("Browser ", index, " Device: Desktop");
    }
    try{
        await page.authenticate({
            username: proxy.username,
            password: proxy.password,
        }).then(async () => {
            let randObj = choices[Math.floor(Math.random() * choices.length)];
            let lang = randObj.language;
            goodBtnSelector = randObj.goodButtonSelector;
            await page.goto(`https://coinmarketcap.com/${lang}/`, {"waitUntil":["load", "networkidle2"], timeout: 60000})
                .then(async () => {
                    try {
                        {
                            const frame = page.mainFrame();
                            const promise = page.waitForNavigation();
                            const element = await frame.waitForSelector(".dQjfsE");
                            await element.click();
                            const element2 = await page.waitForSelector(".bzyaeu-3", {timeout: 5000});
                            await element2.type("Tiger22" , {timeout: 5000});
                            await element2.press('Enter' , {timeout: 5000});
                            await promise;
                        }
                        {
                            const frame = page.mainFrame();
                            await autoScroll(page);
                            const element = await page.waitForSelector(goodBtnSelector);
                            await page.waitForTimeout(2000);
                            await element.click();
                            await page.waitForTimeout(5000);
                            await autoScrollUp(page);
                            console.log("     Browser ", index, "Done ");
                            await browser_handler.setStatus(1);
                            await browser_handler.browser.close();
                            concurrency++;
                            counter++;
                            checkCounter();
                        }
                    }catch(e){
                        browser_handler.status = 0;
                        browser_handler.index = index;
                        await browser_handler.browser.close();
                    }
                })
        })
    }catch(e){
        browser_handler.status = 0;
        browser_handler.index = index;
        await browser_handler.browser.close();
    }
}

async function autoScroll(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}

async function autoScrollUp(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, -distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}

Position of an element with Javascript for a suggest research box

I am trying to make a suggest research box like Google. I am not doing the server side with Ajax for the moment because I have a problem with my code. As you can see on the picture, the position of the suggestion box is not correct.

Positionement problem with JS

Here is the code :

  var values = ["Chatelet", "Gare de Lyon", "Orsay-Ville"];


function positionner() {
var suggest = document.getElementById("suggestion");
var champ = document.getElementById("fmsearch");
suggest.style.left = getLeft(champ) + "px";
suggest.style.top = (getTop(champ) + champ.offsetHeight) + "px";
}

function getLeft(element) {
var offsetLeft = 0;
while (element != null) {
offsetLeft += element.offsetLeft;
element = element.offsetParent;
}
return offsetLeft;
}
function getTop(element) {
var offsetTop = 0;
while (element != null) {
offsetTop += element.offsetTop;
element = element.offsetParent;
}
return offsetTop;
}
positionner();




function suggerer() 
{
  var suggest = document.getElementById("suggestion");
  suggest.innerHTML = "";
  var i, ele;
  for (i=0 ; i<values.length ; i++)
  {
    ele = document.createElement("div");
    ele.innerHTML = values[i];
    suggest.appendChild(ele);
  }
  suggest.style.display = "block";
}

Add filter view hyperlinks and rearrange the column values

I have Sheet1 with existing filter view hyperlinks. I want to find any names that dont have filterviews, then create filterviews with hyperlinks to these names and add them in alphabetical order to the list that already has hyperlinks.

Example:
In Sheet 1, Col C,E,G, new names: Tracy Jack,Maria Jose , Samuel Philips,Karan Tucker, Vincent Lee, Wes Lee do not have a filter view and hyperlink, I want to add filter view and hyperlink to these names and then add them alphabetically to the list of names with hyperlinks in the rows above

Before adding hyperlinks

After adding hyper link to

Tracy Jack (Col C),

Maria Jose , Samuel Philips (Col E),

Karan Tucker, Vincent Lee, Wes Lee(Col G),

I want to add insert these names with links in alphabetical order in the rows above. Please see pic below for final output

After adding and rearranging list

call setContents for Quill works but then cause an error

Please see this code for working with Quilljs:

window.InitialQuill = {
    createQuill: function (quillElement) {
        var options = {
                         debug: 'info',
                         modules: {
                         toolbar: '#toolbar'
                      },
        placeholder: 'write something...',
        readonly: false,
        theme: 'snow'
    };

    new Quill(quillElement, options);
},
getQuillContent: function (quillControl) {
    return JSON.stringify(quillControl.__quill.getContents());
},
getQuillText: function (quillControl) {
    return quillControl.__quill.getText();
},
getQuillHTML: function (quillControl) {
    return quillControl.__quill.root.innerHTML;
},
loadQuillContent: function (quillControl, quillContent) {
    //return quillControl.__quill.setContents(JSON.parse(quillContent), 'api');

    var ops = [
        { insert: 'Hello ' },
        { insert: 'World!', attributes: { bold: true } },
        { insert: 'n' }
    ];
    return quillControl.__quill.setContents(ops,'api')
}
}

I’m using above code in blazor this way:

@inject IJSRuntime JsRuntime

@if(EditorEnabled)
{
<br>
<button class="btn btn-primary" @onclick="GetText">Get Text</button>
<button class="btn btn-primary" @onclick="GetHTML">Get HTML</button>
<button class="btn btn-primary" @onclick="GetEditorContent">Get Content</button>

<br />

<div>
    @EditorContent
</div>
<div>
    @((MarkupString)@EditorHTMLContent)
</div>

<br />
<button class="btn btn-danger" @onclick="SaveContent">Save Content</button>
<button class="btn btn-success" @onclick="LoadContent">Load Content</button>

<br />
<br />
<br />

<div id="toolbar">
    <span class="ql-formats">
        <select class="ql-font">
            <option selected=""></option>
            <option value="serif"></option>
            <option value="tahoma"></option>
        </select>
        <select class="ql-size">
            <option value="small"></option>
            <option selected=""></option>
            <option value="large"></option>
            <option value="huge"></option>
        </select>
    </span>
    <span class="ql-formats">
        <button class="ql-bold"></button>
        <button class="ql-italic"></button>
        <button class="ql-undeline"></button>
        <button class="ql-strike"></button>
    </span>
    <span class="ql-formats">
        <select class="ql-color"></select>
        <select class="ql-background"></select>
    </span>
    <span class="ql-formats">
        <button class="ql-list" value="ordered"></button>
        <button class="ql-list" value="bullet"></button>
        <button class="ql-indent" value="-1"></button>
        <button class="ql-indent" value="+1"></button>
        <select class="ql-align">
            <option selected=""></option>
            <option value="center"></option>
            <option value="right"></option>
            <option value="justify"></option>
        </select>
    </span>
    <span class="ql-formats">
        <button class="ql-link"></button>
    </span>
</div>
}

<div @ref="@DivEditorElement"></div>

@code {
    private string strSavedContent = "";
    private ElementReference DivEditorElement;
    private string EditorContent;
    private string EditorHTMLContent;
    private bool EditorEnabled = true;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if(firstRender == true)
    {
        await JsRuntime.InvokeAsync<string>("InitialQuill.createQuill", DivEditorElement);
    }
}

private async Task GetText()
{
    EditorHTMLContent = "";
    EditorContent = await JsRuntime.InvokeAsync<string>("InitialQuill.getQuillText", DivEditorElement);
}

private async Task GetHTML()
{
    EditorContent = "";
    EditorHTMLContent = await JsRuntime.InvokeAsync<string>("InitialQuill.getQuillHTML", DivEditorElement);
}

private async Task GetEditorContent()
{
    EditorHTMLContent = "";
    EditorContent = await JsRuntime.InvokeAsync<string>("InitialQuill.getQuillContent", DivEditorElement);
}

private async Task SaveContent()
{
    strSavedContent = await JsRuntime.InvokeAsync<string>("InitialQuill.getQuillContent", DivEditorElement);
}

    private async Task LoadContent()
{
    var QuillDelta = await JsRuntime.InvokeAsync<string>("InitialQuill.loadQuillContent", DivEditorElement, strSavedContent);
}
}

All buttons work fine except Load Content. It works and specific text shows in the editor but after then it cause a problem.

Unhandled exception rendering component: An exception occurred executing JS interop: The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1.. See InnerException for more details.
Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1.. See InnerException for more details.

I wrote the code this way:

quillControl.__quill.setContents(JSON.parse(quillContent), 'api');

but I got same error.
Where is my problem? Thanks

I couldn’t understand why this URL “http://localhost:3000/api/orders/income” is responding with empty array [ ]

order.js (router)
Other functions such as create order, delete order, get orders from MongoDB database works perfectly but //GET MONTHLY INCOME Part is not working. Can anyone please fix this problem??

const Order = require("../models/Order");
const {
  verifyToken,
  verifyTokenAndAuthorization,
  verifyTokenAndAdmin,
} = require("./verifyToken");

const router = require("express").Router();

//CREATE

router.post("/", verifyToken, async (req, res) => {
  const newOrder = new Order(req.body);

  try {
    const savedOrder = await newOrder.save();
    res.status(200).json(savedOrder);
  } catch (err) {
    res.status(500).json(err);
  }
});

//UPDATE
router.put("/:id", verifyTokenAndAdmin, async (req, res) => {
  try {
    const updatedOrder = await Order.findByIdAndUpdate(
      req.params.id,
      {
        $set: req.body,
      },
      { new: true }
    );
    res.status(200).json(updatedOrder);
  } catch (err) {
    res.status(500).json(err);
  }
});

//DELETE
router.delete("/:id", verifyTokenAndAdmin, async (req, res) => {
  try {
    await Order.findByIdAndDelete(req.params.id);
    res.status(200).json("Order has been deleted...");
  } catch (err) {
    res.status(500).json(err);
  }
});

//GET USER ORDERS
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
  try {
    const orders = await Order.find({ userId: req.params.userId });
    res.status(200).json(orders);
  } catch (err) {
    res.status(500).json(err);
  }
});

// //GET ALL

router.get("/", verifyTokenAndAdmin, async (req, res) => {
  try {
    const orders = await Order.find();
    res.status(200).json(orders);
  } catch (err) {
    res.status(500).json(err);
  }
});

// GET MONTHLY INCOME  <-----

router.get("/income", verifyTokenAndAdmin, async (req, res) => {
  const date = new Date();
  const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
  const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1));

  

  try {
    const income = await Order.aggregate([
      { $match: { createdAt: { $gte: previousMonth } } },
      {
        $project: {
          month: { $month: "$createdAt" },
          sales: "$amount",
        },
      },
      {
        $group: {
          _id: "$month",
          total: { $sum: "$sales" },
        },
      },
    ]);
    res.status(200).json(income);
    
  } catch (err) {
    res.status(500).json(err);
  }
});

module.exports = router;

Order.js (module)
This is the Order.js module

const mongoose = require("mongoose");

const OrderSchema = new mongoose.Schema(
  {
    userId: { type: String, required: true },
    products: [
      {
        productId: {
          type: String,
        },
        quantity: {
          type: Number,
          default: 1,
        },
      },
    ],
    amount: { type: Number, required: true },
    address: { type: Object, required: true },
    status: { type: String, default: "pending" },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Order", OrderSchema);

index.js
In this part, I declared all the necessary routes along with the order route but I don’t know why only get “/income” part is not responding.

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const productRoute = require("./routes/product");
const cartRoute = require("./routes/cart");
const orderRoute = require("./routes/order");
const stripeRoute = require("./routes/stripe");
const cors = require("cors");

dotenv.config();

mongoose
  .connect(process.env.MONGO_URL)
  .then(() => console.log("DB Connection Successfull!"))
  .catch((err) => {
    console.log(err);
  });

app.use(cors());
app.use(express.json());
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/products", productRoute);
app.use("/api/carts", cartRoute);
app.use("/api/orders", orderRoute);
app.use("/api/checkout", stripeRoute);
 
 const port = process.env.PORT;
 app.listen(port || 5000 , () => {

    console.log(`Backend server is running on port ${port}!`);
});

verifyToken.js

const jwt = require("jsonwebtoken");

const verifyToken = (req, res, next) => {
  const authHeader = req.headers.token;
  if (authHeader) {
    const token = authHeader.split(" ")[1];
    jwt.verify(token, process.env.JWT_SEC, (err, user) => {
      if (err) res.status(403).json("Token is not valid!");
      req.user = user;
      next();
    });
  } else {
    return res.status(401).json("You are not authenticated!");
  }
};

const verifyTokenAndAuthorization = (req, res, next) => {
  verifyToken(req, res, () => {
    if (req.user.id === req.params.id || req.user.isAdmin) {
      next();
    } else {
      res.status(403).json("You are not alowed to do that!");
    }
  });
};

const verifyTokenAndAdmin = (req, res, next) => {
  verifyToken(req, res, () => {
    if (req.user.isAdmin) {
      next();
    } else {
      res.status(403).json("You are not alowed to do that!");
    }
  });
};

module.exports = {
  verifyToken,
  verifyTokenAndAuthorization,
  verifyTokenAndAdmin,
};

Image always renders when shown on page, but not loading when saving HTML as PNG file via library

I’m currently working on a small side-project using React, where I have developed an app that displays a Tweet component that can be customized by the user to ultimately be saved as a PNG or SVG. I have a Next.js application deployed on Vercel that contains an API endpoint (that’s all I’m using this deployment) that when called, calls the Twitter API and retrieves all of the necessary data to display the Tweet component. This is working great, and the Tweet component displays just fine, the profile picture (PFP) loads no problem:

Tweet Snippets

This profile picture is 48px by 48px, and is less than 10KB in size. In order to add export functionality, I am using this neat library html-to-image.

The issue is that when I export the image, all of the UI components render correctly EXCEPT for the profile picture. If I use images not from the Twitter CDN, they usually appear on this exported image. What my theory is is that it is just taking too long for Twitter to serve this image and the html-to-image library is not waiting long enough for the image to load, so it just decides not to include it:

enter image description here

This is the code I am using to export the image (my onclick function`):

import { toBlob, toPng, toSvg } from "html-to-image";
...
const onExpClick = () => {
    if (ref.current === null) {
        return;
    }
    if (exportOptions.format === "PNG") {
        toBlob(ref.current, {
            cacheBust: true,
            width: 1100,
            height: 700,
            pixelRatio: exportOptions.scale,
            style: {
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                justifyContent: "center",
                backgroundImage:
                    "linear-gradient(135deg,#ffddc7,#ffd5c7,#ffcac8,#fecad6,#ffcde8,#ebcefc,#dfcffe,#cad5f3,#d9eafe)",
            },
        })
            .then((blob) => {
                if (blob) {
                    FileSaver.saveAs(blob, "tweet.png");
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }
    ...
};

I am posting because I am unsure of what to do from here, as I am unaware of how front-end developers typically go about solving this problem. If it helps, the link to the profile picture is already known by the time the user presses “export”, could one way to solve this be by downloading the image to local storage and then serving it from there when its time to re-build the component to be used in an exported canvas? That way we wouldn’t have to go back out to the Twitter CDN just to get an Image we already have? Let me know what you would do. I am also willing to fork the html-to-image module if I could achieve what I am doing from that, but so far looking into it I have not found anything that would resolve this issue and it doesn’t seem like that repository is that well maintained anymore.

How do I append a blob file using @azure/storage-blob sdk ? (NodeJS)

My file “mainfile.json” in blob storage has the following content :

[
  { "name": "abc", "id": "01", "location": "random" },
  { "month": "Jan", "project": "50%", "training": "50%" },
]

The data I’m trying to add to it is this :

{"month": "Feb", "project":"60%", "training":"40%"}

I want it to be something like this :

[
  { "name": "abc", "id": "01", "location": "random" },
  { "month": "Jan", "project": "50%", "training": "50%" },
  {"month": "Feb", "project":"60%", "training":"40%"}
]

I’m using @azure/storage-blob sdk to carry out the same and here’s my code below :

const blobServiceClient = require("./getCred");
const fs = require("fs");

async function appendBlob() {
  const containerClient =
    blobServiceClient.getContainerClient("containername");
  //gets the main content from a blob
  const blobClient = containerClient.getBlobClient("mainfile.json");
  //the new appended content gets written into this blob
  const blockBlobClient = containerClient.getBlockBlobClient("data.json");
  // the data that needs to be appended
  const data = fs.readFileSync("new-data.json", "utf-8", (err) => {
    if (err) {
      console.log("File not read");
    }
  });

  // Get blob content from position 0 to the end
  // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
  const downloadBlockBlobResponse = await blobClient.download();
  const downloaded = (
    await streamToBuffer(downloadBlockBlobResponse.readableStreamBody)
  ).toString();
  const append = await appendingFile(downloaded, data);

  const uploadBlobResponse = await blockBlobClient.upload(
    append,
    append.length
  );
  console.log(
    `Uploaded block blob to testing.json successfully`,
    uploadBlobResponse.requestId
  );

  // [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
  async function streamToBuffer(readableStream) {
    return new Promise((resolve, reject) => {
      const chunks = [];
      readableStream.on("data", (data) => {
        chunks.push(data instanceof Buffer ? data : Buffer.from(data));
      });
      readableStream.on("end", () => {
        resolve(Buffer.concat(chunks));
      });
      readableStream.on("error", reject);
    });
  }

  async function appendingFile(content, toBeAdded) {
    return new Promise((resolve, reject) => {
      let temp = content.concat(toBeAdded);
      console.log(temp);
      resolve(temp);
      reject(new Error("Error occurred"));
    });
  }
}

But I get the following as the output :

[
  {
    "name": "KK",
    "id": "01",
    "location": "chennai"
  },
  {
    "month": "December",
    "project": "50%",
    "training": "50%"
  }
]
{
  "month": "January",
  "adaptive-cards": "50%",
  "azure-func-app": "50%"
}

My entire approach could be wrong as I’m new to coding. Please help me with this. Thanks in advance.

Error passing td.parentNode javascript on ‘onclick’ method

Im working with DataTables(https://datatables.net/examples/basic_init/zero_configuration.html) and javascript, right now Im dealing with ‘edit’ behavior, If I click on edit icon a whole row should be editable.

Now on my javascript file Im using ‘fnCreatedCell’ property (https://legacy.datatables.net/ref#fnCreatedCell) and passing a nTd.parentNode as parameter inside my button icon on ‘onclick=enableEditableRow(${nTd.parentNode})’ method, so my problem here is for some reason javascript is throwing me an error:

Uncaught SyntaxError: Unexpected identifier

Its not even useful… IDK how exactly pass this parameter.

Here is my code:

{
            data: null,
            title: 'Edit',
            orderable: false,
            fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html(`<button type="button" class="btn btn-outline-secondary" 
                onclick='enableEditableRow(${oData.id}, ${iRow}, ${nTd.parentNode})'>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16">
                        <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
                        <path fill-rule="evenodd" d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
                    </svg>
                </button>`);
            }
}

How to insert data in many to many relation that has custom fields in typeorm/nestjs?

How to save data in many to many relation that has custom fields in nestjs/typeorm
Here, I have created relation between cart, customer, and product entity. Relation is as follows:
Cart and Customer - OneToOne
Cart and CartProduct(Junction table for cart and product) OneToMany
Product and CartProduct(Junction table for cart and product) OneToMany

customer.entity.ts

import {
  Column,
  Entity,
  OneToMany,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Cart } from './cart.entity';

@Entity()
export class Customer {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToOne(() => Cart, (cart) => cart.customer)
  cart: Cart;
}

cart.entity.ts

import {
  Entity,
  JoinColumn,
  OneToMany,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { CartProduct } from './cartProduct.entity';
import { Customer } from './customer.entity';

@Entity()
export class Cart {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToOne(() => Customer, (customer) => customer.cart)
  @JoinColumn({ name: 'customerid' })
  customer: Customer;

  @OneToMany(() => CartProduct, (cartProducts) => cartProducts.cart)
  cartProducts: CartProduct[];
}

product.entity.ts

import {
  Column,
  Entity,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Brand } from './brand.entity';
import { CartProduct } from './cartProduct.entity';
import { OrderProduct } from './orderProduct.entity';
import { SubCategory } from './subCategory.entity';

@Entity()
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany(() => CartProduct, (cartProduct) => cartProduct.product)
  cartProducts: CartProduct[];
}

cartProduct.entity.ts Junction table for cart and product

import { Column, Entity, ManyToOne } from 'typeorm';
import { Cart } from './cart.entity';
import { Product } from './product.entity';

@Entity()
export class CartProduct {
  @Column()
  quantity: number;

  @ManyToOne(() => Cart, (cart) => cart.cartProducts, { primary: true })
  cart: Cart;

  @ManyToOne(() => Product, (product) => product.cartProducts, {
    primary: true,
  })
  product: Product;
}

Now, while creating cart what I did is,

async addProductToCart(
    customerid: number,
    productid: number,
    quantity: number,
  ): Promise<Cart> {
    const customer = await this.customer.findOne({ id: customerid });
    const cart = this.cart.create();
    const product = await this.product.findOne({ id: productid });
    cart.customer = customer;
    const cartProducts = this.cartProducts.create({
      cart,
      product,
      quantity,
    });
    cart.cartProducts = [cartProducts];
    await this.cartProducts.save(cartProducts); //if i add this line then it 
    // says, NOT NULL constraint failed: cart_product.cartId
    return this.cart.save(cart);
  }

When I make request to this addProductToCart function, then data don’t get stored in the database.
So, how to properly insert data using many to many relation with custom field.