UNPKG

1.49 kBJavaScriptView Raw
1
2
3
4
5module.exports = Context
6
7
8function Context(context,app){
9 var models = app.models;
10
11 /*模块获取函数*/
12 if(context.m)
13 console.error('koa context中m方法已经存在,请注意');
14 else
15 context.m = getModel
16
17 function getModel(name){
18 if(!models[name]){
19 console.error('你所调用的 模型不存在!');
20 throw new Error();
21 }
22 else{
23 return models[name]
24 }
25 }
26
27
28 /*ajax格式助手*/
29 if(context.ajax)
30 console.error('koa context中ajax方法已经存在,请注意');
31 else
32 context.ajax = ajaxHandler
33
34
35 function ajaxHandler(errorMsg,data){
36 var result = {}
37 if(arguments.length == 2){
38 result.status = 'error'
39 result.msg = errorMsg
40 result.data = data;
41 }
42 else if(arguments.length == 1){
43 result.status = 'success'
44 result.data = errorMsg;
45 }
46 context.body = result;
47 }
48
49
50 /*ajax格式助手*/
51 if(context.send)
52 console.error('koa context中send方法已经存在,请注意');
53 else
54 context.send = sendHandler
55
56
57 function sendHandler(status,data){
58 if(arguments.length == 2){
59 context.status = status;
60 context.body = data
61
62 }
63 else if(arguments.length == 1){
64 context.body = status
65 }
66 }
67
68
69 /*ajax格式助手*/
70 if(context.errors)
71 console.error('koa context中errors方法已经存在,请注意');
72 else
73 context.errors = errorsHandler
74
75
76 function errorsHandler(status,error){
77 if(arguments.length == 1){
78 error = status
79 status = 422;
80 }
81 context.status = status;
82 context.body = {errors:error};
83 }
84
85
86
87}
\No newline at end of file