-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpressResponder.js
44 lines (37 loc) · 1010 Bytes
/
expressResponder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import logger from './logger';
import _ from 'lodash';
function Responder() {}
/*
* This method sends the response to the client.
*/
function sendResponse(res, status, body) {
if(!res.headersSent) {
if(body)
return res.status(status).json(body);
return res.status(status).send();
}
else {
logger.error('Response already sent.');
}
}
/*
* These methods are called to respond to the API user with the information on
* what is the result of the incomming request
*/
Responder.success = (res, message) => {
message = _.isString(message) ? { message } : message;
return sendResponse(res, 200, message);
}
Responder.created = (res, object) => {
return sendResponse(res, 201, object);
}
Responder.deleted = (res) => {
return sendResponse(res, 204);
}
Responder.operationFailed = (res, reason) => {
const status = reason.status;
logger.error(reason);
reason = reason.message || reason;
return sendResponse(res, status || 400, {reason});
}
export default Responder;