I am building an API with express and JSON middleware. I want to have a generic middleware that wraps each JSON response. The wrapping is an asynchronous process - there is a backend process that asynchronously generates a signature for the given JSON object. Example:
A route:
app.use("/", (req, res) => res.json({status: "ok"}))
The middleware would ideally intercept the JSON response, asynchronously generate a signature and ultimately send the user the following JSON:
{
"signature": "...",
"content": { "status": "ok" }
}
What's the best approach to building such a middleware?
I have tried replacing res.json with a custom function. The problem with this solution is that the signature generation is asynchronous, but the res.json is a synchronous function. This was my approach:
export function signatureMiddleware(req, res, next) {
var json = res.json;
res.json = async function (obj) {
json.call(this, await wrapAndSign(obj));
};
next();
}