Rxjs: infinite loop with value in each call is the result from the previous

Says, I have an api call that take an input since which is Unix timestamp.

  fetchData = (since?) => {
    const now = Math.floor(Date.now() / 1000); // Current Unix timestamp in seconds
    if (since) {
        //handle logic
        console.log(since)
    }
    return of({ since: now });
  };

Now I want to make an infinite loop that in each call, the input value to fetchData is the return value from the previous call. I tried with this code:

fetchData().pipe(
    expand((response: any) => {
      const { since } = response;
      return fetchData(since);
    }),
    delay(3000),
    repeat(),
  );

I don’t know why console.log kept giving me the same value. What have I done wrong here?

Partial text assertion for elements using Detox

I’m using Detox to test my react native app. I identify my text element by the id and want to assert that the text contains SOME text.

I only want partial text check which .toHaveText("blah") doesn’t allow.

The element has text 0 minutes / X minutes , I purely want to check that the element contains 0 minutes and im not interested in the X minutes (more specifically this second bit can change and my test will fail if i try to predict what X will be)

Am i missing something ?

.toHaveText checks the whole string, I just want to check part of the string

Angular 18 error: TS-992003: No suitable injection token for parameter ‘movieService’ of class ‘MovielistComponent’

Today I decided to start working in the latest Angular version (Angular 18.1) so far I was working with versions 7 to 14…

I just tried making a lil dummy app to showcase a list of movies…

I made a really basic service that gets some data from an API and in the component.ts file called that service to console log it…

I am getting these three errors in my compiler…

✘ [ERROR] TS-992003: No suitable injection token for parameter 'movieService' of class 'MovielistComponent'.
  Consider adding a type to the parameter or use the @Inject decorator to specify an injection token. [plugin angular-compiler]

    src/app/movielist/movielist.component.ts:15:12:
      15 │     private movieService = GetMoviesService,
         ╵             ~~~~~~~~~~~~


✘ [ERROR] TS2339: Property 'getMovies' does not exist on type 'typeof GetMoviesService'. [plugin angular-compiler]

    src/app/movielist/movielist.component.ts:22:28:
      22 │     await this.movieService.getMovies().subscribe(
         ╵                             ~~~~~~~~~


✘ [ERROR] TS7006: Parameter 'data' implicitly has an 'any' type. [plugin angular-compiler]

    src/app/movielist/movielist.component.ts:23:6:
      23 │       data => {
         ╵       ~~~~

Is this some new thing in Angular 18 or am I just blind and missing something basic here…

My code:

service.ts

@Injectable({
  providedIn: 'root'
})
export class GetMoviesService {
  constructor(
    private http: HttpClient
  ) { }

  getMovies(): Observable<movie[]> {
    return this.http.get<movie[]>(`/api/movies`);
  }

}

movielist.component.ts:

@Component({
  selector: 'app-movielist',
  standalone: true,
  imports: [],
  templateUrl: './movielist.component.html',
  styleUrl: './movielist.component.scss'
})
export class MovielistComponent implements OnInit{
  private movie: movie[] = [];
  constructor(
    private movieService = GetMoviesService,
  ) { }
  ngOnInit() {
    this.getMoviesList();
  }

  async getMoviesList() {
    await this.movieService.getMovies().subscribe(
      data => {
        this.movie = data;
        console.log('Movies: ', this.movie);
      }
    )
  }

}

model movie.ts

export interface movie {
  id: number,
  attributes: {
    name: string,
    imageUrl: string,
    synopsis: string,
    year: string,
    genre: string,
  }
}

Div “doesnt exist” when trying to check if user can see it

On my chatting service, I’m checking if the person is at the bottom of the chat by putting a div with id “bottom” there and checking if the user can see it. The first time I do it, everything works fine. Second time and more, it gives me an error saying the “bottom” div is null. I cant figure out whats wrong with it.

Heres the JS code

function updateMessages() {
    var messages = document.getElementById("messages");
    if(messages && document.getElementById("bottom")) { // Check if messages and bottom div exist
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                scroll = messages.scrollTop;
                var messagesRect = messages.getBoundingClientRect();
                var bottomRect = document.getElementById("bottom").getBoundingClientRect();
                console.log(messagesRect);
                console.log(bottomRect);
                var isVisible = (bottomRect.top >= messagesRect.top && bottomRect.bottom <= messagesRect.bottom);

                if (isVisible) {
                    console.log("returned at bottom");
                    messages.innerHTML = this.responseText;
                    messages.scrollTop = messages.scrollHeight;
                } else {
                    console.log("returned not at bottom");
                    messages.innerHTML = this.responseText;
                    messages.scrollTop = scroll;
                }
            }
        };
        xmlhttp.open("GET", "Dont want to share this link", true);
        xmlhttp.send();
    } else {
        console.log("doesnt exist");
        if (!messages) {
            console.log("messages");
        } 
        if (!document.getElementById("bottom")) {
            console.log("bottom");
        }
    }
}
setInterval(updateMessages, 6000);

