63 lines
1.3 KiB
JavaScript
63 lines
1.3 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 _formatResponse = (req, res, next, err, response) => {
|
||
|
if (err) {
|
||
|
req.response = response;
|
||
|
next(err);
|
||
|
} 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;
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Fonction permettant de formater une erreur
|
||
|
* @param {Object} res
|
||
|
* @param {Object} err
|
||
|
*/
|
||
|
const _formatResponseError = (res, err) => {
|
||
|
const code = err.errorCode || 500;
|
||
|
const response = {
|
||
|
code,
|
||
|
message: err.message
|
||
|
};
|
||
|
|
||
|
res.status(Math.trunc(code)).json(response);
|
||
|
};
|
||
|
|
||
|
export const formatResponse = _formatResponse;
|
||
|
export const formatResponseError = _formatResponseError;
|