I'm learning to build APIs with Express. I figured that every time I have to send a successful JSON response, I have to duplicate most of the code. So I tried to put it in a function like so in one of my controller modules:
const successResponse = (res, statusCode, obj, coll = false) => {
const successObj = { status: "success" };
if (coll) successObj.results = obj.length;
successObj.data = { obj };
return res.status(statusCode).json(successObj);
};
exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
const player = await Player.findById(req.params.id);
if (!player) return next(new AppError("Player not found", 404));
successResponse(res, 200, player);
}
The problem is in the line successObj.data = { obj }
where I want the result to be the name of the argument that is passed as key and the object as value(s). The result I currently get is:
{
"status": "success",
"data": {
"obj": { // I want this key to be "player" here
"name": "Sal"
}
}
}
As the comment says I would like the key to be the string that I passed as the object name. I can do it by passing another argument as a string but it will always be the same as the object name that I pass. Is there a better way to do this?