Uploading video to blogger from NodeJS

I am trying to upload video to blogger using following code. I am able to get the response from my code. I am getting stuck at, that I am not able to transfer the video data to blogger.

My NodeJS code:

const axios = require('axios');
const fs = require('fs');
const path = require('path');

const videoPath = '/Downloads/11H3Bepq6Hx_seEhq2iO7OSW1zC01PnKo.mp4';
const videoStream = fs.createReadStream(videoPath);

let data = '{"protocolVersion":"0.8","createSessionRequest":{"fields":[{"external":{"name":"file","filename":"11H3Bepq6Hx_seEhq2iO7OSW1zC01PnKo.mp4","put":{},"size":1018020}},{"inlined":{"name":"title","content":"11H3Bepq6Hx_seEhq2iO7OSW1zC01PnKo.mp4","contentType":"text/plain"}},{"inlined":{"name":"addtime","content":"1726417159033","contentType":"text/plain"}},{"inlined":{"name":"onepick_version","content":"v2","contentType":"text/plain"}},{"inlined":{"name":"onepick_host_id","content":"10","contentType":"text/plain"}},{"inlined":{"name":"onepick_host_usecase","content":"RichEditor","contentType":"text/plain"}},{"inlined":{"name":"tos","content":"true","contentType":"text/plain"}},{"inlined":{"name":"blogID","content":"add-your-own-id-here","contentType":"text/plain"}},{"inlined":{"name":"postID","content":"add-your-own-id-here","contentType":"text/plain"}}]}}';

let config = {
    method: 'post',
    url: 'https://docs.google.com/upload/blogger/resumable?authuser=0&opi=98421741',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
        'Accept': '*/*',
        'Sec-Fetch-Site': 'same-origin',
        'Accept-Language': 'en-IN,en-GB;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Sec-Fetch-Mode': 'cors',
        'Host': 'docs.google.com',
        'Origin': 'https://docs.google.com',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15',
        'Referer': 'https://docs.google.com/',
        'Content-Length': '860',
        'Connection': 'keep-alive',
        'Sec-Fetch-Dest': 'empty',
        'Cookie': '',
        'X-Goog-Upload-Header-Content-Type': 'video/mp4',
        'X-Goog-Upload-Header-Content-Length': '1018020',
        'X-Client-Pctx': 'CgcSBWjtl_cu',
        'X-Goog-Upload-Protocol': 'resumable',
        'X-Goog-Upload-Command': 'start'
    },
    data: data
};

axios.request(config)
    .then((response) => {
        console.log(JSON.stringify(response.data));
        
        const boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
        const body = `--${boundary}rn` +
            `Content-Disposition: form-data; name="metadata"rnrn` +
            `${data}rn` +
            `--${boundary}rn` +
            `Content-Disposition: form-data; name="Filedata"; filename="${path.basename(videoPath)}"rn` +
            `Content-Type: video/mp4rn` +
            `Content-Transfer-Encoding: binaryrnrn` +
            `${fs.readFileSync(videoPath, { encoding: 'binary' })}rn` +
            `--${boundary}--`;

        let config = {
            method: 'post',
            url: `https://docs.google.com/upload/blogger/resumable?authuser=0&opi=98421741&upload_id=${response.data['sessionStatus']['upload_id']}&upload_protocol=resumable`,
            headers: {
                'Content-Type': `multipart/related; boundary=${boundary}`,
                'Accept': '*/*',
                'Sec-Fetch-Site': 'same-origin',
                'Accept-Language': 'en-IN,en-GB;q=0.9,en;q=0.8',
                'Accept-Encoding': 'gzip, deflate, br',
                'Sec-Fetch-Mode': 'cors',
                'Host': 'docs.google.com',
                'Origin': 'https://docs.google.com',
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15',
                'Referer': 'https://docs.google.com/',
                'Content-Length': '1018020',
                'Connection': 'keep-alive',
                'Sec-Fetch-Dest': 'empty',
                'Cookie': '',
                "X-Goog-Upload-Protocol": "multipart",
            },
            "cache": "default",
            "credentials": "include",
            "mode": "cors",
            "redirect": "follow",
            "referrer": "https://docs.google.com/",
            "referrerPolicy": "origin",
            data: body
        };

        axios.request(config)
            .then((response) => {
                console.log(JSON.stringify(response.data));
            })
            .catch((error) => {
                console.log(error);
            });
    })
    .catch((error) => {
        console.log(error);
    });

The response I am getting from blogger:

