Reputation: 159
I'm building a small CRUD app on the Express framework. I want to have a middleware that takes all my responses and verifies them against the expected object schemas. The issue what I'm currently facing is that I don't know where to put this middleware. I've tried to put it globally after my routes and the error handler middleware, but it didn't work for some reason. When I sticked it before my defined routes this middleware worked, but didn't have the required data from a route handler. I'm pretty familiar with the middleware concept in Express, but only for requests.
If you don't have a specific answer for this issue, please feel free to share your opinion if it helps to verify all outbound response. Thanks.
Any help is appreciated.
Upvotes: 0
Views: 1154
Reputation: 2189
I can give you an example usage. You can modify the response
object as you desire.
// ResponseHandler.js
// Creating a response object
class ResponseHandler{
constructor(statusCode, body, success = 1){
this.statusCode = statusCode;
this.body = body;
this.body.success = success ? success : (statusCode == 200 ? 1 : 0);
}
}
module.exports = ResponseHandler;
// responseHandler.js
const ResponseHandler = require('./ResponseHandler');
const responseValidator = (err, req, res, next) => {
let res = res;
if (!(res instanceof ResponseHandler)) {
const statusCode = res.statusCode;
const body = res.body;
const success = res.body.success;
res = new ResponseHandler(statusCode, body, success);
}
next(res);
};
const responseHandler = (err, req, res, next) => {
const response = responseValidator(res);
res.status(response.statusCode).send(response.body);
};
module.exports = {
responseHandler
};
// Usage
// In index.js (After defining your routes)
app.use(responseHandler);
// In controller
let res = {
statusCode: 200,
body: {
success: 1, // Optinal
message: "This is a success message."
}
}
return next(res);
Upvotes: 1