How do I implement data range filtering in Typescript?

Seeking assistance with filtering data by date range and forwarding the results to the client. The objective is to extract tickets created within specific dates, but I keep encountering a console error which is proving challenging to resolve.

    var before:Date = req.query.before;
  if(before !== undefined){
        //@ts-ignore
        var after:Date = req.query.before;
        var filteredData = tempData.filter(function(t){
        return res.send(new Date(t.creationTime) >= after && new Date(t.creationTime) <= before);      
        });
  }

This is the error message displayed in the console:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:558:11)
    at ServerResponse.header (C:\Project\server\node_modules\express\lib\response.js:771:10)
    at ServerResponse.json (C:\Project\server\node_modules\express\lib\response.js:264:10)
    at ServerResponse.send (C:\Project\server\node_modules\express\lib\response.js:158:21)
    at C:\Project\server\index.ts:48:20
    at Array.filter (<anonymous>)
    at C:\Project\server\index.ts:47:37
    at Layer.handle [as handle_request] (C:\Project\server\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Project\server\node_modules\express\lib\router\route.js:137:13)  
    at Route.dispatch (C:\Project\server\node_modules\express\lib\router\route.js:112:3)

Answer №1

Each element in the tempData array is evaluated by the function provided to the filter method.

Within the filter function, there is a call to the res.send() method which sends a response back to the client. It's important to note that this method should only be called once per request, but currently, it is being called for each element in the tempData array.

To optimize your code, consider filtering the data first before sending it back to the client.

let filteredData = tempData.filter(function(t){
    return new Date(t.creationTime) >= after && new Date(t.creationTime) <= before;
});
res.send(filteredData);

In addition, there seems to be an issue with your code where both the before and after variables are set to req.query.before.

The statement

new Date(t.creationTime) <= before && new Date(t.creationTime) >= after;
will likely result in yielding false unless t.creationTime equals req.query.before, leading to an empty array for filteredData. Refer to the documentation on the filter method for more insights.

A possible solution (assuming req.query.after is defined) could be:

const before:Date = req.query.before;
  if(before !== undefined){
        //@ts-ignore
        const after:Date = req.query.after;
        let filteredData = tempData.filter(function(t){
          return new Date(t.creationTime) <= before && new Date(t.creationTime) >= after;
      });
      TICKETS_AMOUNT = filteredData.length.toString();
      res.send(filteredData);
  }

I have provided a full example below:

interface DataType {
    name: string,
    date: Date,
}

let data: Array<DataType> = [
    {"name": "foo", date: new Date(2020, 5, 12)},
    {"name": "bar", date: new Date(2020, 7, 20)},
    {"name": "baz", date: new Date(2021, 2, 23)},
];

app.get('/filter-date-range', (req, res): void => {
    let result = data;

    if (req.query.before) {
        let before: Date = new Date(String(req.query.before));
        if (!isNaN(before.getTime())) {
            result = result.filter((e) => e.date <= before);
        } else {
            res.status(400).send("Unable to parse before date.");
            return;
        }
    }

    if (req.query.after) {
        let after: Date = new Date(String(req.query.after));
        if (!isNaN(after.getTime())) {
            result = result.filter((e) => e.date >= after);
        } else {
            res.status(400).send("Unable to parse after date.");
            return;
        }
    }

    res.json(result);
});

Simply adjust the data variable to suit your specific project needs.

Answer №2

Each element in the tempData array will undergo evaluation by the function passed to the filter method.

I made a modification, and now I no longer receive console errors; however, there seems to be no output as a result.

