-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
112 lines (97 loc) · 2.98 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
103
104
105
106
107
108
109
110
111
112
'use strict';
var utils = require('./lib/helperUtils');
function getOpts(middlewareOpts, overrides) {
overrides = overrides || {};
var defaultOptions = {
responseProperty: {
value: "data"
},
apiVersion: {
enabled: false,
value: "1.0.0"
},
status: {
enabled: false,
value: function(data) {
return (data instanceof Error) ? "error" : "success";
}
},
count: {
enabled: false
},
statusCode: {
enabled: false,
value: function(data) {
return (data instanceof Error) ? 500 : 200
}
}
};
return utils.assign({}, defaultOptions, middlewareOpts, overrides);
}
function generatePayload(data, options) {
data = data || {};
if (data === undefined || data === null || typeof data !== 'object') {
throw new TypeError('Data is not an object.');
}
var payload = {};
var payloadModel = {
apiVersion: {
check: options.apiVersion.enabled,
value: options.apiVersion.value
},
count: {
check: options.count.enabled && (Array.isArray(data)),
value: data.length
},
statusCode: {
check: options.statusCode.enabled,
value: options.statusCode.value(data)
},
status: {
check: options.status.enabled,
value: options.status.value(data)
}
};
// ES5 compatible instead of using ComputePropertyNames
payloadModel[options.responseProperty.value] = {
check: true,
value: data
};
Object.keys(payloadModel).forEach(function(k) {
if (payloadModel[k].check) {
payload[k] = payloadModel[k].value;
}
});
return payload;
}
function sendJSON(middlewareOpts) {
middlewareOpts = middlewareOpts || {};
if (typeof middlewareOpts !== 'object') {
throw new Error('Options must be an object.');
}
return function(req, res, next) {
res.sendJSON = function(data, statusCode) {
middlewareOpts = middlewareOpts || {};
data = data || {};
if (statusCode && typeof statusCode != 'number') {
throw new Error('Status code must be a number.');
}
if (typeof middlewareOpts !== 'object') {
throw new Error('Response options must be an object.');
}
var options = (statusCode) ? getOpts(middlewareOpts, {
statusCode: {
enabled: true,
value: function() {
return statusCode;
}
}}) : getOpts(middlewareOpts);
var payload = generatePayload(data, options);
return res
.status(options.statusCode.value())
.json(payload);
};
next();
}
}
module.exports = sendJSON;