-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsurface.js
253 lines (218 loc) · 5.58 KB
/
surface.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/**
* Surface
* Copyright 2014 Zed Gu
* License: MIT
*/
'use strict';
/**
* Dependencies
*/
var path = require('path');
var util = require('util');
var Kow = require('koa-ovenware');
var debug = require('debug')('surface:debug');
var render = require('./render');
var context = require('./context');
/**
* Global
*/
var defaultSetting = {
root: './lib',
prefix: false,
prefixPattern: /^\/api\/v?\d{1,3}(\.\d{1,3}){0,2}/i,
ctrl: 'controllers',
model: 'models',
format: 'json',
nosniff: true,
authenticate: false,
options: 'Accept,Content-Type',
origin: '*',
routes: {
'index': {
method: 'get',
path: ''
},
'create': {
method: 'post',
path: ''
},
'get': {
method: 'get',
path: '/:id'
},
'update': {
method: 'put',
path: '/:id'
},
'del': {
method: 'delete',
path: '/:id'
}
},
aliases: {
'index': ''
},
fields: {
path: 'request',
status: 'code',
message: 'msg',
data: 'data'
}
};
/**
* Expose
*/
module.exports = Surface;
/**
* Surface Constructor.
* @param {Object} app koa().
* @param {Object} options Config object.
* @api public
*/
function Surface(app, options) {
if (!(this instanceof Surface)) {
return new Surface(app, options);
}
this.conf = setting(options);
this.middleware(app);
context(app, this);
}
var surface = Surface.prototype;
surface.load = function(app, options) {
var kp = Kow.prototype;
var conf = this.conf;
kp.preprocess = function(fn, path) {
function *authFn(next) {
if (yield conf.authenticate.bind(this)()) {
yield fn.bind(this)();
} else {
yield conf.deny.bind(this)();
}
yield next;
}
function *Fn(next) {
yield fn.bind(this)();
yield next;
}
if (conf.authenticate) {
if (conf.authenticatePattern && !conf.authenticatePattern.test(path)) {
return Fn;
}
return authFn;
}
return Fn;
};
var kow = Kow(app, options);
this.kow = kow;
this.ctrls = kow.ctrls;
this.models = kow.models;
};
/**
* middleware of Surface
* @return {Generator} middleware for koa
*/
surface.middleware = function(app) {
var conf = this.conf;
var fields = conf.fields;
app.use(function() {
if (conf.options) {
return function *SurfaceOPTIONS(next) {
yield *next;
if (this.method === 'OPTIONS') {
this.set('Access-Control-Allow-Methods', this.res.getHeader('Allow') + ', OPTIONS');
this.set('Access-Control-Allow-Headers', conf.options);
this.remove('Allow');
}
};
} else {
return function *SurfaceOPTIONS(next) {
yield *next;
if (this.method === 'OPTIONS') {
this.remove('Allow');
this.status = 404;
}
};
}
}());
if (conf.nosniff) {
app.use(function *SurfaceNosniff(next) {
yield *next;
this.set('X-Content-Type-Options', 'nosniff');
});
}
if (conf.origin) {
app.use(function *SurfaceOrigin(next) {
yield *next;
this.set('Access-Control-Allow-Origin', conf.origin);
});
}
this.load(app, this.conf);
var router = this.kow.router || app.router;
// app.router for koa-router 4.x
// this.kow.router for koa-router 5.x
if (router.allowedMethods) {
app.use(router.allowedMethods());
}
app.use(function *Surface(next) {
yield next;
if (this.skip_surface) {
debug('%s : \nNot format by Surface via skip API', this.path);
return;
}
if (conf.prefix && !conf.prefixPattern.test(this.path)) {
debug('%s : \nNot format by Surface via prefix setting: %s', this.url, conf.prefixPattern);
return;
}
var status = this.res.statusCode;
if (status === 204 || status === 205 || status === 304) {
return;
}
/**
* ctx.toJSON().response.string for <= [email protected],
* see https://github.com/koajs/koa/pull/353
* and https://github.com/koajs/koa/commit/eb443d1bee748b3429d5308757573ec083e7e899#diff-d86a59ede7d999db4b7bc43cb25a1c11R477
*/
var msg = this.res.statusMessage || this.toJSON().response.string || this.toJSON().response.message;
var format = render.checkFormat.bind(this)(conf.format);
this.body = render.format(format, this.path, status, msg, this.body, fields);
this.type = format;
this.res.statusCode = status;
});
};
/**
* Set conf
* @param {Object} options Options objest
* @return {Object} Formated conf object
* @api private
*/
function setting(options) {
var conf = {};
if (options === null || typeof options !== 'object') {
options = {};
}
for (var key in defaultSetting) {
conf[key] = options[key] === undefined ? defaultSetting[key] : options[key];
}
conf.format = defaultFormat(['json', 'xml'].indexOf(conf.format.toLowerCase()));
var prefix = conf.prefix;
if ((typeof prefix === 'string' || util.isRegExp(prefix)) && !options.prefixPattern) {
conf.prefixPattern = util.isRegExp(prefix) ? prefix : new RegExp(prefix);
}
if (conf.authenticate) {
conf.deny = options.deny;
conf.authenticatePattern = options.authenticatePattern || conf.prefixPattern;
if (conf.authenticate.constructor.name !== 'GeneratorFunction') {
console.error('authenticate should be a GeneratorFunction');
conf.authenticate = false;
}
if (conf.deny.constructor.name !== 'GeneratorFunction') {
console.error('deny should be a GeneratorFunction');
}
}
return conf;
}
function defaultFormat(index) {
var d = [['json', 'xml'], ['xml', 'json']];
index = index === -1 ? 0 : index;
return d[index];
}