forked from koajs/joi-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjoi-router.js
451 lines (370 loc) · 9.59 KB
/
joi-router.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
'use strict';
var assert = require('assert');
var debug = require('debug')('koa-joi-router');
var isGenFn = require('is-gen-fn');
var flatten = require('flatten');
var methods = require('methods');
var KoaRouter = require('koa-router');
var busboy = require('co-busboy');
var parse = require('co-body');
var Joi = require('joi');
var slice = require('sliced');
var delegate = require('delegates');
var OutputValidator = require('./output-validator');
module.exports = Router;
// expose Joi for use in applications
Router.Joi = Joi;
function Router() {
if (!(this instanceof Router)) {
return new Router();
}
this.routes = [];
this.router = new KoaRouter();
}
/**
* Array of routes
*
* Router.prototype.routes;
* @api public
*/
/**
* Delegate methods to internal router object
*/
delegate(Router.prototype, 'router')
.method('prefix')
.method('use');
/**
* Return koa middleware
* @return {Function}
* @api public
*/
Router.prototype.middleware = function middleware() {
return this.router.routes();
};
/**
* Adds a route or array of routes to this router, storing the route
* in `this.routes`.
*
* Example:
*
* var admin = router();
*
* admin.route({
* method: 'get',
* path: '/do/stuff/:id',
* handler: function *(next){},
* validate: {
* header: Joi object
* params: Joi object (:id)
* query: Joi object (validate key/val pairs in the querystring)
* body: Joi object (the request payload body) (json or form)
* maxBody: '64kb' // (json, x-www-form-urlencoded only - not stream size)
* // optional
* type: 'json|form|multipart' (required when body is specified)
* failure: 400 // http error code to use
* },
* meta: { // this is ignored but useful for doc generators etc
* desc: 'We can use this for docs generation.'
* produces: ['application/json']
* model: {} // response object definition
* }
* })
*
* @param {Object} spec
* @return {Router} self
* @api public
*/
Router.prototype.route = function route(spec) {
if (Array.isArray(spec)) {
for (var i = 0; i < spec.length; i++) {
this._addRoute(spec[i]);
}
} else {
this._addRoute(spec);
}
return this;
};
/**
* Adds a route to this router, storing the route
* in `this.routes`.
*
* @param {Object} spec
* @api private
*/
Router.prototype._addRoute = function addRoute(spec) {
this._validateRouteSpec(spec);
this.routes.push(spec);
debug('add %s "%s"', spec.method, spec.path);
var bodyParser = makeBodyParser(spec);
var validator = makeValidator(spec);
var handlers = flatten(spec.handler);
var args = [
spec.path,
prepareRequest,
bodyParser,
validator
].concat(handlers);
var router = this.router;
spec.method.forEach(function(method) {
router[method].apply(router, args);
});
};
/**
* Validate the spec passed to route()
*
* @param {Object} spec
* @api private
*/
Router.prototype._validateRouteSpec = function validateRouteSpec(spec) {
assert(spec, 'missing spec');
var ok = typeof spec.path === 'string' || spec.path instanceof RegExp;
assert(ok, 'invalid route path');
checkHandler(spec);
checkMethods(spec);
checkValidators(spec);
};
/**
* @api private
*/
function checkHandler(spec) {
if (!Array.isArray(spec.handler)) {
spec.handler = [spec.handler];
}
return flatten(spec.handler).forEach(isGeneratorFunction);
}
/**
* @api private
*/
function isGeneratorFunction(handler) {
assert(isGenFn(handler), 'route handler must be a GeneratorFunction');
}
/**
* Validate the spec.method
*
* @param {Object} spec
* @api private
*/
function checkMethods(spec) {
assert(spec.method, 'missing route methods');
if (typeof spec.method === 'string') {
spec.method = spec.method.split(' ');
}
if (!Array.isArray(spec.method)) {
throw new TypeError('route methods must be an array or string');
}
if (spec.method.length === 0) {
throw new Error('missing route method');
}
spec.method.forEach(function(method, i) {
assert(typeof method === 'string', 'route method must be a string');
spec.method[i] = method.toLowerCase();
});
}
/**
* Validate the spec.validators
*
* @param {Object} spec
* @api private
*/
function checkValidators(spec) {
if (!spec.validate) return;
var text;
if (spec.validate.body) {
text = 'validate.type must be declared when using validate.body';
assert(/json|form/.test(spec.validate.type), text);
}
if (spec.validate.type) {
text = 'validate.type must be either json, form, multipart or stream';
assert(/json|form|multipart|stream/i.test(spec.validate.type), text);
}
if (spec.validate.output) {
spec.validate._outputValidator = new OutputValidator(spec.validate.output);
}
// default HTTP status code for failures
if (!spec.validate.failure) {
spec.validate.failure = 400;
}
}
/**
* Creates body parser middleware.
*
* @param {Object} spec
* @return {GeneratorFunction}
* @api private
*/
function makeBodyParser(spec) {
return function* parsePayload(next) {
if (!(spec.validate && spec.validate.type)) return yield* next;
var opts;
try {
switch (spec.validate.type) {
case 'json':
if (!this.request.is('json')) {
return this.throw(400, 'expected json');
}
opts = {
limit: spec.validate.maxBody
};
this.request.body = yield parse.json(this, opts);
break;
case 'form':
if (!this.request.is('urlencoded')) {
return this.throw(400, 'expected x-www-form-urlencoded');
}
opts = {
limit: spec.validate.maxBody
};
this.request.body = yield parse.form(this, opts);
break;
case 'stream':
case 'multipart':
if (!this.request.is('multipart/*')) {
return this.throw(400, 'expected multipart');
}
opts = spec.validate.multipartOptions || {}; // TODO document this
opts.autoFields = true;
this.request.parts = busboy(this, opts);
break;
}
} catch (err) {
if (!spec.validate.continueOnError) return this.throw(err);
captureError(this, 'type', err);
}
yield* next;
};
}
/**
* @api private
*/
function captureError(ctx, type, err) {
// expose Error message to JSON.stringify()
err.msg = err.message;
if (!ctx.invalid) ctx.invalid = {};
ctx.invalid[type] = err;
}
/**
* Creates validator middleware.
*
* @param {Object} spec
* @return {GeneratorFunction}
* @api private
*/
function makeValidator(spec) {
var props = 'header query params body'.split(' ');
return function* validator(next) {
var err;
if (!spec.validate) return yield* next;
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
if (spec.validate[prop]) {
err = validateInput(prop, this.request, spec.validate);
if (err) {
if (!spec.validate.continueOnError) return this.throw(err);
captureError(this, prop, err);
}
}
}
yield* next;
if (spec.validate._outputValidator) {
debug('validating output');
err = spec.validate._outputValidator.validate(this);
if (err) {
err.status = 500;
return this.throw(err);
}
}
};
}
/**
* Middleware which creates `request.params`.
*
* @api private
*/
function* prepareRequest(next) {
this.request.params = this.params;
yield* next;
}
/**
* Validates request[prop] data with the defined validation schema.
*
* @param {String} prop
* @param {koa.Request} request
* @param {Object} validate
* @returns {Error|undefined}
* @api private
*/
function validateInput(prop, request, validate) {
debug('validating %s', prop);
var res = Joi.validate(request[prop], validate[prop]);
if (res.error) {
res.error.status = validate.failure;
return res.error;
}
// update our request w/ the casted values
if (prop === 'header') {
// request.header is getter only, cannot set it
Object.keys(res.value).forEach(function(key) {
request.header[key] = res.value[key];
});
} else {
request[prop] = res.value;
}
}
/**
* Routing shortcuts for all HTTP methods
*
* Example:
*
* var admin = router();
*
* admin.get('/user', function *() {
* this.body = this.session.user;
* })
*
* var validator = Joi().object().keys({ name: Joi.string() });
* var config = { validate: { body: validator }};
*
* admin.post('/user', config, function *(){
* console.log(this.body);
* })
*
* function *commonHandler(){
* // ...
* }
* admin.post('/account', [commonHandler, function *(){
* // ...
* }]);
*
* @param {String} path
* @param {Object} [config] optional
* @param {GeneratorFunction|GeneratorFunction[]} handler(s)
* @return {App} self
*/
methods.forEach(function(method) {
method = method.toLowerCase();
Router.prototype[method] = function(path) {
// path, handler1, handler2, ...
// path, config, handler1
// path, config, handler1, handler2, ...
// path, config, [handler1, handler2], handler3, ...
var fns;
var config;
if (typeof arguments[1] === 'function' || Array.isArray(arguments[1])) {
config = {};
fns = slice(arguments, 1);
} else if (typeof arguments[1] === 'object') {
config = arguments[1];
fns = slice(arguments, 2);
}
var spec = {
path: path,
method: method,
handler: fns
};
Object.keys(config).forEach(function(key) {
spec[key] = config[key];
});
this.route(spec);
return this;
};
});