{"sessionStatus":{"state":"FINALIZED","externalFieldTransfers":[{"name":"file","status":"COMPLETED","bytesTransferred":0,"bytesTotal":1018020,"putInfo":{"url":"https://docs.google.com/upload/blogger/resumable?authuser=0&opi=98421741&upload_protocol=resumable&upload_id=AD-8ljsco6WMZdutraflzfW1AtmJ1k5OYO2PudwjgaYof8PaCSqRn5kqZofxDnlNtVlaig95-jM&file_id=000"},"content_type":"video/mp4"}],"additionalInfo":{"uploader_service.GoogleRupioAdditionalInfo":{"completionInfo":{"status":"SUCCESS"}}},"upload_id":"AD-8ljsco6WMZdutraflzfW1AtmJ1k5OYO2PudwjgaYof8PaCSqRn5kqZofxDnlNtVlaig95-jM"}}

You see the bytesTransferred shows 0. It means video data is not transferred.

When tranferring through browser, response generated is as follows:

{"sessionStatus":{"state":"FINALIZED","externalFieldTransfers":[{"name":"file","status":"COMPLETED","bytesTransferred":1018020,"bytesTotal":1018020,"putInfo":{"url":"https://docs.google.com/upload/blogger/resumable?authuser=0u0026opi=98421741u0026upload_id=AD-8ljvGMD4Mg6k6oSxW74UCa0gsZKJt3grXpwNS6UFtbCnu0D-HyPXF5_B_Krr1aJ-mZQjJ3jcicPLGUSAARAl4TJdDosvQiwltu-Xd139T0aI0u0026file_id=000"},"content_type":"video/mp4"}],"additionalInfo":{"uploader_service.GoogleRupioAdditionalInfo":{"completionInfo":{"status":"SUCCESS","customerSpecificInfo":{"contentId": "ed34314396d57090"}}}},"upload_id":"AD-8ljvGMD4Mg6k6oSxW74UCa0gsZKJt3grXpwNS6UFtbCnu0D-HyPXF5_B_Krr1aJ-mZQjJ3jcicPLGUSAARAl4TJdDosvQiwltu-Xd139T0aI0"}}

Here bytesTransferred is 1018020 same as bytesTotal.

Upon more research, I came across this code:

h.Xc = function() {
        var a = yd(this.Ca);
        this.V.length != null && (a["Content-Length"] = this.V.length);
        a = fac(a);
        a["X-Goog-Upload-Protocol"] = "multipart";
        a["Content-Type"] = "multipart/related; boundary=" + this.U;
        this.H = "Transferring";
        this.N = new DZ;
        this.O.te();
        this.O.listen(this.N, "progress", this.pda);
        this.O.listen(this.N, "complete", this.oda);
        var b = this.N,
            c = b.send,
            d = this.Ia,
            e = this.Ha,
            f = "--" + this.U + 'rnContent-Disposition: form-data; name="metadata"rnrn' + (this.Ga + "rn--") + this.U + 'rnContent-Disposition: form-data; name="Filedata"rnContent-Transfer-Encoding: ' +
            (this.La + "rnrn") + this.V + "rn--" + this.U + "--rn";
        this.wa = f.length - this.V.length;
        c.call(b, d, e, f, a)
    };

But still the error is there. In my code, to simulate please login in blogger. Grab cookie value. Also replace add-your-own-id-here in data variable with appropriate values.

Thank You

Cannot access JavaScript Modules from Cloudflare R2…Why am I getting CORS Errors?

I am using R2 to serve static files for my webpage index.html:


    <script type="module" src="{% static 'js/display.js' %}"></script>
    <script type="module" src="{% static 'js/run-model.js' %}"></script>    
    <script src="{% static 'js/file.js' %}"></script>

display.js

import { variable1, function1} from "./run-model.js";

run-model.js

import { variable2, function2} from "./display.js";

The site is able to load the js files, but then in addition it throws CORS errors for the modules as they try to import variables. I have tried adding a rule in Cloudflare to set an Access-Control-Allow-Origin header to * and also set a CORS policy on the bucket for anything from my domain https://www.example.com. Still the same issue… Why is this?

Access to script at ‘https://<>.r2.cloudflarestorage.com/bucket/js/display.js’ from origin ‘https://www.example.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

GET https://<>.r2.cloudflarestorage.com/bucket/js/display.js net::ERR_FAILED 400 (Bad Request)

Access to script at ‘https://<>.r2.cloudflarestorage.com/bucket/js/run-model.js’ from origin ‘https://www.example.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

GET https://<>.r2.cloudflarestorage.com/bucket/js/run-model.js net::ERR_FAILED 400 (Bad Request)

The two failed items don’t have the Access-Control-Allow-Origin header and have the Content-Type header as ‘application/xml’:

enter image description here

How to add thresholds with specific ranges to a Highcharts graph?

I’m working on a Highcharts line chart where I need to add thresholds with specific ranges on the x-axis. I want certain areas of the chart to be colored based on these thresholds, Here are the details of my problem:
I’ve used the zone configuration options in Highcharts to try to implement this, but I’m not getting the desired results. Here’s the code I’ve used so far:

Thresholds:

Threshold 1:
    Value: 10°C
    Range: from 100 meters to 500 meters (on the x-axis)

Threshold 2:
    Value: 20°C
    Range: from 600 meters to 2682 meters (on the x-axis)