And the console logs:

First updateMessages();

DOMRect {x: 0, y: 146, width: 1149, height: 660, top: 146, …}
DOMRect {x: 5, y: 791, width: 1124, height: 2, top: 791, …}
returned at bottom

second updateMessages()

doesnt exist
bottom

HTML:
<div class="row content" id="messages" style="display: block;"><div id="bottom"><hr></div>message 1</div>

Primeng customize dropdown items differently from “main” item

I recently installed Primeng.

I’m trying to use p-menubar component aka Menubar, I read on docs that there’s the possibility to customize menu items using ng-template but the moment I add “sub-items” (the nested menu items), it applies the same style of the “main” items.

This is what I have right now:

<p-menubar [model]="menuItems">
    <ng-template pTemplate="item" let-item>
        <p style="color: white; padding: 0 10px">{{ item.label }}</p>
    </ng-template>
</p-menubar>

what happens here is that I have a blue background so I set menu items’ color to white, unfortunately it applies even to sub-menu, where the background color is white as well, and it makes the text unreadable.

Is there a way to define a second template to customize the submenu items or to keep the style only on the “main” items?

I tried to edit the css but I couldn’t achieve the expected result since they’re the same element.

how to collapse bootstrap navbar if the options start to overflow

I have a bootstrap 5 navbar where user’s can add options to it.

The issue I am facing is that if they add ten or so option its starts to overflow.

I want it automatically to collaspe when it starts to overflow, simially the way it does when the screen gets too small.

It would also be great if it would be possible for some elements to always show.

Here is my navbar code

<nav class="navbar navbar-expand-sm navbar-dark" id="navbar">
    <div class="container-fluid" id="navbar-content">
      <a class="navbar-brand">Project X</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mynavbar">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="mynavbar">
        <ul class="navbar-nav" id="nav-spaces">
            <li class="nav-item"><a class="nav-link active" href="#" data-space-id="1">Default</a></li>
        </ul>
        <div class="ms-auto">
          <button class="btn btn btn-outline-light btn-lg ms-1" id="button-space" data-bs-toggle="modal" data-bs-target="#modal-spaces"><i class="fa-solid fa-pencil"></i> spaces</button>
          <button class="btn btn-outline-success btn-lg ms-1" id="button-login" data-bs-toggle="modal" data-bs-target="#modal-admin"><i class="fa-solid fa-user-lock"></i> Admin</button>
          <button class="btn btn-outline-success btn-lg ms-1" id="button-logout"><i class="fa-solid fa-right-from-bracket"></i> Logout</button>
          <button class="btn btn-outline-light btn-lg ms-1" id="button-hide-navbar"><i class="fa-solid fa-chevron-up"></i></button>
        </div>
      </div>
    </div>
  </nav>

Problem with navbar

Telegram share link can’t process “n” symbol

Whenever I try to share text from another app in Telegram using t.me/share/url?url=text or tg://msg_url?url=text, the ‘n’ character is encoded and looks like ‘%0A’. However, the same link works just fine on other Android and iOS devices. And if we open that link in the browser and then click “Share” it also works perfectly on the device.

Code
The result I get

I tried using an empty url query and putting the main text in a text query. I tried the encoded one 2 times. Both options did not help.

Cant SWAP MATIC token Using 0x example dApp

I checked there isn’t already an issue for the bug I encountered.

Hello, this is my first post as a programmer, please don’t judge harshly, thank you.

