This repository has been archived by the owner on Oct 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (89 loc) · 2.49 KB
/
index.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*jslint node:true indent:2 nomen:true*/
'use strict';
var arg = require("arg-err").config({ propErr: true }),
assert = require('assert');
module.exports = function (req, res, next) {
function sendResponse(code, json) {
if (req.query.callback) {
return res.jsonp(json);
}
return res.status(code).json(json);
}
function getSuccessCode() {
return (req._method === 'POST' || req.method === 'POST') ? 201 : 200;
}
function getSuccessResponseData(data) {
return (!data || (req._method === 'DELETE' || req.method === 'DELETE')) ? null : data;
}
res.jSend = function (data, metadata) {
var payload = {
status: 'success',
data: getSuccessResponseData(data)
};
if (metadata) {
payload.metadata = metadata;
}
return sendResponse(getSuccessCode(), payload);
};
function formatErrorObject(err) {
return {
message: String(err),
stack: err.stack
};
}
function validateErrorOptions(options) {
assert(options, 'res.jSend.error invoked without options');
var required = {
message: "string"
},
optional = {
code: "number",
data: "object"
},
err = arg.err(options, required, optional);
assert(!err, 'res.jSend.error options validation: ' + err);
}
res.jSend.error = function (options) {
validateErrorOptions(options);
if (options.data instanceof Error) {
options.data = formatErrorObject(options.data);
}
if (options.code === undefined) {
options.code = 500;
}
var responseData = {
status: 'error',
code: options.code,
message: options.message
};
if (process.env.NODE_ENV !== 'production') {
responseData.data = options.data || null;
}
return sendResponse(options.code, responseData);
};
function validateFailOptions(options) {
assert(options, 'res.jSend.fail invoked without options');
var required = {},
optional = {
data: ["object", "string"],
code: "number",
message: "string",
},
err = arg.err(options, required, optional);
assert(!err, 'res.jSend.fail options validation: ' + err);
}
res.jSend.fail = function (options) {
validateFailOptions(options);
if (options.code === undefined) {
options.code = 400;
}
var responseData = {
status: 'fail',
code: options.code,
data: options.data,
message: options.message
};
return sendResponse(options.code, responseData);
};
return next();
};