Yes, we are sending a response for each REST API. Is it recommended to create a generic function for sending responses and reducing code lines? What are the benefits and drawbacks of common response function? Thank you in advance for your responses.
Current Code:
router.get('/all', async (req, res) => {
console.log("Get-all api is hitting");
let limit = req.query.limit || 10
const all_posts = await Post.find().sort({ published_at: -1 }).limit(limit)
console.log("all_posts", all_posts);
if (!all_posts) return res.json({
success: false,
message: "Something went wrong"
});
return res.json({
success: true,
message: "All posts",
data: all_posts
});
})
Expected Code:
- Writing a common function in this file
in helpers/response.js
// Sending response function
async function response(res, status, message, data) {
res.json({
success: status,
message: message,
data: data
});
}
module.exports = { response }
in controller file
const { response } = require('..helpers/response')
router.get('/all', async (req, res) => {
console.log("Get-all api is hitting");
let limit = req.query.limit || 10
const all_posts = await Post.find().sort({ published_at: -1 }).limit(limit)
console.log("all_posts", all_posts);
if (!all_posts) return response(res, false, "Something went wrong", [])
return response(res, true, "Fetched all posts", all_posts)
})