-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
191 lines (153 loc) · 4.92 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
const qs = require('querystring');
const stream = require('stream');
class Nuntio {
constructor(message, data, page, ctx) {
if (typeof message !== 'string') {
[data, page, message] = [message, data, page];
}
page && (page.page = page.page && parseInt(page.page));
page && (page.limit = page.limit && parseInt(page.limit));
page && (page.offset = page.offset && parseInt(page.offset));
this.data = data;
this.page = page;
this.message = message || 'OK';
this.statusCode = 200;
this.ctx = ctx;
}
toJSON() {
return {
statusCode: this.statusCode,
message: this.message,
page: this.constructPage(),
data: this.data
};
}
constructUrl(query) {
const ctx = this.ctx;
return `${ctx.path}?${qs.stringify(query)}`;
}
constructPage() {
if (!this.page || typeof this.page !== 'object' || !this.page.count) return;
let prevPage, nextPage, prevOffset, nextOffset;
let { page, offset, limit, count } = this.page;
const { query } = this.ctx;
if (!offset && isFinite(page)) {
offset = page * limit;
}
if (offset > 0) {
prevPage = page - 1;
prevOffset = Math.max(0, offset - limit);
}
if (count > offset + limit) {
nextPage = page + 1;
nextOffset = offset + limit;
}
const pageQuery = { ...query, limit };
const prevPageQuery = { ...pageQuery, page: prevPage, offset: prevOffset };
const nextPageQuery = { ...pageQuery, page: nextPage, offset: nextOffset };
return {
...this.page,
prev: isFinite(prevOffset) && {
url: this.constructUrl(prevPageQuery),
query: prevPageQuery,
queryString: '?' + qs.stringify(prevPageQuery)
},
next: isFinite(nextOffset) && {
url: this.constructUrl(nextPageQuery),
query: nextPageQuery,
queryString: '?' + qs.stringify(nextPageQuery)
}
};
}
updateCtxWithError(ctx) {
ctx.status = this.statusCode;
ctx.body = this;
}
/**
* @param {object} [opts={}] - configure middlewar
* @param [opts.catchAll=false] - catch non-Nutio errors
* @param [opts.expose=false] - pass error info to client
* @param [opts.log=true] - log caught exceptions
* @return {function}
*/
static middleware(opts = {}) {
opts = { catchAll: false, expose: false, log: true, ...opts };
return async function NuntioMiddleware(ctx, next) {
try {
await next();
if (
ctx.type === 'application/json' &&
!ctx.state.nuntio_skip &&
!(ctx.body instanceof stream)
) {
ctx.body = new Nuntio(ctx.message, ctx.body, ctx.page, ctx).toJSON();
}
} catch (error) {
if (opts.log) console.error(error);
if (error instanceof Nuntio) {
error.updateCtxWithError(ctx);
} else if (opts.catchAll) {
Nuntio.error(error.message, error, opts).updateCtxWithError(ctx);
} else {
throw error;
}
}
};
}
static end(ctx, body, message) {
body = body || ctx.body || null;
message = message || ctx.message === 'Not Found' ? 'OK' : ctx.message;
ctx.body = new Nuntio(message, body, ctx.page, ctx).toJSON();
ctx.state.nuntio_skip = true;
}
/**
* Check if val evaluates to true, otherwise throw supplied error.
* @param {*} val - value to check if true
* @param {string|object|function|Error} error - will be thrown if assertion fails
*/
static assert(val, error) {
if (!!val) return;
if (typeof error === 'function') {
error = error();
}
throw error;
}
static error(message, error, options) {
if (message instanceof Error) {
[error, options, message] = [message, error, options];
} else if (!(error instanceof Error)) {
[message, options, error] = [message, error, options];
}
options = options || {};
message = message || 'Internal Server Error';
// Support calling with statusCode only;
if (typeof options === 'number') {
options = { statusCode: options };
}
options.expose = options.expose || process.env.NODE_ENV === 'development';
const nuntio = new Nuntio(message, options.expose && { original: error });
if (!error) {
error = new Error();
Error.captureStackTrace(error, Nuntio);
}
const { statusCode = 500, ...restOpts } = options;
nuntio.error = error;
nuntio.data = { original: error };
nuntio.options = restOpts;
nuntio.statusCode = statusCode;
if (nuntio.error instanceof Error && !('toJSON' in nuntio.error)) {
nuntio.error.toJSON = function toJSON() {
const alt = {};
Object.getOwnPropertyNames(this).forEach(function(key) {
alt[key] = this[key];
}, this);
return alt;
};
}
return nuntio;
}
static unauthorized(message = 'unauthorized', options) {
return Nuntio.error(message, { statusCode: 401, ...options });
}
}
module.exports = Nuntio;