const before: Date = req.query.before;
if(before !== undefined){
    //@ts-ignore
    const after: Date = req.query.before;
    let filteredData = tempData.filter(function(t){
        return new Date(t.creationTime) <= before && new Date(t.creationTime) >= after;
    });
    TICKETS_AMOUNT = filteredData.length.toString();
    res.send(filteredData);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show a notification if the MongoDB collection is devoid of any data

One of the features of my website is a notices section, which retrieves data from my Mongo Database. In case there are no new notices in the collection, I want to display a message saying "No new notices." The following code snippet shows how I am impleme ...

What is the best way to initiate a refetch when the need arises to follow a different path?

I have encountered a situation where I am able to pass the refetch function on a child component. However, an issue arises when transitioning to another page and implementing redux. This is particularly problematic when attempting to open a dialog for a ne ...

Utilizing NodeJs to retrieve data asynchronously and store it in a variable for future use

I've spent hours searching for a solution on how to implement an async function that can return a result, store it in a variable outside the function, and reuse that data. Unfortunately, I haven't had any luck so far. The main issue I'm fac ...

Updating the value in React context does not result in the value being updated

I am in the process of developing a simple routing system where users can either be authenticated or not. I have been using hooks to implement this functionality, but so far, it has not been as successful as I hoped for. authProvider.tsx import React, {Di ...

"Error message: Trying to import a component in Angular, but encountering a message stating that the component has no exported

When creating a component named headerComponent and importing it into app.component.ts, an error is encountered stating that 'website/src/app/header/app.headerComponent' has no exported member 'headerComponent'. The code for app.headerC ...

Integrating Google Sheets in an Express.js application involves syncing data

Is it possible to implement a feature in Express JS that allows users to authorize their Google account with our app? This way, we can access the google sheet from their accounts and display it within our express app. If users make changes to the spreadshe ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

"Exploring the power of Angular 16 coupled with Firebase 9 for seamless file

Recently, I've been facing some challenges with my Angular 16 app that uses Firebase 9 and angular/fire 7. Specifically, I've been struggling to implement a simple file upload feature to Firebase storage. Despite spending the last couple of days ...

Issues with React Material UI Select functionality not performing as expected

I've been working on populating a Select Component from the Material UI library in React, but I'm facing an issue where I can't choose any of the options once they are populated. Below is my code snippet: import React, { useState, useEffect ...

Why does React redirect me to the main page after refreshing the page, even though the user is authenticated in a private route?

In the process of developing a private route component that restricts unauthenticated users and redirects them to the homepage, we encountered an issue upon page refresh. The problem arises when the current user variable momentarily becomes null after a ...

Exploring the depths of mongodb through targeted field queries

I am working with a collection of objects structured like this : var Meetup = new Schema({ name: String, text:String, }); My goal is to retrieve all meetups whose name contains a specific string. Below is the API code snippet : module.exports. ...

Error: Invalid parameter detected for Shopify script-tag

I'm encountering a persistent error message stating { errors: { script_tag: 'Required parameter missing or invalid' } } This issue arises when attempting to upload a script tag to a storefront. Currently, I'm just experimenting with s ...

Experiencing Issues Connecting to AWS RDS MySQL Database Through Express JS

I have been attempting to establish a connection with my Amazon RDS cloud database using the Express framework. The connection setup in my server.js file is as follows: const express = require('express'); var bodyParser = require('body-pars ...

Why is Socket.io functioning on localhost but fails to work once deployed to Heroku?

Sharing my socket server code: const io = require("socket.io")(8080, { cors: { // origin: "http://localhost:3000", origin: "https://mern-bubble.herokuapp.com", }, }); This is the client-side implementation: useEf ...

How to verify if an unknown-type variable in TypeScript contains a specific property

When using typescript with relay, the props passed down are of type unknown. Despite my efforts, I am unable to persuade the compiler that it can have some properties without encountering an error: <QueryRenderer environment={environment} query={te ...

What exactly is the functionality of the third parameter (usually next()) behind the scenes in ExpressJS once it is hidden behind the abstraction layer?

Consider this scenario: in the following two code snippets, how is the next() function used as a parameter and how does it facilitate the automatic transition to the next middleware function? What is the underlying mechanism that enables this abstraction? ...

I'm looking to add autocomplete functionality to a text input in my project, and then retrieve and display data from a MySQL database using

Looking to enhance user experience on my form where users can select inputs. Specifically, I want to implement a feature where as the user starts typing in a text input field with data from a MYSQL database, suggestions will be displayed. The form is locat ...

Retrieve data from the database that meets criteria based on multiple entries in a junction table

Can you assist me in selecting data from a database based on multiple occurrences in a junction table? I am using Sequelize ORM, but plain SQL would work as well. I need the query to be dynamic, taking user input into account. However, a static solution w ...

Encountering an Uncaught TypeError when attempting to set properties of null with useRef

I've been working on an app that requires access to the user's device camera in order to display live video on the screen. I've managed to achieve this by utilizing a video HTML Object and setting the media stream as its srcObject. Everythin ...

React: Issue with passing arguments to redux action hooks

In my React application, I have implemented Redux-Toolkit to manage reducers and actions with slices. I am currently working on creating actions that can update and delete values from the store, requiring arguments for their usage. To achieve this, I have ...