Node express (typescript) | serialize date type as epoach ms globally

Viewed 204

I wish to configure my node based API back-end, to serialize all of Date types as Epoch millis instead of ISO.

for example, if I have the following interface:

export interface Profile {
    updatedAt: Date;
    updatedBy: string;
}

and when I'm returning my struct back to the client:

 return res.status(OK).json(myProfile);

I get the following response:

   "updatedAt": "2021-06-08T17:06:44.412Z",
   "updatedBy": "825e9b827ce329a7ddc8fbdc3f714cbd1c239182"

I wish to receive:

   "updatedAt":  1623172004412,
   "updatedBy": "825e9b827ce329a7ddc8fbdc3f714cbd1c239182"

and to do it once, globally for all of my endpoints any Ideas?

1 Answers

To do this for any field, for any object, you could define a new function:

let customJSON = (obj) => {
    Object.entries(obj).map(([k,v]) => v instanceOf Date && (obj[k] = new Date(v).getTime()));
    return obj;
}

Then register this function in Express as middleware:

app.use((req, res, next) => {
    const originalSON = res.json
    res.json = (status, data) => {
        originalSON.call(res, customJSON(data));
    }
    next();
});

This should require no change to your call site:

return res.status(OK).json(myProfile);
Related