I want to:

Color the area between 100 meters and 500 meters red if the temperature is above 10°C.
Color the area between 600 meters and 2682 meters red if the temperature is above 20°C.
Display dashed lines at the thresholds of 10°C and 20°C.




  Highcharts.chart('container', {
  title: {
    text: 'Thermal Profile'
  },
  series: [
    {
      name: 'Temperature 0-10°C',
      data: [
        [0, 20.18], [1, 20.21], [2, 20.38], /* ... */ [99, 19.95] // Data filtered for temperatures below 10°C
      ],
      color: '#83c081', // Color for temperatures < 10°C
      zones: [
        {
          value: 10,
          color: '#83c081'
        }
      ]
    },
    {
      name: 'Temperature 10-20°C',
      data: [
        [100, 10.5], [101, 11.2], /* ... */ [499, 19.8] // Data filtered for temperatures between 10°C and 20°C
      ],
      color: '#dc0059', // Color for temperatures > 10°C and < 20°C
      zones: [
        {
          value: 20,
          color: '#dc0059'
        }
      ]
    },
    {
      name: 'Temperature 20-30°C',
      data: [
        [600, 21.5], [601, 22.0], /* ... */ [2682, 27.5] // Data filtered for temperatures between 20°C and 30°C
      ],
      color: '#83c081', // Color for temperatures > 20°C
      zones: [
        {
          color: '#83c081'
        }
      ]
    }
  ],
  xAxis: {
    title: {
      text: 'Distance (m)'
    },
    categories: ["0", "550", "1100", "1650", "2150", "2682"]
  },
  yAxis: {
    title: {
      text: 'Temperature (°C)'
    },
    plotLines: [
      {
        color: '#dc0059',
        dashStyle: 'Dash',  // Dashed line
        value: 10, // Threshold at 10°C
        width: 2,
        label: {
          text: 'Threshold 10°C',
          align: 'right'
        }
      },
      {
        color: '#dc0059',
        dashStyle: 'Dash',  // Dashed line
        value: 20, // Threshold at 20°C
        width: 2,
        label: {
          text: 'Threshold 20°C',
          align: 'right'
        }
      }
    ]
  },
  tooltip: {
    headerFormat: '<b>{point.x} m</b><br>',
    pointFormat: 'Temperature: {point.y} °C'
  }
});

Trouble making API POST request with Next.js

I am a noob when it comes to anything related to backend, also new in Next.js and TypeScript.
I am trying to make a POST request to an API, which should receive formData and create a new listing based on that formData. I am trying to do this with Next.js server actions and route handlers.

Here is my code:

This is from the form component:

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        const form = e.currentTarget as HTMLFormElement;
        const formData = new FormData(form);
        
        const address = formData.get("address");
        const mail = formData.get("mail");
        const region_id = selectedRegion?.id; //these come from states
        const agent_id = selectedAgent?.id;  //these come from states
        const city_id = selectedCity?.id;   //these come from states
        const area = formData.get("area");
        const price = formData.get("price");
        const type = formData.get("type");
        const cover = formData.get("cover"); // This is the file input

        try {
            console.log(address, mail, region_id, agent_id, city_id, area, price, type, cover);

            const newFormData = new FormData();

            newFormData.append("address", address as string);
            newFormData.append("mail", mail as string);
            newFormData.append("region_id", region_id as any);
            newFormData.append("agent_id", agent_id as any);
            newFormData.append("city_id", city_id as any);
            newFormData.append("area", area as string);
            newFormData.append("price", price as string);
            newFormData.append("type", type as string);
            newFormData.append("cover", cover as File); 
            
            await addListingAction(newFormData)
        } catch (error) {
            alert(`Error: ${error}`);
        }
    };

This is my server action:

    export async function addListingAction(formData: FormData) {
  try {
    await addListing(formData);
  } catch (error) {
    console.log(error);
  } finally {
    revalidatePath("/")
  }
}

my api.ts file:

export async function addListing(formData: FormData) {

  return await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/add-listing`, {
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
}

and my route.ts file:

import { NextResponse } from 'next/server';

export async function POST(req: Request) {
  try {
    const formData = await req.formData();

    const address = formData.get("address");
    const mail = formData.get("mail");
    const region_id = formData.get("region_id");
    const agent_id = formData.get("agent_id");
    const city_id = formData.get("city_id");
    const area = formData.get("area");
    const price = formData.get("price");
    const type = formData.get("type");
    const cover = formData.get("cover") as File | null;

    const form = new FormData();
    if (address) form.append("address", address);
    if (mail) form.append("mail", mail);
    if (region_id) form.append("region_id", region_id);
    if (agent_id) form.append("agent_id", agent_id);
    if (city_id) form.append("city_id", city_id);
    if (area) form.append("area", area);
    if (price) form.append("price", price);
    if (type) form.append("type", type);
    if (cover instanceof File) form.append("cover", cover);

    const REDBERRY_API_TOKEN = process.env.REDBERRY_API_TOKEN;

    if (!REDBERRY_API_TOKEN) {
      throw new Error("Missing API token");
    }


    const response = await fetch('https://api.real-estate-manager.redberryinternship.ge/api/real-estates', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${REDBERRY_API_TOKEN}`,
      },
      body: form,
    });