Issue:

I’m using the 0x Next.js swap dApp example from the 0x documentation on the Polygon network in my application. Everything works correctly except for “MATIC”.

I can’t swap this token; it doesn’t recognize the balance and says there’s insufficient balance. What could be the problem?

Describe the bug

Hello, this is my first post as a programmer, please don’t judge harshly, thank you.

Issue:

I’m using the 0x Next.js swap dApp example from the 0x documentation on the Polygon network in my application. Everything works correctly except for “MATIC”.

I can’t swap this token; it doesn’t recognize the balance and says there’s insufficient balance. What could be the problem?

I cant sell MATIC token, but can buy MATIC correct

In the console, I see errors like:

ContractFunctionExecutionError
    at getContractError (getContractError.js:31:12)
    at simulateContract (simulateContract.js:49:98)
    at async prepareWriteContract (chunk-OKULXQAF.js:2132:31)
Caused by: ContractFunctionZeroDataError
    at getContractError (getContractError.js:20:17)
    at simulateContract (simulateContract.js:49:98)
    at async prepareWriteContract (chunk-OKULXQAF.js:2132:31)

I hope I’ve reached the right place, thank you.

My code: GitHub Repository

Link to Minimal Reproducible Example

No response

Steps To Reproduce

  1. fork https://github.com/petrolozynskyi/0x-nextjs-demo-app
  2. run in terminal “npm i”
    3.run in terminal “npm run dev”
    4.Connect Wallet
    5.Click to Wallet in left corner, and choose network(Polygon)

and try to swap MATIC to something other

What Wagmi package(s) are you using?

@wagmi/core

Wagmi Package(s) Version(s)

^1.1.0

Viem Version

^0.3.50

TypeScript Version

5.0.4

How to get the refreshed token in a Linnworks embed app?

I thought I’d try posting my problem here given the non-existent support that Linnworks provide.

I’ve created a private embedded app within Linnworks that displays orders in a spreadsheet format. The app is built with Vue.js and uses axios to pull the data from Linnworks APIs. Everything is working as it should be here, except that I’m only returning 100 orders at a time to keep things quick.

I’ve added a “load more orders” button which appends an additional 100 orders to the end of the sheet, but after a period of inactivity, this causes a “401 unauthorised error” because the token has expired.

Because it’s an embedded app, Linnworks store the token within the src of the iframe when the app is initialised, so when it has expired, it doesn’t get physically refreshed by the system.

<iframe src="https://example.com/sheet.html?token=9b11e8ff-4791-aca5-b58d-f6da84e996a6"></iframe>

Is there a way of getting the refreshed token without reloading the entire app?

I’ve created a private embedded app within Linnworks that displays orders in a spreadsheet format. The app is built with Vue.js and uses axios to pull the data from Linnworks APIs. Everything is working as it should be here, except that I’m only returning 100 orders at a time to keep things quick.

Promise is never returned in firestore().collection(‘Users’).add({ name: ‘Ada Lovelace’, age: 30 })

I’m using React Native with Expo and library @react-native-firebase/firestore.
I’m trying to add a document to a collection in Firestore but the promise never returns so nothing is inserted in firestore.
The promise that never resolves is this one:

// Attempt to add user
const result = await userRef.add({
  name: 'Ada Lovelace',
  age: 30,
});

I would expect the user object to get saved in Firestore and to see the following logs:

console.log('Result:', result);

This is my code:

import React, { useEffect } from 'react';
import { View, Text, Button } from 'react-native';
import firebase from '@react-native-firebase/app';
import firestore from '@react-native-firebase/firestore';

// Configuración de Firebase
const firebaseConfig = {
  apiKey: "xxx",
  authDomain: "xxx",
  projectId: "xxx",
  storageBucket: "xxx",
  messagingSenderId: "xxx",
  appId: "xxx",
  measurementId: "xxx"
};

// Inicializar Firebase
if (!firebase.apps.length) {
  console.log('Initializing Firebase');
  firebase.initializeApp(firebaseConfig);
} else {
  console.log('Firebase already initialized');
}

