core
core copied to clipboard
Custom response interceptors.
There is should be a way to get the custom response for every API instead of fixed.
Generically (i.e., raw express), it might be done something like this:
const express = require('express');
const app = express();
app.all('*', (req, res, next) => {
var json = res.json;
res.json = function (data) {
const result = {
...data,
inserted: 1
};
json.call(this, result);
};
next();
});
app.use('/endpoint', (req, res, next) => {
res.json({
result: 1
});
next();
});
app.use((req, res) => {
if (!res.headersSent)
res.status(404).json({error: 'NOT_FOUND'});
});
app.listen(3000, () => console.log('Example app listening on port 3000!'));
I included the 404 handler because there's a problem here that's surfaced.
If I GET /endpoint the response code is 200 with body:
{
"result": 1,
"inserted": 1
}
However, if I get an invalid URL, GET /invalid, the response code is properly 404, but the body ran through the catch all interceptor:
{
"error": "NOT_FOUND",
"inserted": 1
}
Note to self - the * interceptor pattern used above might be a way to refactor how resLocals works so that the route handlers don't have to call next unless they implement an after or afterAll handler.