-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
48 lines (43 loc) · 1.04 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
module.exports = function (options = {}) {
const custom = options.custom
if (custom && (typeof custom !== 'function')) {
throw new TypeError('`custom` should be a function that return an object')
}
return async function koaRes (ctx, next) {
try {
await next()
if (ctx._returnRaw) {
return
}
const code = ctx.status
const data = ctx.body
if (ctx.method.toLowerCase() !== 'option' && code !== 404) {
ctx.body = {
code,
data
}
if (custom) {
Object.assign(ctx.body, custom(ctx))
}
ctx.status = code
}
} catch (e) {
if (ctx._returnRaw) {
throw e
}
ctx.app.emit('error', e, ctx)
ctx.status = e.status || e.statusCode || 500
ctx.body = {
code: ctx.status,
message: e.message || e,
stack: e.stack || e
}
if (custom) {
Object.assign(ctx.body, custom(ctx))
}
if (!options.debug) {
delete ctx.body.stack
}
}
}
}