Url, not updating with useSearchParams and select tag option is not working while sorting out data

The issues are the select tag option which is not working after I used useSearchParams to update URL by sorting data, the URL is not showing the option when I select the options. The expectation is that when I select any option, the URL should be updating with the option but otherwise.

This is the select tag option code which I created as a reusable component so that I can

const Select = ({ options, value, onChange, ...props }) => {
  return (
    <StyledSelect value={value} {...props}>
      {options.map((option, index) => (
        <option value={option.value} key={index} onChange={onChange}>
          {option.label}
        </option>
      ))}
    </StyledSelect>
  );
};

export default Select;

reuse it another component.

Then the next work is where I called the above component inside the Sort component which contain the logic for the updating the URL and sorting of the array of object(options):

import { useSearchParams } from 'react-router-dom';
import Select from './Select';

const SortBy = ({ options }) => {
  const [searchParams, setSearchParams] = useSearchParams();
  const sortBy = searchParams.get('sortBy') || '';

  function handleChange(e) {
    searchParams.set('sortBy', e.target.value);
    setSearchParams(searchParams);
  }

  return (
    <Select
      value={sortBy}
      options={options}
      type="white"
      onChange={handleChange}
    />
  );
};

export default SortBy;

This last code base is how the SortBy component is call and those options are pass into it

type here

How to add all child arrays to one array?

I have a constant file like that:

const files = [{
    id: 232141332,
    title: "Работа",
    type: "FOALDER",
    opened: true,
    level: 0,
    fatherId: null,
    children: [{
        id: 734573086,
        title: "MA5600",
        type: "FOALDER",
        opened: true,
        level: 1,
        fatherId: 232141332,
        children: [{
            id: 867407333,
            title: "удалить плату",
            type: "FILE",
            opened: false,
            level: 2,
            fatherId: 734573086,
            children: []
          },
          {
            id: 110345245,
            title: "добавить плату",
            type: "FILE",
            opened: false,
            level: 2,
            fatherId: 734573086,
            children: []
          }
        ]
      },
      {
        id: 222225454,
        title: "C300M",
        type: "FOALDER",
        opened: true,
        level: 1,
        fatherId: 232141332,
        children: [{
          id: 333334256,
          title: "добавить опцию TR-82",
          type: "FILE",
          opened: false,
          level: 2,
          fatherId: 222225454,
          children: []
        }]
      }
    ]
  },
  {
    id: 23232,
    title: "Прога",
    type: "FOALDER",
    opened: true,
    level: 0,
    fatherId: null,
    children: [{
        id: 2323242,
        title: "React",
        type: "FOALDER",
        opened: true,
        level: 1,
        fatherId: 1224232,
        children: [{
            id: 45674734,
            title: "добавить компонент",
            type: "FILE",
            opened: false,
            level: 2,
            fatherId: 734573086,
            children: []
          },
          {
            id: 5368876,
            title: "удалить компонент",
            type: "FILE",
            opened: false,
            level: 2,
            fatherId: 734573086,
            children: []
          }
        ]
      },
      {
        id: 258089,
        title: "SQL",
        type: "FOALDER",
        opened: true,
        level: 1,
        fatherId: 232141332,
        children: [{
          id: 1112312,
          title: "посмотреть количество по условию",
          type: "FILE",
          opened: false,
          level: 2,
          fatherId: 222225454,
          children: []
        }]
      }
    ]
  }
]

How can I create an array which will be consist of al children of 1 element of files? Like this:

[{"MA5600"}, {удалить плату}, {добавить плату}, {C300M}, {добавить опцию TR-82}]. 

It is array of all children of object with title Работа, but I need not only names, full files.

How can I display more data(details) in the details popup of the TUI Calendar in Angular?

enter image description here

Title: “Unable to display more details in the TUI Calendar details popup in Angular”

Body:

I am working with the TUI Calendar in my Angular project. I have set up a calendar view, but I am facing an issue where the details page does not display additional data as expected. Although I have tried to configure the popup to show more details, only limited information appears, and the rest is missing.

Expected Results:

The details popup should display all relevant data, including additional information that I want to show when clicking on an event in the calendar.
Actual Results:

The details popup only displays a limited amount of data, and the additional details I want to show are not appearing.
Steps to Reproduce:

Set up TUI Calendar in Angular.
Configure the details popup to show more information.
Click on an event to open the details page.
Observe that only a subset of the data is displayed.

Using Flask, Jquery, when attempting to set src using attr() call only works some of the time

I have the following code in an HTML file, this is meant to both allow for text to appear and stay on screen, but also for the webpage to play audio, however the audio, around 75% of the time will replay previous audio instead of new audio after submit button is pressed for a second time.

$(document).ready(function(){
        $("#messageArea").on("submit", function(event){
          var rawText = $("#text").val();

          $("#text").val("");
          $("#messageForm").append(rawText + "   ||   ");

          $.ajax({
            cahce:false,
            data:{
              message:rawText,
            },
            type:"POST",
            url:"/getChat",
          }).done(function(data) {
            var botHTML = data
            $("#messageForm").append($.parseHTML(botHTML));
            $('<audio></audio').attr({
              'src':'audio/a1.mp3',
              'volume':0.4,
              'autoplay':'autoplay',
              'controls':'controls',
            });
            console.log("here")
          });

          event.preventDefault();
        });
      });

Here is the function that sends the audio

@app.route("/audio/<filename>")
def sendAudio(filename , methods=['GET', 'POST']):
    print("sending audio", filename)
    return send_file(f"audio/{filename}",mimetype="audio/mpeg")

as shown in the image audio is not called certain times, I believe it has to do with the ajax function, but I am out of ideas

I have tried to alter the caching, alter where it is placed, tried creating a separate ajax GET call, and tried using Flasks for_url function, but none of these have worked

Nodemon dont start the server.js

I recently started using Nodemon. But when I run this command “nodemon server.js”, comes this:

