-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.js
36 lines (33 loc) · 925 Bytes
/
rest.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
module.exports = {
APIError: function(code, message) {
this.code = code || "internal:unknown_error";
this.message = message;
},
restify: pathPrefix => {
// REST API前缀
pathPrefix = pathPrefix || "/api/";
return async (ctx, next) => {
// 是否是REST API前缀
if (ctx.request.path.startsWith(pathPrefix)) {
// 绑定rest()方法
ctx.rest = data => {
ctx.response.type = "application/json";
ctx.response.body = data;
};
try {
await next();
} catch (e) {
// 返回错误:
ctx.response.status = 400;
ctx.response.type = "application/json";
ctx.response.body = {
code: e.code || "internal:unknown_error",
message: e.message || ""
};
}
} else {
await next();
}
};
}
};