I’m trying to create a middleware that logs information about the request to a MongoDB database using mongoose. So far I have managed to successfully do so by modifying the res object.
const logger: RequestHandler = async (req, res, next) => {
const originalJson = res.json;
// ** modify the res.json function
res.json = async function (body: ResBody) {
const { _log, ...rest } = body
if (_log) {
try {
// do something with the log
await LogsModel.create({
..._log,
// other stuff
})
} catch (error) {
console.error('Error creating log.n', error)
}
}
// ** call the original res.json function and send the response.
originalJson.call(this, rest)
return;
}
next()
}
With this middleware, any API that calls res.json()
and include an _log
property to the response object will trigger this and create a log in the LogsModel
.
The model needs to have a unique logID
, which is generated by a custom function that counts the total documents in the collection and simply increments it for future logs. However, if multiple requests come in concurrently from different APIs who call res.json
, the logID
goes out of sync and does not properly increment.
For example, suppose the collection is empty and three APIs were called concurrently, the ID generated will all have the value of 00000000
indicating the first entry to the collection. Is there a way to process this correctly, where there will be three log ID: 00000000
, 00000001
, and 00000003
?
I can’t use unique ID generators (like uuid
) because the id has some pattern format.