forked from tb1over/node-koa-REST-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.js
35 lines (30 loc) · 867 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
//REST绑定
module.exports={
APIError: function (code, message) { //restAPI错误处理
this.code = code || 'internal:unknown_error';
this.message = message || '';
},
restify: (pathPrefix) => { //restAPI方法绑定->为ctx绑定rest方法
pathPrefix=pathPrefix || '/api/';
return async (ctx,next)=>{
if(ctx.request.path.startsWith(pathPrefix)){ //API请求
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:unknow_error',
message: e.message || ''
};
}
}else{
await next();
}
}
}
}