nodemon server.js
[nodemon] 3.1.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node server.js tailwind.config.js`
[nodemon] clean exit - waiting for changes before restart

The problem is that Nodemon tries to start two files. How can I fix it? I have no nodemon.json file or similar. I installed Nodemon with npm install nodemon

Migrating from react-router-dom v5 to v6 structure

I have a similar structure as the one below in my project, currently using react-router-dom v5.

Let’s call this <Routes /> component:

<Switch>
  <Redirect from="/" to="/some/path" />
  <Redirect from="/main" to="/some/path" />
  <Route path="/main" component={SomePage} />
</Switch>

And inside <SomePage />, I render something like this:

return (
<>
 <Tabs />
 <Switch>
    <Route path="/some/path" component={MyComponent} />
    <Route path="/some/other" component={OtherComponent} />
    <Route path="/some/last" component={LastComponent} />
 </Switch>
</>
)

Now I am updating react-router-dom to v6, so I changed what was written in their docs…

In <Routes /> component:

<RouterRoutes>
 <Route path="/" element={<Navigate to="/some/path" />} />
 <Route path="/main" element={<Navigate to="/some/path" />} />
 <Route path="/main" element={SomePage />} />
</RouterRoutes>

Did similar thing in <SomePage />, but now nothing is rendered and I don’t get what I need to change. I’ve looked on different threads around here on SO and Google and I still don’t get what is the recommended way to handle this whilst keeping project structure. I am trying to keep similar structure, as in <SomePage /> imports and creates its own routes and the main <Routes /> component is concerned only with the main routes.

Security issue: CacheStorage can violate Content Security Policy (CSP) rules

You know with this CSP configuration:

Content-Security-Policy: script-src 'self'

Then this code can’t be executed:

// Content-Security-Policy: script-src 'self'
const dangerousStringToBeEvaluated= "console.log('HACKED!')"
eval(dangerousStringToBeEvaluated) // EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'

But if I know some JavaScript file is cached in CacheStorage (and is served by service-worker), then I can work around this limitation:

// Content-Security-Policy: script-src 'self'
const dangerousStringToBeEvaluated = "console.log('HACKED!')"
const cache = await caches.open('some-cache')
await cache.put(
  '/some-file.js',
  new Response(dangerousStringToBeEvaluated, {headers: {'Content-Type': 'application/javascript'}}),
)

And afterward, you see HACKED! in your console, when /some-file.js imported!


Is there any other CSP rule to prevent this behavior? For example, by limiting write-access to CacheStorage?

Form is Submitted right after the form is valid, but I haven’t touched the submit button

I use react-hook-form, yup validation.
If I finish the form, before I try to submit, the code automatically submits the form.
But I should prevent this before the user touches the submit button.
Any idea for the auto submission?

const Parent = () => {
  const schema = Yup.object().shape({
  .....
  });

const methods = useForm({
  defaultValues: {...},
  resolver: yupResolver(schema),
  mode: 'all',
});
....
}

And here is the child form

const Form = () => {
  const {handleSubmit, formState } = useFormContext();
  const onFinish = async (data: {[key: string]: any}) => {
  // submit
  }

return (
  <form onSubmit={handleSubmit(onFinish)}>
  ....
  </form>
)
}

How to make lines in file tree

I have created a design in figma and now i am trying to render this in browser. But i can’t imagine, how to create lines before child tree nodes depending on structure?

TreeNode.jsx

import classes from "./TreeNode.module.css"
import opened_file from "../../images/opened_file.svg"
import closed_file from "../../images/closed_file.svg"
import file_image from "../../images/file_image.svg"
import three_points from "../../images/three_points.svg"
import { useEffect, useState } from "react"

function TreeNode ({item}) {
    const [element, setElement] = useState(item)

    return (
        <div className={classes.treeNode}>
            <div id={element.id} className={classes.treeNodeWrapper}>
                <div className={classes.treeNodeLeftSide}>
                    {element.type === "FOALDER" &&
                        <div className={element.opened ? classes.treeNodeOpened : classes.treeNodeClosed}>
                            <img src={element.opened ? opened_file : closed_file} alt={classes.opened ? "svg_opened_file" : "svg_closed_file"}/>
                        </div>
                    }
                    {element.type === "FILE"
                    &&
                    <div className={classes.treeNodeFIleImage}>
                        <img src={file_image} alt="svg_file_image"/>
                    </div>
                    }
                    <div className={classes.treeNodeName}>
                        {element.title}
                    </div>
                </div>
                <div className={classes.treeNodeCloseTextBlock}>
                    
                </div>
                <div className={classes.treeNodeEdit}>
                    <img src={three_points} alt="svg_edit_file"/>
                </div>
            </div>
            <div className={classes.nextTreeNode}>
                {element.children?.map((x) => (
                    <TreeNode key={x.id} item={x}/>
                ))}
            </div>
        </div>
    );
}

export default TreeNode;

TreeNode.module.css

.treeNodeWrapper{
    display: flex;
    align-items: center;
    padding-left: 20px;
    padding-right: 18px;
    justify-content: space-between;
    padding-top: 7.25px;
    padding-bottom: 7.25px;
    position: relative;
}

.treeNodeLeftSide{
    display: flex;
    align-items: center;
}

.treeNodeOpened{
    margin-right: 10px;
}

.treeNodeClosed{
    margin-right: 7px;
}

.treeNodeFIleImage{
    margin-right: 6px;
}

.treeNodeName{
    font-family: "Inter", serif;
    font-optical-sizing: auto;
    font-weight: 400;
    font-style: normal;
    color: #5E6D83;
    font-size: 12.88px;
    letter-spacing: -2%;
    line-height: 0px;
}

.nextTreeNode{
    padding-left: 25px;
}

.treeNodeWrapper::before{
    content: url('../../images/file_line_default.svg');
    position: absolute;
    left: -1.7px;
}

files.js

const files = [
    {
        id: 232141332,
        title: "Documents",
        type: "FOALDER",
        opened: false,
        level: 0,
        fatherId: null,
        children: [
            {
                id: 734573086,
                title: "MA5600",
                type: "FOALDER",
                opened: true,
                level: 1,
                fatherId: 232141332,
                children: [
                    {
                        id: 867407333,
                        title: "delete board",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 734573086,
                        children: []
                    },
                    {
                        id: 110345245,
                        title: "add board",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 734573086,
                        children: []
                    }
                ]
            },
            {
                id: 222225454,
                title: "C300M",
                type: "FOALDER",
                opened: false,
                level: 1,
                fatherId: 232141332,
                children: [
                    {
                        id: 333334256,
                        title: "no option TR-82",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 222225454,
                        children: []
                    }
                ]
            }
        ]
    },
    {
        id: 23232,
        title: "Food",
        type: "FOALDER",
        opened: false,
        level: 0,
        fatherId: null,
        children: [
            {
                id: 2323242,
                title: "MA5600",
                type: "FOALDER",
                opened: false,
                level: 1,
                fatherId: 1224232,
                children: [
                    {
                        id: 45674734,
                        title: "delete board",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 734573086,
                        children: []
                    },
                    {
                        id: 5368876,
                        title: "add board",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 734573086,
                        children: []
                    }
                ]
            },
            {
                id: 258089,
                title: "C300M",
                type: "FOALDER",
                opened: false,
                level: 1,
                fatherId: 232141332,
                children: [
                    {
                        id: 1112312,
                        title: "no option TR-82",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 222225454,
                        children: []
                    }
                ]
            }
        ]
    }
]

export default files;

How can i do it like at this image, what i have to use css or js?

enter image description here

How it looks like in browser now without lines:

enter image description here

How to prevent base color from changing when overlaying patterns?

I’m building a custom racing silks customizer using THREE.js. My app allows users to:
By the way it is something like this website here: https://hylandsportswear.com/kitbuilder/#/customise/80325870?basketIndex=1
my one is just a 2d model and uses a color picker.

Select a base color.
Apply a pattern (e.g., stripes, chequered, heart).
Adjust the pattern’s color.
Adjust the base color once pattern is also applied
color changes are done using a color picker
However, I’m facing an issue where the base color appears to change when a pattern is applied.

The Problem
Expected Behavior: The base color remains exactly as selected (e.g., #ff3370), and the pattern is simply overlaid on top of it.
Actual Behavior: When a pattern is applied, the visible base color shifts (e.g., from pink to red; for some reason it always goes darker than the intended color but eh primary colors dont have the same issue), although the hex code remains unchanged. When switching back to “solid,” the base color is displayed correctly.

my setup includes this:
Base Color: User-selected via an HTML .
Pattern: A transparent PNG (e.g., a black heart with a transparent background). (used gimp to create it).
ShaderMaterial: Used to overlay the pattern on the base color.

I have tried adjusting the fragment shader and vertexshader, i have also made sure my pattern is not the problem. It has a fully transparent background (0 opacity) and then the pattern has (1 opacity and is in the black color).

this is my code for displaying the pattern on top of the base.

const updateMaterials = () => {
if (!silkModel) return;

const sections = [
  { name: "jacketmaterial", colorId: "jacketColor", patternId: "jacketPattern", patternColorId: "jacketPatternColor" },
  { name: "lsleevematerial", colorId: "sleevesColor", patternId: "sleevesPattern", patternColorId: "sleevesPatternColor" },
  { name: "rsleevematerial", colorId: "sleevesColor", patternId: "sleevesPattern", patternColorId: "sleevesPatternColor" },
  { name: "capmaterial", colorId: "capColor", patternId: "capPattern", patternColorId: "capPatternColor" },
];

sections.forEach(({ name, colorId, patternId, patternColorId }) => {
  const baseColorValue = document.getElementById(colorId)?.value || "#ffffff";
  const patternColorValue = document.getElementById(patternColorId)?.value || "#ffffff";
  const selectedPattern = document.getElementById(patternId)?.value || "solid";

  const baseColor = new THREE.Color(baseColorValue);
  const patternColor = new THREE.Color(patternColorValue);

  silkModel.traverse((child) => {
    if (child.isMesh && child.material && child.material.name === name) {
      console.log("Updating material for:", name);
      console.log("Base Color:", baseColorValue);
      console.log("Pattern Color:", patternColorValue);
      console.log("Selected Pattern:", selectedPattern);

      let texture =
        selectedPattern === "custom" ? customPatterns.current[name] : patterns[selectedPattern];

      console.log("Texture Info:", texture);

      if (!texture || selectedPattern === "solid") {
        child.material = new THREE.MeshStandardMaterial({
          color: baseColor,
          emissive: baseColor,
          emissiveIntensity: 0.5,
          side: THREE.DoubleSide,
          name: child.material.name,
        });
      } else {
        child.material = new THREE.ShaderMaterial({
          uniforms: {
              baseColor: { value: baseColor },
              patternColor: { value: patternColor },
              patternTexture: { value: texture },
          },
          vertexShader: `
              varying vec2 vUv;
              void main() {
                  vUv = uv;
                  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
              }
          `,
          fragmentShader: `
          uniform vec3 baseColor;
          uniform vec3 patternColor;
          uniform sampler2D patternTexture;
          varying vec2 vUv;
        
          void main() {
            vec4 texelColor = texture2D(patternTexture, vUv);
            float alpha = texelColor.a; // Transparency of the pattern
        
            // If alpha is 0, use the base color only. If alpha > 0, blend the pattern color.
            vec3 outputColor = mix(baseColor, patternColor, alpha);
        
            gl_FragColor = vec4(outputColor, 1.0);
          }
        `,
        
          side: THREE.DoubleSide,
          transparent: true, // Ensures blending with the base color
          name: child.material.name,
      });
      
      }
      child.material.needsUpdate = true;
    }
  });
});

};

heart: textureLoader.load("/textures/black_heart_pattern.png", (texture) => {
  texture.colorSpace = THREE.SRGBColorSpace;
  texture.flipY = false;
}),

Virtual Scrolling for larga children in mat-tree component

I am having some issues with my mat-tree component. I am trying to draw folder/files hierarchy with a root folder (or several root folders). The problem is when I try to open a very large children, the mat-tree starts rendering all the children nodes and it takes more than 1 minute. I have been reading about virtual scrolling, but I all the examples I found works for lists, not for lists inside objects.

This is my component:

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <mat-tree-node *matTreeNodeDef="let node">
    <div fxLayout="row" fxFlex>
      <span *ngFor="let i of array(treeControl.getLevel(node))" class="indent"></span>
      <mat-checkbox
        [checked]="node.checked"
        (change)="onCheckboxChange(node)"
        [disabled]="!node.checkeable"
        (click)="$event.stopPropagation()"
      >
        <button mat-icon-button><mat-icon> text_snippet </mat-icon></button>
      </mat-checkbox>
      <span
        class="file-name"
        fxLayoutAlign="center center"
        (click)="downloadFile(node.file_ancillary_oid, node.size)"
      >
        {{ getFileName(node) }}
      </span>
    </div>
    <div fxFlex="20" fxLayoutAlign="center center">{{ formatSize(node.size) }}</div>
  </mat-tree-node>

  <mat-tree-node *matTreeNodeDef="let node; when: isFolder" class="border-top">
    <div fxLayout="row" fxFlex>
      <span *ngFor="let i of array(treeControl.getLevel(node))" class="indent"></span>
      <mat-checkbox [checked]="node.checked" (change)="onCheckboxChange(node)" [disabled]="!node.checkeable">
        <button mat-icon-button matTreeNodeToggle [attr.aria-label]="'toggle ' + node.name">
          <mat-icon *ngIf="hasChild"> {{ treeControl.isExpanded(node) ? 'folder_open' : 'folder' }} </mat-icon>
        </button>
      </mat-checkbox>
      <span fxLayoutAlign="center center" matTreeNodeToggle class="file-name"> {{ node.name }} </span>
    </div>
    <div fxFlex="20" fxLayoutAlign="center center">{{ node.size }}</div>
  </mat-tree-node>
</mat-tree>

How to Prevent ASP.NET Validation From Jumping to the Top of Page

I have a basic VB.NET contact page with validation controls and a “ValidationSummary” control. Whenever I click on the button to submit, if there is a validation error it jumps to the top of the page.

I tried multiple references from this site and none of them worked see links below.

The extra weird thing is that some of them work on my localhost, but when I load it to the third-party hosting provider, it doesn’t work?! For example, some of the various JavaScript suggestions that use different “window.scrollTo” method work on localhost, but not on the provider’s host server.

Very basic example:

<!doctype html>
<html lang="en">
<head runat="server">
    <title>Basic Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div style='min-height: 900px; margin-bottom: 40px; border: 1px solid #000;'>
            <p>Added dummy space to demonstrate the issue.</p>
        </div>
        <div>
            <label for="TextBox01" class="form-label">
                Full Name:
                <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator01" ControlToValidate="TextBox01" SetFocusOnError="True" Display="Dynamic" Text="*" ErrorMessage="The 'Full name' field is required." />
            </label>

            <asp:TextBox ID="TextBox01" runat="server" CssClass="form-control" Type="text" />
        </div>
        <div>
            <asp:Button ID="ButtonSend" runat="server" Text="Send" /><br />
            <asp:ValidationSummary ID="ValidationSummaryEdit" runat="server" Visible="True" DisplayMode="List" />
        </div>
    </form>
</body>
</html>

Links to suggestions I tried:

How can I prevent a page to jump to top position after failed validation?

ASP.Net validation summary causes page to jump to top

How can I prevent a page to jump to top position after failed validation?

How to periodically refresh web page content and switch between two DIV’s?

I am not familiar with JavaScript so I’m still learning.
At our office we have two different servers monitoring our network (filecount, file availablity, etc.). Both servers produce a dashboard page every minute.
I want to view both dashboards, one after another, with an interval of 2 minutes and have the content of the dashboard refreshed without refreshing the entire web page as this is being displayed on a TV.
I have this working to a point where the two dashboards are displayed with the desired interval, but only the content of the two dashboards are not being updated/refreshed and I can’t figure out why.

I’ve created a web page with the below HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Live Update</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="autoUpdateVTS.js"></script>
    <script type="text/javascript" src="autoUpdateIDS.js"></script>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="VTS">
</div>
<div id="IDS" class="hide">
</div>
</body>
</html>

The CSS only contains data for the visibily of my DIV’s:

html,
body {
}
#VTS {

}

#IDS {

}

.hide { display: none !important; }

The first script is getting the content of the first dashboard and refresh the data every 20 seconds:

document.addEventListener("DOMContentLoaded", function()
{
    var xhr = null;

    getXmlHttpRequestObject = function()
    {
        if(!xhr)
        {               
            xhr = new XMLHttpRequest();
        }
        return xhr;
    };

    updateVTS = function()
    {
        var url = 'http://vtc130/hm01/dashboard.htm'; 
        xhr = getXmlHttpRequestObject();
        xhr.onreadystatechange = evenHandlervts;
        // asynchronous requests
        xhr.open("GET", url, true);
        xhr.send(null);
    };

    updateVTS();

    function evenHandlervts()
    {
        // Check response is ready or not
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            dataDiv = document.getElementById('VTS');
            // Set current data text
            dataDiv.innerHTML = xhr.responseText;
            // Update the live data every 20 sec
            setTimeout(updateVTS, 20000);
        }
    }

});

The second script is identical to the above but getting data from the second dashboard and put this in the other DIV.

script.js is used to toggle the visibility of the two DIV’s with the interval of 2 minutes:

window.addEventListener('load', function()
{
    switchVTSIDS = function()
    {
        setInterval(function() {
            VTS.classList.toggle("hide");
            IDS.classList.toggle("hide");
                                }, 120000);
    };

    switchVTSIDS();
});

With the above setup the two DIV’s are toggeled as preferred, but the data the two DIV’s are not being refreshed/updated automatically.
The data from the DIV’s are loaded when i open the web page, but they don’t get updated automatically.

Hopefully someone can assist and point me in the right direction here.

DiscordAPIError[10062]: Unknown interaction at handleErrors

I’m making a slash command to send a user info about command when they use /showallrole I just get this error please help me to check my code.
this code for show all user in my discord.

C:botbot_discord_js_time_rolenode_modules@discordjsrestdistindex.js:640
      throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
            ^

DiscordAPIError[10062]: Unknown interaction
    at handleErrors (C:botbot_discord_js_time_rolenode_modules←[4m@discordjs←[24mrestdistindex.js:640:13)
←[90m    at processTicksAndRejections (node:internal/process/task_queues:96:5)←[39m
    at async BurstHandler.runRequest (C:botbot_discord_js_time_rolenode_modules←[4m@discordjs←[24mrestdistindex.j
s:736:23)
    at async REST.request (C:botbot_discord_js_time_rolenode_modules←[4m@discordjs←[24mrestdistindex.js:1387:22)
    at async ChatInputCommandInteraction.reply (C:botbot_discord_js_time_rolenode_modules←[4mdiscord.js←[24msrcstr
ucturesinterfacesInteractionResponses.js:111:5) {
  requestBody: {
    files: [],
    json: {
      type: ←[33m4←[39m,
      data: {
        content: ←[32m'deleted_user_361e19ab73da: Role: Subscribe Valid Sampai 5/02/2024 14:38 (setahun)n'←[39m +
          ←[32m'cierocielo: Role: Subscribe Valid Sampai 21/01/2025 6:59 (22 menit)n'←[39m +
          ←[32m'vincee94: Role: Subscribe Valid Sampai 23/01/2025 16:36 (2 hari)n'←[39m +
          ←[32m'aruturuuu: Role: Subscribe Valid Sampai 24/01/2025 19:36 (4 hari)n'←[39m +
          ←[32m'nobo88: Role: Subscribe Valid Sampai 25/01/2025 22:32 (5 hari)n'←[39m +
          ←[32m'arjuna_inguh: Role: Subscribe Valid Sampai 25/01/2025 22:35 (5 hari)n'←[39m +
          ←[32m'mayrekber: Role: Subscribe Valid Sampai 27/01/2025 10:13 (6 hari)n'←[39m +
          ←[32m'uzziel: Role: Subscribe Valid Sampai 30/01/2025 16:17 (9 hari)n'←[39m +
          ←[32m'kunard: Role: Subscribe Valid Sampai 1/02/2025 22:06 (12 hari)n'←[39m +
          ←[32m'adre0064: Role: Subscribe Valid Sampai 3/02/2025 21:17 (14 hari)n'←[39m +
          ←[32m'.beelee: Role: Subscribe Valid Sampai 4/02/2025 2:31 (14 hari)n'←[39m +
          ←[32m'monte_24678: Role: Subscribe Valid Sampai 17/02/2025 19:58 (sebulan)n'←[39m +
          ←[32m'harmankardon5: Role: Subscribe Valid Sampai 18/02/2025 14:43 (sebulan)n'←[39m +
          ←[32m'booboo1433: Role: Subscribe Valid Sampai 18/02/2025 19:53 (sebulan)n'←[39m +
          ←[32m'irric: Role: Subscribe Valid Sampai 21/02/2025 19:42 (sebulan)n'←[39m +
          ←[32m'navii2121: Role: Subscribe Valid Sampai 8/04/2025 19:38 (3 bulan)n'←[39m,
        tts: ←[33mfalse←[39m,
        nonce: ←[90mundefined←[39m,
        embeds: ←[90mundefined←[39m,
        components: ←[90mundefined←[39m,
        username: ←[90mundefined←[39m,
        avatar_url: ←[90mundefined←[39m,
        allowed_mentions: ←[90mundefined←[39m,
        flags: ←[33m64←[39m,
        message_reference: ←[90mundefined←[39m,
        attachments: ←[90mundefined←[39m,
        sticker_ids: ←[90mundefined←[39m,
        thread_name: ←[90mundefined←[39m
      }
    }
  },
  rawError: { message: ←[32m'Unknown interaction'←[39m, code: ←[33m10062←[39m },
  code: ←[33m10062←[39m,
  status: ←[33m404←[39m,
  method: ←[32m'POST'←[39m,
  url: ←[32m'https://discord.com/api/v10/interactions/1331044983817375835/aW50ZXJhY3Rpb246MTMzMTA0NDk4MzgxNzM3NTgzNTpic0
NmSjRqMG9XS1pnQWNYUDdNN1lVaVBRNklwdmVYWktWZ2lRMXdQSnJxaXVZSWRMQjdZQjhrSW5EYkJiNjNVaGk2OTBvQTJkbkkzRlZvQ3FORW1HSEg3U3ZyNW
U0V2oxRTFpRlNkcDk0VElvdnZlM2ZrSml0TlhrS25GM0wyMQ/callback'←[39m
}

And here is the full code :

const moment = require("moment");
const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('showallroles')
    .setDescription('Show the expiration time of all roles')
    .addRoleOption(option => option.setName('role').setDescription('The role to show users for').setRequired(true))
    .addStringOption(option => option.setName('sort').setDescription('Sort order').addChoices({name: 'Ascending', value: 'asc'}, {name: 'Descending', value: 'desc'}).setRequired(true)),
  async execute(client, interaction, guildId, db) {
    const roleId = interaction.options.getRole('role').id;
    const sortOrder = interaction.options.getString('sort') || 'asc'; // Default to ascending if sort option not provided
    let reply = "";
    
    const users = db.prepare("SELECT * FROM members WHERE role = ? ORDER BY unixTimestamp " + (sortOrder === 'asc' ? 'ASC' : 'DESC')).all(roleId); // Get all users from the database, sorted by expiry
    if (users.length > 0) {
      for (const user of users) {
        const date = moment.unix(user.unixTimestamp); // Convert
        const currentData = moment();
        moment.locale('id');
        const duration = moment.duration(date.diff(currentData));
        const formattedDuration = duration.humanize();
        const member = await client.users.fetch(user.memberId); // Fetch the user object from Discord API

        if (member) {
          reply += `${member.username}: Role: ${(await interaction.guild.roles.fetch(user.role))?.name} Valid Sampai ${date.format("D/MM/YYYY H:mm")} (${formattedDuration})n`;
        }
      }
    } else {
      reply = "Tidak ada Time Role";
    }
      
    if (reply.length < 2000) {
      await interaction.reply({ content: reply, ephemeral: true });
    } else {
      const attachment = new AttachmentBuilder(Buffer.from(reply), { name: 'output.txt' });
      await interaction.reply({ files: [attachment], ephemeral: true });
    }
  }
};

I couldn’t find any answers to this problem on the internet so I’m hoping you can answer it. Thank you in advance!

NestJS Application Dependencies Not Found When Reusing Singleton in Jest E2E Tests

I’m working on reusing a NestJS application instance across multiple test suites in my Jest E2E tests.

Here is my current setup:

jest.config.json

{
  other configs...

  "setupFilesAfterEnv": ["./test/jest.setup.ts"],
  "globalSetup": "./test/mysql-global-setup.ts",
  "globalTeardown": "./test/mysql-global-teardown.ts",
  "maxWorkers": 1
}
// test/mysql-global-setup.ts

import { MySqlContainer, StartedMySqlContainer } from '@testcontainers/mysql';
import { initializeApp } from './test_nest_application';
const globalAny: any = global;

export default async () => {
  // some mysql testcontainers settings...

  console.log('Starting NestJS application...');
  const testContext = await initializeApp();
  console.log('NestJS application started.');
};
// test/test-nest-application.ts

import { Test } from '@nestjs/testing';
import { AppModule } from '../src/app.module';
import { WinstonLoggerService } from '../src/common/logger/logger.service';
import * as cookieParser from 'cookie-parser';
import { InternalExceptionsFilter } from '../src/common/filters/internal-exceptions.filter';
import { HttpExceptionsFilter } from '../src/common/filters/http-exception.filter';
import { INestApplication, ValidationPipe } from '@nestjs/common';

let app: INestApplication;

// declare global nest application
declare global {
  var testContext;
}

export const initializeApp = async (): Promise<INestApplication> => {
  // use global.testContext as singleton instance
  if (!global.testContext) {
    const moduleFixture = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    app = moduleFixture.createNestApplication();

    // setting some application's config values...
    await app.init();

    global.testContext = app;
  }

  return global.testContext;
};

I want to reuse the TestNestApplication in separate test suites.
However, according to jest document says that “Any global variables that are defined through globalSetup can only be read in globalTeardown.”

To work around this, I defined a singleton module that returns the Nest application named initializeApp() to reuse the Nest application.

The initialized application isn’t defined in globalSetup instead, it is defined in a separate module and added to a global variable.

In my test suites, I use the application like this:

// test/rss/rss-e2e-spec.ts

describe('Rss Accept E2E Test', () => {
  let app: INestApplication;
  let rssRepository: Repository<Rss>;
  let rssAcceptRepository: Repository<RssAccept>;
  let redisService: RedisService;

  beforeAll(async () => {
    app = await initializeApp();
    rssRepository = app.get(RssRepository);
    rssAcceptRepository = app.get(RssAcceptRepository);
    redisService = app.get(RedisService);
  });

describe('POST /api/rss/accept/{rssId}', () => {
    // test codes...

When I run this test, I encounter the following error:

    Nest could not find RssRepository element (this provider does not exist in the current context)

      19 |   beforeAll(async () => {
      20 |     app = await initializeApp();
    > 21 |     rssRepository = app.get(RssRepository);
         |                         ^
      22 |     rssAcceptRepository = app.get(RssAcceptRepository);
      23 |     redisService = app.get(RedisService);
      24 |   });

Nest can’t find the RssRepository instance as well as other dependencies. However, initializing the Nest application every time with beforeAll() works fine without any errors.

Additionally, if no value is passed to the .get() method, I receive an error stating that the .get() method itself cannot be found. However, it keep says can’t find providers.

But, initializing nest application every time with beforeAll() works fine with no errors. (Which means, same initializing codes worked fine when I ran it in beforeAll()

Any insights or suggestions on how to properly share the Nest application instance across test suites would be greatly appreciated.