if (!response.ok) {
  let errorResponse;
  try {
    errorResponse = await response.json();
  } catch {
    errorResponse = await response.text();
  }
  console.error('HTTP error! Status:', response.status, 'Response:', errorResponse);
  return NextResponse.json(
    { message: 'API request failed', error: errorResponse },
    { status: response.status }
  );
}


  const listing = await response.json();

  return NextResponse.json({ listing }, { status: 201 });

  } catch (error) {
    const message = error instanceof Error ? error.message : 'An unexpected error occurred';
    console.error('Error creating listing:', message);
  return NextResponse.json(
    { message: 'Failed to create listing', error: message },
    { status: 500 }
  );
  }
}

The API documentation says that the curl request looks like this:

    curl -X 'POST' 
  'https://api.real-estate-manager.redberryinternship.ge/api/real-estates' 
  -H 'accept: application/json' 
  -H 'Authorization: Bearer API_TOKEN' 
  -H 'Content-Type: multipart/form-data' 
  -F 'region_id=1' 
  -F 'price=100000' 
  -F 'zip_code=0101' 
  -F 'area=100.5' 
  -F 'city_id=1' 
  -F 'address=example address' 
  -F 'agent_id=371' 
  -F 'bedrooms=3' 
  -F 'is_rental=0' 
  -F '[email protected];type=image/png' 
  -F 'description=house near metro station'

and the response looks like this:

"price": "100000",
  "zip_code": "0101",
  "area": "100.5",
  "city_id": "1",
  "address": "example description",
  "agent_id": "371",
  "bedrooms": "3",
  "is_rental": "0",
  "description": "house near metro station",
  "image": "https://api.real-estate-manager.redberryinternship.ge/storage/images/vZ6KRjLiBIoVqwl4GMniE598mAzno8wqzCkZyg3f.png",
  "created_at": "2024-09-15T16:43:21.000000Z",
  "id": 450

The error I am getting is:

Error creating listing: Unexpected token ‘<‘, “<!DOCTYPE “… is not valid JSON
POST /api/add-listing 500 in 931ms
{
message: ‘Failed to create listing’,
error: ‘Unexpected token ‘<‘, “<!DOCTYPE “… is not valid JSON’
}

Any help would be greatly appreciated.

Shuffling a list based on specific requirements

I am building an online language experiment using JavaScript. As a beginner-level javaScript learner, I am having difficulties shuffling a list based on specific requirements and sampling items from the shuffled list. I would very much appreciate any help in figuring out how to do this.

I have a list of words as follows. Condition X1 = X2, Y1 = Y2. This is to make things clearer later.

word_number condition word
w1 X1 a
w1 X2 b
w1 Y1 c
w1 Y2 d
w2 X1 e
w2 X2 f
w2 Y1 g
w2 Y2 h
w3 X1 i
w3 X2 j
w3 Y1 k
w3 Y2 l
w4 X1 m
w4 X2 n
w4 Y1 o
w4 Y2 p

First, I would like to shuffle the list so that the four words of the same word_number will stay together. I expect the list to be like this:

word_number condition word
w2 X1 e
w2 X2 f
w2 Y1 g
w2 Y2 h
w4 X1 m
w4 X2 n
w4 Y1 o
w4 Y2 p
w3 X1 i
w3 X2 j
w3 Y1 k
w3 Y2 l
w1 X1 a
w1 X2 b
w1 Y1 c
w1 Y2 d

Second, I would like to shuffle the two words of the same condition in the list. I expect the list to be like this.

word_number condition word
w2 X2 f
w2 X1 e
w2 Y2 h
w2 Y1 g
w4 X1 m
w4 X2 n
w4 Y2 p
w4 Y1 o
w3 X2 j
w3 X1 i
w3 Y1 k
w3 Y2 l
w1 X1 a
w1 X2 b
w1 Y2 d
w1 Y1 c

Lastly, I want to select one word from each word_number, including two from X condition and two from Y condition. So basically, select the first word of word_number 2 and 4 in X condition and the first word of word_number 3 and 1 in Y condition.

word_number condition word
w2 X2 f
w4 X1 m
w3 Y1 k
w1 Y2 d

This final list is what I would like to have for my experiment.

ApexCharts.js brush option enabled error: Uncaught (in promise) ReferenceError: ApexCharts is not defined

I am trying to create a candlestick combo chart per example shown in the ApexCharts example Apex Candlestick Charts

I use Vite, and am importing it from the node_modules folder via:
import ApexCharts from "apexcharts";

and then attempting to render it:

let options = {
    series: [
      {
        data: chartData,
      },
    ],
    chart: {
      type: "candlestick",
      height: 300,
      id: "mainCandle",
      toolbar: {
        autoSelected: "pan",
        show: true,
      },
      zoom: {
        enabled: true,
      },
    },
    tooltip: {
      enabled: false,
    },
    plotOptions: {
      candlestick: {
        colors: {
          upward: "#3C90EB",
          downward: "#DF7D46",
        },
      },
    },
    xaxis: {
      type: "datetime",
    },
  };

  chart = new ApexCharts(document.querySelector("#chart-candlestick"), options);
  chart.render();

  let optionsBar = {
    series: [
      {
        name: "volume",
        data: chartData,
      },
    ],
    chart: {
      height: 150,
      type: "candlestick",
      brush: {
        enabled: true,
        target: "mainCandle",
        autoScaleYaxis: true,
      },
      toolbar: {
        autoSelected: "pan",
        show: true,
      },
      zoom: {
        enabled: true,
      },
      selection: {
        enabled: true,
        xaxis: {
          min: new Date("01 Jul 2024").getTime(),
          max: new Date("04 Sep 2024").getTime(),
        },
        fill: {
          color: "#ccc",
          opacity: 0.4,
        },
        stroke: {
          color: "#0D47A1",
        },
      },
    },
    tooltip: {
      enabled: false,
    },
    dataLabels: {
      enabled: false,
    },
    plotOptions: {
      bar: {
        columnWidth: "80%",
        colors: {
          ranges: [
            {
              from: -1000,
              to: 0,
              color: "#F15B46",
            },
            {
              from: 1,
              to: 10000,
              color: "#FEB019",
            },
          ],
        },
      },
    },
    stroke: {
      width: 0,
    },
    xaxis: {
      type: "datetime",
      axisBorder: {
        offsetX: 13,
      },
    },
    yaxis: {
      labels: {
        show: false,
      },
    },
  };

  chartBar = new ApexCharts(document.querySelector("#chart-bar"), optionsBar);
  chartBar.render();`

The 1st chart renders as expected, but the 2nd chart gives the error: Uncaught (in promise) ReferenceError: ApexCharts is not defined

This only seems to error out if the brush option is turned on like so:

chart: {
  brush: { 
    enabled: true,
    target: "target",
    }
}

Open to suggestions. =)

Testing pdf generation with jest

I want to test generation of pdf on my client. For generating i use pdfMake library. And to check if the text inside a pdf is correct i want to parse it but i cant come up with a method to do it.

I know that pdfMake makes blob with pdf data and then i can open it in a tab in browser but how can i check generated data? Seems like i cant access pdf after it opens in window object, so i tried to parse blob or buffer after creating a document. But all pdf-parsing libs seem to work only with existing file on disk and not on blobs or buffers. Are there any solutions? Or the only thing i can do check inside document definition? It would be grate if i also would be able to access coordinates of the document if this possible.

Updating Dynamic changes to fetching Data

I am stuck at the moment. I created the funcitonanilty to control how often data is is fetched using calculation of milliseconds to seconds,munutes and hours, which seems to be working fine.

The issue I am stuck with solving is while the data is being fetched and if the user wants to change the interval from 5 seconds to 10 minutes or 1 hour. the fetching of the data goes to 1 seconds for some reason. can someone assist?

Please see my setupDynamicIntervalChange() Function:

const setupDynamicIntervalChange = (input,select) =>{

    input.addEventListener('input', () =>{
        const intervalValue = input.value;
        const selectedInterval = select.value;

        if(isValidInterval(intervalValue, selectedInterval)){
            document.querySelector('.interval-Btn');
            return
        }

    });

    select.addEventListener('change', () =>{
        const intervalValue = input.value;
        const selectedInterval = select.value;

        if(isValidInterval(intervalValue, selectedInterval)){
            document.querySelector('.interval-Btn');
        }
    });

    fetchData()
}

Please see the full code on JS fiddle

https://jsfiddle.net/blaze92/gvcnp7j8/4/

Just a note this dynamic is the last piece of the puzzle to finish off this functionality

I did try this at one point, but it does not solve the isse and causes another issue with the user input and select option

function refreshFetch(intervalMilliseconds) {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        console.log('Previous refresh interval cleared');
    }

    refreshInterval = setInterval(() => {
        fetchData();
        console.log('Data fetched in refreshFetch');
    }, intervalMilliseconds);
}

document.addEventListener('DOMContentLoaded', () => {
    const input = document.querySelector('.interval-input');
    const select = document.querySelector('.select-interval');
    const button = document.querySelector('.interval-Btn');

    setupDynamicIntervalChange(input, select);

    button.addEventListener('click', () => {
        const intervalValue = parseInt(input.value, 10);
        const selectedInterval = select.value;

        if (isValidInterval(intervalValue, selectedInterval)) {
            const intervalMilliseconds = intervalValue * (intervalLookup[selectedInterval] || 1000);
            fetchInterval = setInterval(fetchData, intervalMilliseconds);
            refreshFetch(intervalMilliseconds);
        }
    });
});
document.addEventListener('DOMContentLoaded', () => {
    const input = document.querySelector('.interval-input');
    const select = document.querySelector('.select-interval');
    const button = document.querySelector('.interval-Btn');

    setupDynamicIntervalChange(input, select);

    button.addEventListener('click', () => {
        const intervalValue = parseInt(input.value, 10);
        const selectedInterval = select.value;

        if (isValidInterval(intervalValue, selectedInterval)) {
            const intervalMilliseconds = intervalValue * (intervalLookup[selectedInterval] || 1000);
            fetchInterval = setInterval(fetchData, intervalMilliseconds);
            refreshFetch(intervalMilliseconds);
        }
    });
});

How to pass a second array through my functions without altering the first array

I’m trying to create a second game mode in a js quiz. I have one game mode running as expected and another set of questions in another array waiting to be used. However, I’m very new to js and struggling how to pass the second array through all my code without altering the first set of data.

I’ve tried an if statement that uses the 2nd array but then the rest of the functions stop working. I’ve tried passing the array through my createQuestion function but it creates errors in the console. Such as

Uncaught TypeError: Cannot read properties of undefined (reading '1')
    at createQuestion (script.js:184:35)
    at HTMLButtonElement.nextQuestion (script.js:236:5)

The 2nd array I would like to pass through looks like this

let quizData2 = [
    {
        question: "assets/images/year/Brazil98-00.avif",
        answers: ["1997", "1999", "2002", "1995"],
        correct: "1999",
    },
    {
        question: "assets/images/year/Denmark-92.webp",
        answers: ["1991", "1990", "1995", "1992"],
        correct: "1992",
    },

When the start guess shirt year function is called I would like the 2nd arrays data set to be used.

document.getElementById('guess-shirt-start-btn').addEventListener('click', startGuessShirtTeam);
document.getElementById('guess-year-start-btn').addEventListener('click', startGuessShirtYear);

// function to start the Guess the Shirt type game
function startGuessShirtTeam () {
    document.getElementById('game-choices-container').classList.add('hidden');
    document.getElementById('question-container').classList.remove('hidden');
    gameMode = 'shirt-quiz'
    modeOfGame(); 
    console.log(gameMode)
    createQuestion(quizData1);
    displayNumberOfQuestions();
};

function startGuessShirtYear () {
    document.getElementById('game-choices-container').classList.add('hidden');
    document.getElementById('question-container').classList.remove('hidden');
    gameMode = 'shirt-year'
    modeOfGame();
    console.log(gameMode)
    createQuestion(quizData2)
    displayNumberOfQuestions();
}

I can get the first question from both arrays displaying but my subsequent check answer and next question functions stop working.

function createQuestion (questionArray) {
    displayQuestionTitle();

    shirtImage.src = questionArray[questionNumber].question;
    
    questionArray[questionNumber].answers.forEach((o) => {
        document.getElementById('answer-button-1').innerText = questionArray[questionNumber].answers[0]
        document.getElementById('answer-button-2').innerText = questionArray[questionNumber].answers[1]
        document.getElementById('answer-button-3').innerText = questionArray[questionNumber].answers[2]
        document.getElementById('answer-button-4').innerText = questionArray[questionNumber].answers[3]
    });
    document.getElementById('answer-button-1').addEventListener('click', checkAnswer);
    document.getElementById('answer-button-2').addEventListener('click', checkAnswer);
    document.getElementById('answer-button-3').addEventListener('click', checkAnswer);
    document.getElementById('answer-button-4').addEventListener('click', checkAnswer);
};

My next question function

function nextQuestion () {
    let allAnswers = document.querySelectorAll('.answer-btns');
    allAnswers.forEach((o) => {
        o.classList.remove('disabled')
    });
    if (questionNumber >= maxQuestions - 1) {
        displayQuizResult();
        return;
    }
    questionNumber++;
    clearCorrectAnswer();
    clearQuestionTitle();
    createQuestion();
    clearAnswers();
    showCurrentQuestionNumber();
}

Check answer function

function checkAnswer (e) {
    let userAnswer = e.target.textContent;
    if (userAnswer === questionArray[questionNumber].correct) {
        userScore++;
        finalScore++;
        e.target.classList.add("correct");
        showUserScore();
    } else {
        e.target.classList.add("incorrect");
        let correct = document.getElementById('correct-answer');
        let correctAnswer = document.createTextNode(`Sorry that's incorrect, the answer is ${questionArray[questionNumber].correct}`);

    correct.appendChild(correctAnswer);
    }

    let allAnswers = document.querySelectorAll('.answer-btns');
    allAnswers.forEach((o) => {
        o.classList.add('disabled')
    });
};

