I'm new to express, currently if I want to send a response I would do the following
//...
res.json({
status: 200,
message: "success",
data: "something"
})
//...
for all my controllers functions I would do it this way. I guess this is kind of overwhelming so I was thinking if it's possible to make a generalized version of response.
so after some search I found there is 2 ways of achieving this:
1. use a middleware that runs at the end of each route
I found this answer. which made it clear but I think it's a waste of time and my controller then won't be readable enough and I must do the following in every controller function
req.responseObject = response;
return next()
2. override response class of the express itself
this is much promising, but unfortunately after so many tries and following express docs I couldn't get it to work here is what I've tried so far
I've created this util function here:
//myRes.js
module.exports = function (code, message, payload) {
return this.status(code).json({
status: 'success', // this will be variable according to whatever code I get
code: code,
message: message || '',
payload: payload || '',
});
};
then I've added this line to app.js
// app.js
const express = require('express');
const app = express();
const myRes= require('./utils/myRes');
app.response.send = myRes;
//...
and this is how I use it on my controller
res.send(200, "hello world", [{"key": "value"}])
when I try to run this I got this Error stack
RangeError: Maximum call stack size exceeded
at JSON.stringify (<anonymous>)
at stringify ([project_dir]\node_modules\express\lib\response.js:1123:12)
at ServerResponse.json ([project_dir]\node_modules\express\lib\response.js:260:14)
at ServerResponse.module.exports [as send] ([project_dir]\src\utils\response.js:2:28)
at ServerResponse.json ([project_dir]\node_modules\express\lib\response.js:267:15)
at ServerResponse.module.exports [as send] ([project_dir]\src\utils\response.js:2:28)
at ServerResponse.json ([project_dir]\node_modules\express\lib\response.js:267:15)
at ServerResponse.module.exports [as send] ([project_dir]\src\utils\response.js:2:28)
at ServerResponse.json ([project_dir]\node_modules\express\lib\response.js:267:15)
at ServerResponse.module.exports [as send] ([project_dir]\src\utils\response.js:2:28)
at ServerResponse.json ([project_dir]\node_modules\express\lib\response.js:267:15)
at ServerResponse.module.exports [as send] ([project_dir]\src\utils\response.js:2:28)
at ServerResponse.json ([project_dir]\node_modules\express\lib\response.js:267:15)
at ServerResponse.module.exports [as send] ([project_dir]\src\utils\response.js:2:28)
at ServerResponse.json ([project_dir]\node_modules\express\lib\response.js:267:15)
at ServerResponse.module.exports [as send] ([project_dir]\src\utils\response.js:2:28)
why JSON.stringify is complaining I haven't used this function on my entire application
also I am not just capped to these 2 solutions you can suggest other ways if you think it's better