export default function App() {
  useEffect(() => {
    console.log('Firestore instance:', firestore());
  }, []);

  const addUser = async () => {
    try {
      console.log('Adding user...');
      const userRef = firestore().collection('Users');
      console.log('User collection reference:', userRef);

      // Attempt to add user
      const result = await userRef.add({
        name: 'Ada Lovelace',
        age: 30,
      });

      console.log('Result:', result);
      console.log('User added!');
    } catch (error: any) {
      console.error('Error adding user: ', error);

      // Captura de errores HTTP
      if (error.response) {
        console.log('Error data:', error.response.data);
        console.log('Error status:', error.response.status);
        console.log('Error headers:', error.response.headers);
      } else if (error.request) {
        console.log('Error request:', error.request);
      } else {
        console.log('Error message:', error.message);
      }
      console.log('Error config:', error.config);

      alert(`Error adding user: ${error.message}`);
    }
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Add User to Firestore</Text>
      <Button title="Add User" onPress={addUser} />
    </View>
  );
}

and this is my rule:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

I’m using these versions:

    "@react-native-firebase/app": "^20.3.0",
    "@react-native-firebase/auth": "^20.3.0",
    "@react-native-firebase/firestore": "^20.3.0",
    "@react-native-firebase/messaging": "^20.3.0",

HTML file Failed to load resource: net::ERR_FAILED

