Joe LoPresti
Joe LoPresti

Reputation: 37

express.js route not recognizing null value for conditional response

I am trying to render an alternative response to my express.js route when a date value in the parameter ends up being invalid. When I see an invalid date the value ends up being null so in my if statement in the middleware I test for a truthy value and if it is not truthy i serve up an alternative response.

What I get is the true value even though the value of the date is null. Here is an example:

api/timestamp/hello is my route.

A valid date should look like this: {"unix":1546214400000,"utc":"Mon, 31 Dec 2018 00:00:00 GMT"}

An invalid date like 'hello' should look like this {'error': 'Invalid Date'}

The code returns the correct value if the date is valid, but if the date is invalid I get {"unix":null,"utc":"Invalid Date"} instead of {'error': 'Invalid Date'}

Below is the code.

   app.get('/api/timestamp/:date', (req,res) => {
    let date = new Date(req.params.date);

    if (date === null) {        
        res.send({'error': 'Invalid Date'});             
    } else {
       let unix = date.getTime();  
       let utc = date.toUTCString();
       res.send({unix, utc});  
    }  
});

I'm relatively new to express and Node.js for that matter. Any thoughts on why the null value is not being recognized?

Upvotes: 1

Views: 1397

Answers (3)

Kevin Coulibaly
Kevin Coulibaly

Reputation: 156

Date constructor returns date to 1 January 1970 if the parameter is null and I can't think of any case it would return null.

Which means that your first check will always be false since your are using strict equality.

Probably you better be checking if req.params.date is truthy and unix is a valid timestamp

Hope this helps

Upvotes: 0

paulsm4
paulsm4

Reputation: 121669

Q: Wouldn't it make sense to check for a valid date BEFORE you try converting it to Unix and UTC?

app.get('/api/timestamp/:date', (req,res) => {

  let date = new Date(req.params.date);
  if (req.params.date && date instanceOf Date) {
    let unix = date.getTime();  
    let utc = date.toUTCString();
    res.send({unix, utc}); 
  } else {
    res.send({'error': 'Invalid Date'});
  }
}

Upvotes: 3

Sombriks
Sombriks

Reputation: 3622

The way you are building your response, node thinks it's a destructuring assignment, therefore you get the strange response.

To get what you want you can make something like this:

app.get('/api/timestamp/:date?', (req,res) => {
  if(req.params.date){
    let date = new Date(req.params.date);
    let unix = date.getTime();  
    let utc = date.toUTCString();
    if(unix) return res.send({unix,utc})
    res.send({'error': 'Invalid Date'});
  } else 
    res.send({'error': 'Invalid Date'});
})

Upvotes: 1

Related Questions