How To Make Cleanup Function more Efficient?

Just looking to see how I would make this function more efficient.

I’m a beginner programmer building my first chrome extension. It scans webpages for ISBN-13s and DOIs and searches another site to see if they are available for download. There can’t be any special characters though, so I have to clean out any “-” that commonly show up. This is the match / cleanup function.

Is there any way that I could do this better? The “-” sliceout seems particularly wieldy. I know how to do that a bit faster in python, but I’m a lot less familiar with Javascript methods.

function isbn13extract(page) {
    var isbn13pattern = /(978|979)[0-9|-]{10,11}/
    var match = page.match(isbn13pattern)
    matchout = match[0]
    if(matchout[3] == "-")
        matchout = matchout.substr(0,3) + matchout.substr(4,13)
        console.log(matchout)

    if (matchout != null) {
        console.log("You did it this is the ISBN:", matchout)
        return matchout
    }
    else {
        console.log("Couldn't Find ISBN")
        return(null)
    }

}

I tried looking up if there were simpler methods to remove specific characters from strings in Javascript but what I mostly got were somewhat wieldy answers. The code currently runs though so what I am doing is working.

React using redux

I hope you are well, I have a problem using React together with Redux, the problem is this:
The problem

I’m getting a “ReferenceError: Cannot access ‘authSlice’ before initialization”. I think the problem is that I have a class called http, and there I import store, and then in my slice class I import an http method, I think that’s it. But it’s because I need to access the store, I attach my store, segment and http class:

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { HOST } from "../http/utils";
import makeApiCall from "../http"; //Possible cause