I have an HTML file, where I joined a CSS style, JS code for Image Classification and HTML code, from MediaPipe (https://codepen.io/mediapipe-preview/pen/BaVZejK). I created a custom model, .tflite, whose path was added in modelAssetPath:, instead of the default model.

I get the following errors in Debug Console in Chrome:

Access to fetch at 'https://storage.googleapis.com/xxxxxxxxxx/resnet50_quantized.tflite' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

and

Failed to load resource: net::ERR_FAILED -- from a public object in Google Cloud Storage

and

Uncaught (in promise) TypeError: Failed to fetch
    at Mh.l (tasks-vision:7:47151)
    at Mh.l (tasks-vision:7:76591)
    at Mh.o (tasks-vision:7:121629)
    at Zo (tasks-vision:7:45744)
    at async createImageClassifier (

In VSCode, I get the following:

Could not read source map for https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision: Unexpected 404 response from https://cdn.jsdelivr.net/npm/@mediapipe/vision_bundle_mjs.js.map: Failed to resolve the requested file.
Uncaught TypeError TypeError: Failed to fetch
    at l (cdn.jsdelivr.net/npm/@mediapipe/tasks-vision:7:47151)
    at l (cdn.jsdelivr.net/npm/@mediapipe/tasks-vision:7:76591)
    at o (cdn.jsdelivr.net/npm/@mediapipe/tasks-vision:7:121629)
    at Zo (cdn.jsdelivr.net/npm/@mediapipe/tasks-vision:7:45744)
    --- await ---

As my knowledge of JS is quite limited, I’d like to have some ideas about what can be wrong, like position of script, module, href, if possible.

Here is my effort so far:

<!DOCTYPE html>
<html lang="en">
<head>
<style>

@use "@material";
body {
  font-family: roboto;
  margin: 2em;
  color: #3d3d3d;
  --mdc-theme-primary: #007f8b;
  --mdc-theme-on-primary: #f1f3f4;
}

h1 {
  color: #007f8b;
}

h2 {
  clear: both;
}

video {
  clear: both;
  display: block;
}

section {
  opacity: 1;
  transition: opacity 500ms ease-in-out;
}

.mdc-button.mdc-button--raised.removed {
  display: none;
}

.removed {
  display: none;
}

.invisible {
  opacity: 0.2; 
}

.videoView,
.classifyOnClick {
  position: relative;
  float: left;
  width: 48%;
  margin: 2% 1%;
  cursor: pointer;
}

.videoView p,
.classifyOnClick p {
  padding: 5px;
  background-color: #007f8b;
  color: #fff;
  z-index: 2;
  margin: 0;
}

.highlighter {
  background: rgba(0, 255, 0, 0.25);
  border: 1px dashed #fff;
  z-index: 1;
  position: absolute;
}

.classifyOnClick {
  z-index: 0;
  font-size: calc(8px + 1.2vw);
}

.classifyOnClick img {
  width: 100%;
}

.webcamPredictions {
  padding-top: 5px;
  padding-bottom: 5px;
  background-color: #007f8b;
  color: #fff;
  border: 1px dashed rgba(255, 255, 255, 0.7);
  z-index: 2;
  margin: 0;
  width: 100%;
  font-size: calc(8px + 1.2vw);
}

</style>


</head>

<body>
  
  <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
  <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>

<h1>Classifying images using the MediaPipe Image Classifier Task</h1>

<section id="demos" class="invisible">
  <h2>Demo: Classify Images</h2>
  <p><b>Click on an image below</b> to see its classification.</p>
  <div class="classifyOnClick">
    <img src="https://assets.codepen.io/9177687/dog_flickr_publicdomain.jpeg" width="100%" crossorigin="anonymous" title="Click to get classification!" />
    <p class="classification removed">
    </p>
  </div>
  <div class="classifyOnClick">
    <img src="https://assets.codepen.io/9177687/cat_flickr_publicdomain.jpeg" width="100%" crossorigin="anonymous" title="Click to get classification!" />
    <p class="classification removed">
    </p>
  </div>

  <h2>Demo: Webcam continuous classification</h2>
  <p>Hold some objects up close to your webcam to get real-time classification. For best results, avoid having too many objects visible to the camera.</br>Click <b>enable webcam</b> below and grant access to the webcam if prompted.</p>

  <div class="webcam">
    <button id="webcamButton" class="mdc-button mdc-button--raised">
      <span class="mdc-button__ripple"></span>
      <span class="mdc-button__label">ENABLE WEBCAM</span>
    </button>
    <video id="webcam" autoplay playsinline></video>
    <p id="webcamPredictions" class="webcamPredictions removed"></p>
  </div>
</section>

<script type="module">
import {
  ImageClassifier,
  FilesetResolver
} from "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision";
const video = document.getElementById("webcam");
const webcamPredictions = document.getElementById("webcamPredictions");
const demosSection = document.getElementById("demos");
let enableWebcamButton;
let webcamRunning = false;
const videoHeight = "360px";
const videoWidth = "480px";

const imageContainers = document.getElementsByClassName(
  "classifyOnClick"
);
let runningMode = "IMAGE";

// Add click event listeners for the img elements.
for (let i = 0; i < imageContainers.length; i++) {
  imageContainers[i].children[0].addEventListener("click", handleClick);
}

// Track imageClassifier object and load status.
let imageClassifier;


const createImageClassifier = async () => {
  const vision = await FilesetResolver.forVisionTasks(
    "https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm"
  );
  imageClassifier = await ImageClassifier.createFromOptions(vision, {
    baseOptions: {
      modelAssetPath: `https://storage.googleapis.com/xxxxxxxxxxxxxxxxxx/resnet50_quantized.tflite`
    },
    maxResults: 7,
    runningMode: runningMode,
    scoreThreshold: 0.0
  });
  
  // Show demo section now model is ready to use.
  demosSection.classList.remove("invisible");
};
createImageClassifier();

/**
 * Demo 1: Classify images on click and display results.
 */
async function handleClick(event) {
  // Do not classify if imageClassifier hasn't loaded
  if (imageClassifier === undefined) {
    return;
  }
  // if video mode is initialized, set runningMode to image
  if (runningMode === "VIDEO") {
    runningMode = "IMAGE";
    await imageClassifier.setOptions({ runningMode: "IMAGE" });
  }

  // imageClassifier.classify() returns a promise which, when resolved, is a ClassificationResult object.
  // Use the ClassificationResult to print out the results of the prediction.
  const classificationResult = imageClassifier.classify(event.target);
  // Write the predictions to a new paragraph element and add it to the DOM.
  const classifications = classificationResult.classifications;

  const p = event.target.parentNode.childNodes[3];
  p.className = "classification";
  p.innerText =
    "Classificaton: " +
    classifications[0].categories[0].categoryName +
    "n Confidence: " +
    Math.round(parseFloat(classifications[0].categories[0].score) * 100) +
    "%";
  classificationResult.close();
}

/********************************************************************
// Demo 2: Continuously grab image from webcam stream and classify it.
********************************************************************/

// Check if webcam access is supported.
function hasGetUserMedia() {
  return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
}

// Get classification from the webcam
async function predictWebcam() {
  // Do not classify if imageClassifier hasn't loaded
  if (imageClassifier === undefined) {
    return;
  }
  // if image mode is initialized, create a new classifier with video runningMode
  if (runningMode === "IMAGE") {
    runningMode = "VIDEO";
    await imageClassifier.setOptions({ runningMode: "VIDEO" });
  }
  const startTimeMs = performance.now();
  const classificationResult = imageClassifier.classifyForVideo(
      video,
      startTimeMs
    );
  video.style.height = videoHeight;
  video.style.width = videoWidth;
  webcamPredictions.style.width = videoWidth;
  const classifications = classificationResult.classifications;
  webcamPredictions.className = "webcamPredictions";
  webcamPredictions.innerText =
    "Classification: " +
    classifications[0].categories[0].categoryName +
    "n Confidence: " +
    Math.round(parseFloat(classifications[0].categories[0].score) * 100) +
    "%";
  // Call this function again to keep predicting when the browser is ready.
  if (webcamRunning === true) {
    window.requestAnimationFrame(predictWebcam);
  }
}

// Enable the live webcam view and start classification.
async function enableCam(event) {
  if (imageClassifier === undefined) {
    return;
  }

  if (webcamRunning === true) {
    webcamRunning = false;
    enableWebcamButton.innerText = "ENABLE PREDICTIONS";
  } else {
    webcamRunning = true;
    enableWebcamButton.innerText = "DISABLE PREDICTIONS";
  }

  // getUsermedia parameters.
  const constraints = {
    video: true
  };

  // Activate the webcam stream.
  video.srcObject = await navigator.mediaDevices.getUserMedia(constraints);
  video.addEventListener("loadeddata", predictWebcam);
}

// If webcam supported, add event listener to button.
if (hasGetUserMedia()) {
  enableWebcamButton = document.getElementById("webcamButton");
  enableWebcamButton.addEventListener("click", enableCam);
} else {
  console.warn("getUserMedia() is not supported by your browser");
}

</script>

</body>
</html>

Both the default .tflite model and my customized .tflite load in the Chrome address bar, so I don’t think it’s an object permission. As you can see, the page does not load:

enter image description here

How to Get File Type passed into multipart form-data with Multer When Uploading to S3 in Node.js?

I’m using Multer to handle file uploads in my Node.js application, and I’m uploading files to an S3 bucket. I need to get the type I pass into multi-part formdata before uploading. How can I achieve this?

As I have mentioned in below Image like I want type invoice value before uploading file into S3 and and before going into multer upload function.

Postman Image

router.post('/upload', 
    passportAuth.authenticateJwt, 
    authorization.isAuthenticated,
    (req, res, next) => {
        try {
            upload.array('files', 10)(req, res, (err:any) => {
                if (err instanceof multer.MulterError) {
                    const customError = new Error("Size limit exceed");
                    return res.status(400).json({ status: "error", message: customError.message });
                } else if (err) {
                    const customError = new Error("Allow files only of extensions jpeg|jpg|png|doc|docx|pdf|xlsx|mp4|mkv|tff extensions !!!!");
                    return res.status(400).json({ status: "error", message: customError.message });
                } else {
                    next();
                }
            });
        } catch (error:any) {
            const customError = new Error("Internal Server Error");
            return res.status(500).json({ status: 'error', message: customError.message });
        }
    },
    s3Controller.uploadFiletoS3
);

Above I my route I have tried creating sperate middleware to get the req.body.type but I am not able to get req.body.type in both before the route and also into the below Image which I my upload function in that to I am not getting the body.file.type only getting the files which I am uploading.

Multer Function to upload the files

TypeError: Cannot read properties of undefined (reading ‘readFileSync’)

const { ethers } = require("ethers");
const { fs } = require("fs-extra"); 
require("dotenv").config(); 

async function main() {
  const provider = new ethers.providers.JsonRpcProvider(process.env.RPC_URL); 

  const encryptedJson = fs.readFileSync("./.encryptedKey.json", "utf8"); 

  let wallet = new ethers.Wallet.fromEncryptedJsonSync(
    encryptedJson,
    process.env.PRIVATE_KEY_PASSWORD
  ); 

  wallet = await wallet.connect(provider);

  const abi = readFileSync(
    "./hh-fcc/ethers-simple-storage_SimpleStorage_sol_SimpleStorage.abi",
    "utf8"
  );
  const binary = readFileSync(
    "./hh-fcc/ethers-simple-storage_SimpleStorage_sol_SimpleStorage.bin",
    "utf8"
  );
  const contractFactory = new ethers.ContractFactory(abi, binary, wallet);
  console.log("Deploying, please wait...");
  const contract = await contractFactory.deploy();
  await contract.deployTransaction.wait(1);

  const currentFavoriteNumber = await contract.retrieve();
  console.log(`Current Favorite Number: ${currentFavoriteNumber.toString()}`);
  const transactionResponse = await contract.store("7"); 
  const transactionReceipt = await transactionResponse.wait(1); 
  const updatedFavoriteNumber = await contract.retrieve();
  console.log(`Updated favorite number is: ${updatedFavoriteNumber}`);
}

main() // code for waiting the above code to finish
  .then(() => process.exit(0)) //and then print any errors
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

`For the above code I’m getting the error as: TypeError: Cannot read properties of undefined (reading ‘readFileSync’)

Based on the other solutions on stackoverflow I have lowered the version of ethers which solved the bug but ended up to this line of error`

Type Error in .d.ts File Angular Component from Library

I have created a library in Angular, and within it, I have created a component. After running npm i, I receive an error in the .d.ts file.

Error: node_modules/@my-lib/recursive-tree/lib/recursive-tree.component.d.ts:24:5 – error TS2344: Type ‘{ nodes: { alias: “nodes”; required: true; }; orderedChildren: { alias: “orderedChildren”; required: true; }; position: { alias: “position”; required: false; }; currentPosition: { alias: “currentPosition”; required: true; }; ids: { …; }; disableItem: { …; }; }’ does not satisfy the constraint ‘{ [key: string]: string; }’.
Property ‘”nodes”‘ is incompatible with index signature.
Type ‘{ alias: “nodes”; required: true; }’ is not assignable to type ‘string’.

This is my recursive-tree.component.ts:

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'lib-recursive-tree[currentPosition]',
  templateUrl: 'recursive-tree.component.html',
  styleUrls: ['recursive-tree.component.scss']
})
export class RecursiveTreeComponent {

