forked from csxiaoyaojianxian/JavaScriptStudy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrest.js
More file actions
40 lines (40 loc) · 1.34 KB
/
rest.js
File metadata and controls
40 lines (40 loc) · 1.34 KB
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
/*
* @Author: csxiaoyao
* @Date: 2018-04-19 10:43:31
* @Last Modified by: csxiaoyao
* @Last Modified time: 2018-04-19 10:43:31
*/
module.exports = {
APIError: function (code, message) {
this.code = code || 'internal:unknown_error';
this.message = message || '';
},
restify: (pathPrefix) => {
// REST API前缀,默认为/api/
pathPrefix = pathPrefix || '/api/';
return async (ctx, next) => {
// 是否是REST API前缀
if (ctx.request.path.startsWith(pathPrefix)) {
console.log(`Process API ${ctx.request.method} ${ctx.request.url}...`);
// 绑定rest()方法
ctx.rest = (data) => {
ctx.response.type = 'application/json';
ctx.response.body = data;
}
try {
await next();
} catch (e) {
console.log('Process API error...');
ctx.response.status = 400;
ctx.response.type = 'application/json';
ctx.response.body = {
code: e.code || 'internal:unknown_error',
message: e.message || ''
};
}
} else {
await next();
}
};
}
};