Express: Body parser JSON reviver not working as expected

643 views Asked by At

I'm using Node and Express, hosting in Firebase Functions to build an API to persist the data.

When I send a JSON object to a router, the parser works ok, but when I have Dates, they are parsed as string, causing some trouble to save the data correctly.

I discovered the body parser could help me, as it includes a reviver function to JSON.parse when parsing the request body.

In my index.ts I have:

const app = express();
const main = express();

app.use('/', indexRouter);
app.use('/mail', mailRouter);
// ... more routes

main.use(cors());
main.use(bodyParser.urlencoded({ extended: true }));
main.use(bodyParser.json({
    reviver: (key, value) => {
        if (typeof value === "string") {
            const valueDate = new Date(value).getTime();

            if(!isNaN(valueDate)){
                return new Date(value);
            }
        }

        return value;
    }
}));
main.use('/v1', app);

export const api = functions.https.onRequest(main);

In the visit.ts router I have:

import express from 'express';
import Visit from '../models/visit';

const router = express.Router();

router.post('/', async (req, res) => {
    const visit = <Visit>req.body;
    console.log('Is date: `, visit.date instanceof Date)
});

export default router;

It seems the reviver is never called (if I put just a console.log, it's never showed up)

Am I missing some detail? The order of middlewares in index.ts is wrong? I've got no clue :(

PS: I'm testing using Postman, putting the header Content-Type as application/json. In the application I am using the fetch function using the same header.

0

There are 0 answers