  @Input() nodes?: any[];
  @Input() orderedChildren: string[] = [];
  @Input() position: number = 0;
  @Input() currentPosition!: string;
  @Input() ids?: { [key: string]: string[] };
  @Input() disableItem: boolean = false;
  @Output() selectedIdsChange = new EventEmitter<{ [key: string]: string[] }>();

  constructor() { }

  trackById(index: number, item: any) {
    return item.id;
  }

  updateSelectedIds(node: any) {

    if (!this.ids) {
        this.ids = {};
    }

    if (!this.ids[this.currentPosition]) {
        this.ids[this.currentPosition] = [];
    }
    
    if (node.selected) {
      if (!this.ids[this.currentPosition].includes(node.id)) {
        this.ids[this.currentPosition].push(node.id);
        this.deselectChildNodes(node);
      }
    } else {
      this.ids[this.currentPosition] = this.ids[this.currentPosition].filter(id => id !== node.id);
    }

    this.selectedIdsChange.emit(this.ids)
  }

  
  deselectChildNodes(node: any, pos: number = this.position) {
    const childNodes = node[this.orderedChildren[pos]];
    if (childNodes && Array.isArray(childNodes)) {
      for (const child of childNodes) {
        child.selected = false;
        const childPos = this.orderedChildren[pos + 1];
        if (this.ids && this.ids[childPos]) {
          this.ids[childPos] = this.ids[childPos].filter(id => id !== child.id);
        }
        this.deselectChildNodes(child, pos + 1);
      }
    }
  }


  updateSelectedIdsChild( obj: {[key:string]: string[]}){

    if (!this.ids) {
      this.ids = {};
    }

    this.ids = {...this.ids,
      ...obj
    }

    this.selectedIdsChange.emit(this.ids)

  }

}

I tried to search for solutions online but I found nothing