1

When a client passes a deprecated date format to my

I'm running a Node in which clients can post dates to the API. When they pass a deprecated time format to my Moment parser, I'm thinking maybe returning a 400 to the client. I'm not sure if this is a recommended approach, and would like your views on it. In my particular case it shouldn't cause much problems, as it will only affect my team.

If I decide to go for returning 400 when such deprecated date formats are passed to my API, I need a way of detecting these occurrences. As of now, I get deprecated warnings in the server log, but haven't found a way to to this. I tried this, but since Moment doesn't seem to throw a real error (even if it certainly looks like it from the logs), it's not detecting the deprecated dates:

try {
  my_date = Moment(request.body.date)
}
catch (err) {
  console.log("ERROR");
}

This will only catch real errors, not deprecated warnings.

Does anyone know how to catch Moment deprecated warnings in the code?

kenneho
  • 401
  • 1
  • 7
  • 24

1 Answers1

1

To see if a date is valid according to your currently supported format, use something like this:

var formats = [
    moment.ISO_8601,
    "MM/DD/YYYY HH:mm:ss",
    // some other formats that you need ...
];
if (!moment(request.body.date, formats, true).isValid()) {
    return res.status(400).send('Invalid date format');
}
// handle request

Always use true as a third argument to moment() for strict validation. Otherwise it will try to match invalid dates as well.

And always provide an explicit list of supported formats that you want to use or otherwise you will not be sure what is matched and what isn't, especially in future versions of Moment where it may change.

See this answer for more info:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177