const accessToken = localStorage.getItem("accessToken");
const refreshToken = localStorage.getItem("refreshToken");
const username = localStorage.getItem("username");

const initialState = {
  username: username || null,
  password: null,
  isLoading: false,
  error: null,
  accessToken: accessToken || null,
  refreshToken: refreshToken || null,
};

export const loginUser = createAsyncThunk(
  "api/login",
  async (payload, { rejectWithValue }) => {
    const url = HOST.concat("api/token/");
    return makeApiCall(url, "POST", payload, rejectWithValue);
  },
);

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    logout: (state) => {
      state.accessToken = null;
      state.refreshToken = null;
      state.username = null;
      state.password = null;
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
    },
    refresh: (state, action) => {
      state.refreshToken = action.payload.refresh;
      state.accessToken = action.payload.access;
    },
    setError: (state, action) => {
      state.error = action.payload;
      state.isLoading = false;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(loginUser.pending, (state, action) => {
        state.isLoading = true;
      })
      .addCase(loginUser.fulfilled, (state, action) => {
        state.accessToken = action.payload.access;
        state.refreshToken = action.payload.refresh;
        localStorage.setItem("accessToken", state.accessToken);
        localStorage.setItem("refreshToken", state.refreshToken);
        state.isLoading = false;
      })
      .addCase(loginUser.rejected, (state, action) => {
        state.error = action.payload;
        state.isLoading = false;
      });
  },
});

export const { logout, setError, refresh } = authSlice.actions;
export default authSlice.reducer;


Here my store configuration:

import { configureStore } from "@reduxjs/toolkit";
import { authSlice } from "./authSlice";
import { userSlice } from "./userSlice";

export const store = configureStore({
  reducer: {
    auth: authSlice.reducer,
    user: userSlice.reducer,
  },
});

and here my class http:

import axios from "axios";
import { store } from "../redux/store"; //Possible cause
import { HOST } from "./utils";

const getHeaders = () => {
  const headers = {
    Accept: "application/json",
    "Content-type": "Application/json",
  };
  const access = store.getState().auth.accessToken;
  if (access) {
    headers.Authorization = `Bearer ${access}`;
  }
  return headers;
};

const refreshAccessToken = async function () {
  return axios
    .request({
      method: "POST",
      url: HOST.concat("/api/v1/auth/refresh/"),
      data: {
        refresh: store.getState().auth.refreshToken,
      },
    })
    .then((response) => {
      if (response.status === 200) {
        store.dispatch({
          type: "auth/refresh",
          payload: response.data,
        });
      }
    })
    .catch(() => {
      store.dispatch({
        type: "auth/logout",
      });
    });
};

const axiosClient = axios.create();

