53 lines
1.1 KiB
JavaScript
53 lines
1.1 KiB
JavaScript
/**
|
|
* Fonction permettant de formater une réponse API
|
|
* @param {Object} req
|
|
* @param {Object} res
|
|
* @param {Functiont} next
|
|
* @param {Object} err
|
|
* @param {Object} response {code: Integer, res: Array/Object}
|
|
*/
|
|
const ResponseFormater = (req, res, next, err, response) => {
|
|
if (err) {
|
|
const code = err.errorCode || 500;
|
|
|
|
res
|
|
.status(Math.trunc(code))
|
|
.json({
|
|
code,
|
|
message: err.message
|
|
})
|
|
.end();
|
|
} else {
|
|
switch (req.method) {
|
|
case "GET":
|
|
res
|
|
.status(response ? 200 : 204)
|
|
.json(response)
|
|
.end();
|
|
break;
|
|
case "PATCH":
|
|
res
|
|
.status(200)
|
|
.json(response)
|
|
.end();
|
|
break;
|
|
case "DELETE":
|
|
res
|
|
.status(200)
|
|
.json(response)
|
|
.end();
|
|
break;
|
|
case "POST":
|
|
res
|
|
.status(201)
|
|
.json(response)
|
|
.end();
|
|
break;
|
|
default:
|
|
next(new Error("Not implemented"));
|
|
break;
|
|
}
|
|
}
|
|
};
|
|
|
|
export default ResponseFormater;
|