axiosClient.interceptors.request.use(
  async (config) => {
    config.headers = getHeaders();
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

axiosClient.interceptors.response.use(
  (response) => {
    return response;
  },
  async function (error) {
    let response_status;
    try {
      response_status = error.response.status;
    } catch (e) {
      response_status = 200;
    }
    const originalRequest = error.config;
    if (response_status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      await refreshAccessToken();
      return axiosClient(originalRequest);
    }

    return Promise.reject(error);
  },
);

export default async function makeApiCall(url, method, data, rejectWithValue) {
  return new Promise((resolve, reject) => {
    axiosClient
      .request({
        url,
        method,
        data,
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(rejectWithValue(error.response.data));
      });
  });
}

I hope you can help me, if you need me to show you something else just ask, thank you very much in advance for reading my problem, I hope you can help me.

I hope you can help me solve a problem, I use React and Redux, but I am getting a:

ReferenceError: Cannot access ‘authSlice’ before initialization

Showing a table that shows the Current, Latest and Wanted versions of each dependency

I have a task to update all packages specified in package.json in a project. I was able to update all, but I was asked to show proof that all packages are updated, a sort of table showing the Current, Latest, and Wanted version of each dependency. The “npm outdated” doesn’t show anything since all the dependencies are up to date.
Thanks to everyone who will try to help!

react setState mistake

have a mistake in a articles.js
articles.js:

import React, {Component} from 'react';
import './index.css';

export default  class Class extends Component {
    constructor(props) {
        super(props);
        this.state = {
            asd: "asd"
        }
    }

    componentDidMount(){
        this.df();
    }

    async df(){
        let a = await fetch("http://localhost:8080/articles")
        let content = await a.json();
        alert(content)
        this.setState(state=>{
           asd:content.core
            }
        )
    }
    render() {
        return (
            <div>
                <div id={"mainArticle"} dangerouslySetInnerHTML={{__html:this.state.asd}}>
                    </div>
                <div>
                    </div>
                <p></p>
                </div>
            );
        }
}

I take a string in the df function that contains an html fork and pass it to setState asd

after that, this function is passed to componentDidMount, which will launch the function and change the value of asd

next, the value of asd is passed to the

dangerouslySetInnerHTML attribute, where the div should already output the html markup inside itself

terminal gives me mistake:
Expected an assignment or function call and instead saw an expression
what wrong?

i dont no what to do…

Raffle Sheet to Capture 3 Entries for 3 Ticket Option is NOT Working

I have a Google form where I’m attempting to run a charity raffle. One of the questions is a multiple choice: 1 Raffle Ticket – $20 and the other option is: 3 Raffle Tickets – $50. If someone selects “3 Raffle Tickets” and submits the form, I need 3 corresponding entries in my Google Sheet for the number of tickets they purchased.

I tried using AI to create the Apps Script, but have been unsuccessful. Here is what I currently have:

function onFormSubmit(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lastRow = sheet.getLastRow();
  var values = sheet.getRange(lastRow, 1, 1, sheet.getLastColumn()).getValues()[0];
  
  var ticketChoice = values[4]; // Assuming ticket choice is in column E
  
  if (ticketChoice.includes("3 Raffle Tickets")) {
    // Add two more rows for 3 Raffle Tickets
    for (var i = 0; i < 2; i++) {
      sheet.appendRow(values);
    }
  }
  // Do nothing for 1 Raffle Ticket as it's already added by form submission
}

In testing the form, here is what’s happening. When I select the “3 Raffle Tickets” option, it appears to work:
Test with 3 Raffle Tickets option

However, in my next test I select the “1 Raffle Ticket” option, and here’s what happens:
Test with 1 Raffle Ticket option

As you can see, the original entries for 3 tickets is there. However, when I submitted the 1 Rafflet Ticket option, it was added, but 2 other entries were added for the original 3 Ticket entry. Any help in resolving this would be greatly appreciated so we can launch this charity raffle on time. Thank you!

I’m not a scripting expert, so I tried using Perplexity AI to get a working script (see above), but it’s been unsuccessful.

I’m expecting that when someone buys a “3 Raffle Tickets” option, 3 entries are added to the Google Sheet and when someone buys a “1 Raffle Ticket” option, 1 entry is added to the sheet. People can have multiple entries.

how to implement the creation and addition of a card in JS [closed]

I am making a project according to which I should have the functions of creating a card (createCard), deleting (clickDelete) and adding (render) cards to dom-elements. Also, the func createCard must accept a click listener to delete the card. I have such a code, which outputs an error – ReferenceError: the carddata is not defined(in the render function) and the cards are not displayed. please help the beginner figure it out.

const cardTemplate = document.querySelector('#card-template').content;
const cardList = document.querySelector('.places__list');



// func createCard

function createCard(cardData, deleteCard) { 
  const cardElement = cardTemplate.cloneNode(true);
  const cardTitle = cardElement.querySelector('.card__title');
  const cardImage = cardElement.querySelector('.card__image');
  cardTitle.textContent = cardData.name;
  cardImage.alt = cardData.name;
  cardImage.src =  cardData.link;
  cardData.querySelector.querySelector('.card__delete-button').addEventListener('click', () =>{
    deleteCard(cardElement);
  });
  
  return cardElement;
  
};


//delete card
function clickDelete (event){
  const currentCard = event.target.closest('.card');
  currentCard.remove();
}

// render 
function render() {
  initialCards.forEach(createCard);
  const cardElement = createCard(cardData, deleteCard);
  cardList.append(cardElement);
}

render();

I want to create cards that I can delete with a button and display on the page.