-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathRoute.js
545 lines (497 loc) · 17.8 KB
/
Route.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import KoaRouter from 'koa-router';
import chalk from 'chalk';
import { RateLimit } from 'koa2-ratelimit';
import ErrorApp from '../utils/ErrorApp';
import StatusCode from '../utils/StatusCode';
import { deepCopy, isArray } from '../utils/utils';
import { generateDoc } from '../utils/docGenerator';
import RouteDecorators from './RouteDecorators';
export default class Route {
/**
* @type {boolean}
* @desc if true it will log which route are mount and which are not
*/
static displayLog = true;
/**
* @type {StatusCode}
*/
static StatusCode = StatusCode;
/**
* @typedef {Object} BeforeRouteParams
* @property {string} path the path at which the route will be available.
* @property {ParamsMethodDecorator} options
* @property {function} call the fonction to call when route match, this is automaticaly add by route decorator
*/
/**
* @typedef {Object} RouteParams
* @property {Koa} koaApp the Koa application
* @property {string} prefix a prefix which will be preppended before every route's paths
* @property {Route[]} routes an array containing all the mounted Routes
* @property {Model[]} [models] an array containing all of the app's models
* @property {string} [model] the name of the route's own model
* @property {disable} [boolean] whether the route should be disabled
*
*/
/**
* @typedef {function} Decorator
* @return { }
*/
/**
* @external {KoaContext} http://koajs.com/#api
*/
/**
* @external {Koa} http://koajs.com/#application
*/
/**
* @param {RouteParams} params the route's parameters
*/
constructor({ koaApp, prefix, routes, models, model, disable }) {
/**
* @type {Koa}
* @desc the main Koa application
*/
this.koaApp = koaApp;
/**
* @type {string}
* @desc the route's prefix
*/
this.prefix = prefix;
/**
* @type {Route[]}
* @desc an array composed of all the availble routes in the application
*/
this.allRoutesInstance = routes;
/**
* @type {Model[]}
* @desc an array of all the models available in the application
*/
this.models = models;
/**
* @type {boolean}
* @desc whether the route should be disabled. disabled routes cannot be called.
*/
this.disable = disable != null ? disable : this.disable;
/**
* @type {function[]}
* @desc the route's registered middlewares
*/
this.middlewares = this.middlewares || [];
if (this.models && model) {
/**
* @type {Model|undefined}
* @desc the route's own model
*/
this.model = this.models[model];
}
/**
* @type {KoaRouter}
* @desc the underlying koa router for this particular route
*/
this.koaRouter = new KoaRouter();
// This Variable are set by RouteDecorators
this.routes;
this.routeBase;
}
/**
* @access public
* @desc mounts the tagged function as a GET route.
* @param {ParamsMethodDecorator} params the route's parameters
* @return {Decorator}
*/
static WebSocket = RouteDecorators.WebSocket;
/**
* @access public
* @desc mounts the tagged function as a GET route.
* @param {ParamsMethodDecorator} params the route's parameters
* @return {Decorator}
*/
static Get = RouteDecorators.Get;
/**
* @access public
* @desc mounts the tagged function as a POST route.
* @param {ParamsMethodDecorator} params the route's parameters
* @return {Decorator}
*/
static Post = RouteDecorators.Post;
/**
* @access public
* @desc mounts the tagged function as a PUT route.
* @param {ParamsMethodDecorator} params the route's parameters
* @return {Decorator}
*/
static Put = RouteDecorators.Put;
/**
* @access public
* @desc mounts the tagged function as a PATCH route.
* @param {ParamsMethodDecorator} params the route's parameters
* @return {Decorator}
*/
static Patch = RouteDecorators.Patch;
/**
* @access public
* @desc mounts the tagged function as a DELETE route.
* @param {ParamsMethodDecorator} params the route's parameters
* @return {Decorator}
*/
static Delete = RouteDecorators.Delete;
/**
* @access public
* @desc used to set some parameters on an entire class.The supported parameters are middlewares, disable, and routeBase.
* @return {Decorator}
* @param {ParamsClassDecorator} params the route's parameters
*/
static Route = RouteDecorators.Route;
/**
* logs a message, but only if the route's logs are set to be displayed.
*
* accepts several parameters
*/
log(str, ...args) {
if (Route.displayLog) {
// eslint-disable-next-line
console.log(str, ...args);
}
}
/**
* @access public
* @desc Registers the route and makes it callable once the API is launched.
* the route will be called along with the middlewares that were registered in the decorator.
*
* you will usually not need to call this method yourself.
*/
mount() {
if (this.disable !== true) {
for (const type in this.routes) {
// eslint-disable-line
for (const route of this.routes[type]) {
const routePath = `/${this.prefix}/${this.routeBase}/${route.path}`
.replace(/[/]{2,10}/g, '/')
.replace(/[/]$/, '');
if (!route.options.disable) {
this.log(chalk.green.bold('[Mount route]'), `\t${type}\t`, routePath);
if (type === 'websocket') {
this.webSocketRouter = (ctx) => {
if (ctx.path === routePath)
ctx.websocket.on(route.options.eventName, route.call);
};
} else {
this.koaRouter[type](routePath, ...this._use(route));
}
generateDoc(this, route);
} else {
this.log(chalk.yellow.bold('[Disable Mount route]\t'), type, routePath);
}
}
}
} else {
this.log(chalk.yellow.bold(`Routes "${this.routeBase}" of class ${this.constructor.name} are't add`));
}
}
// ************************************ MIDDLEWARE *********************************
/**
*@ignore
*/
_use(infos) {
const { options = {} } = infos;
const { middlewares = [] } = options;
const middlewaresToAdd = [this._beforeRoute(infos)];
middlewaresToAdd.push(...this.middlewares); // add middlewares of the class
middlewaresToAdd.push(...middlewares); // add middlewares of the specific route
this.addRateLimit(middlewaresToAdd, infos);
middlewaresToAdd.push(infos.call.bind(this));
return middlewaresToAdd;
}
/**
*@ignore
*/
getRateLimit(option, routePath, type) {
option.interval = RateLimit.RateLimit.timeToMs(option.interval);
return RateLimit.middleware({
prefixKey: `${type}|${routePath}|${option.interval}`,
...option,
});
}
/**
* if a decorator has a rateLimit property, it will add the rate limiting mechanism to the route,
* with a unique ID for each route in order to differentiate the various routes.
*
* You should not need to call this method directly.
* @param {function[]} middlewares the array of currently registered middlewares for the given route
* @param {{options:{rateLimit:Object,routePath:string,type:string}}} params the route's parameters
*/
addRateLimit(middlewares, { options }) {
const { rateLimit, routePath, type } = options;
if (rateLimit) {
if (isArray(rateLimit)) {
for (const elem of rateLimit) {
middlewares.push(this.getRateLimit(elem, routePath, type));
}
} else {
middlewares.push(this.getRateLimit(rateLimit, routePath, type));
}
}
}
// beforeRoute
/**
*@ignore
*/
_beforeRoute(infos) {
return async (ctx, next) => await this.beforeRoute(ctx, infos, next);
}
/**
* @desc a member which can be overriden, which will always be executed before the route is accessed
* @param {KoaContext} ctx Koa's context object
* @param {BeforeRouteParams} params an object containing all route parameters
* @param {function} next the next middleware in the chain
*/
async beforeRoute(ctx, { options }, next) {
await this._mlTestAccess(ctx, options);
this._mlParams(ctx, options);
if (next) {
await next();
}
}
/**
*@ignore
*/
async _mlTestAccess(ctx, { accesses }) {
if (isArray(accesses) && accesses.length) {
for (const access of accesses) {
if (await access(ctx)) return true;
}
this.throwForbidden(null, true);
}
if (isArray(this.accesses) && this.accesses.length) {
for (const access of this.accesses) {
if (await access(ctx)) return true;
}
this.throwForbidden(null, true);
}
return true;
}
/**
*@ignore
*/
_mlParams(ctx, { bodyType, queryType }) {
if (bodyType) {
ctx.request.bodyOrigin = deepCopy(ctx.request.body);
ctx.request.bodyChanged = this._mlTestParams(ctx, ctx.request.body, bodyType);
ctx.request.body = ctx.request.bodyChanged;
}
if (queryType) {
ctx.request.queryOrigin = deepCopy(ctx.request.query || {});
ctx.request.queryChanged = this._mlTestParams(ctx, ctx.request.query, queryType);
ctx.request.query = ctx.request.queryChanged;
}
}
/**
*@ignore
*/
_mlTestParams(ctx, body, type) {
const cloneType = type.clone();
if (ctx.i18n) cloneType.setLocale(ctx.i18n.getLocale());
cloneType.test(body);
if (cloneType.error || cloneType.errors) {
this.throwBadRequest(cloneType.errors || cloneType.error);
}
return cloneType.value;
}
// ************************************ !MIDDLEWARE *********************************
/**
*@desc retrieves the context's body, if the request has one.
*@param {KoaContext} ctx koa's context object
*@param {boolean} [original=false] if set to true, the function will return the body before it is filtered by the param decorator.
* otherwise, it will return the filtered and transformed body.
*/
body(ctx, original = false) {
return original ? ctx.request.bodyOrigin : ctx.request.bodyChanged;
}
/**
* @access public
* @desc retrieves the query params in a GET request
* @param {KoaContext} ctx koa's context object
* @return {Object.<string, *>}
*/
queryParam(ctx, original = false) {
return original ? ctx.request.queryOrigin : ctx.request.queryChanged;
}
/**
* @access public
* @desc sets the response's body (with a message + data field) and status.
* @param {KoaContext} ctx koa's context object
* @param {number} [status] the HTTP status code to end the request with
* @param {*} [data] the data to be yielded by the requests
* @param {string} [message] the message to be yielded by the request
* @return { }
*/
send(ctx, status = 200, data, message) {
ctx.body = ctx.body || {}; // add default body
ctx.status = status;
// Do not remove this test because if status = 204 || 304, node will remove body
// see _hasBody on
// https://github.com/nodejs/node/blob/master/lib/_http_server.js#L235-L250
if (ctx.body) {
if (data != null) {
ctx.body.data = data;
}
if (message != null) {
ctx.body.message = message;
}
ctx.body.date = Date.now();
}
}
/**
* @access public
* @desc same as {@link send}, but automatically sets the status to 200 OK
* @param {KoaContext} ctx koa's context object
* @param {*} [data] the data to be yielded by the requests
* @param {string} [message] the message to be yielded by the request
* @return { }
*/
sendOk(ctx, data, message) {
return this.send(ctx, Route.StatusCode.ok, data, message);
}
/**
* @access public
* @desc same as {@link send}, but automatically sets the status to 201 CREATED
* @param {KoaContext} ctx koa's context object
* @param {*} [data] the data to be yielded by the requests
* @param {string} [message] the message to be yielded by the request
* @return { }
*/
sendCreated(ctx, data, message) {
return this.send(ctx, Route.StatusCode.created, data, message);
}
/**
* @access public
* @desc replies with an empty body, yielding 204 NO CONTENT as the status
* @param {KoaContext} ctx koa's context object
* @return { }
*/
sendNoContent(ctx) {
return this.send(ctx, Route.StatusCode.noContent);
}
/**
* @access public
* @desc throws a formated error to be caught.
* @param {number} status the error's HTTP status StatusCode
* @param {string | object} [error] the error(s) to be yielded by the request
* @param {boolean} translate indicates whether the message should be translated or not
* @throws {ErrorApp} thrown error.
* @return { }
*/
throw(status, error, translate = false) {
throw new ErrorApp(status, error, translate);
}
/**
* @access public
* @version 2.0.0
* @desc same as {@link throw}, but automatically sets the status to 400 BAD REQUEST
* @param {string | object} [error] the error(s) to be yielded by the request, default to "Bad request"
* @param {boolean} translate indicates whether the message should be translated or not
* @return { }
*/
throwBadRequest(error, translate = false) {
return this.throw(Route.StatusCode.badRequest, error || 'Bad request', translate);
}
/**
* @access public
* @version 2.0.0
* @desc same as {@link throw}, but automatically sets the status to 401 UNAUTHORIZED
* @param {string | object} [error] the error(s) to be yielded by the request, default to "Unauthorized"
* @param {boolean} translate indicates whether the message should be translated or not
* @return { }
*/
throwUnauthorized(error, translate = false) {
return this.throw(Route.StatusCode.unauthorized, error || 'Unauthorized', translate);
}
/**
* @access public
* @version 2.0.0
* @desc same as {@link throw}, but automatically sets the status to 403 FORBIDDEN
* @param {string | object} [error] the error(s) to be yielded by the request, default to "Forbidden"
* @param {boolean} translate indicates whether the message should be translated or not
* @return { }
*/
throwForbidden(error, translate = false) {
return this.throw(Route.StatusCode.forbidden, error || 'Forbidden', translate);
}
/**
* @access public
* @version 2.0.0
* @desc same as {@link throw}, but automatically sets the status to 404 NOT FOUND
* @param {string | object} [error] the error(s) to be yielded by the request, default to "Not found"
* @param {boolean} translate indicates whether the message should be translated or not
* @return { }
*/
throwNotFound(error, translate = false) {
return this.throw(Route.StatusCode.notFound, error || 'Not found', translate);
}
/**
* @access public
* @desc checks a condition. If it evaluates to false, throws a formated error to be caught.
* @param {boolean} condition if set to false; assert will fail and throw.
* @param {number} status the error's HTTP status StatusCode
* @param {string | object} [error] the error(s) to be yielded by the request
* @param {boolean} translate indicates whether the message should be translated or not
* @throws {ErrorApp} thrown error, should the assert fail.
* @return { }
*/
assert(condition, status, error, translate = false) {
if (!condition) {
this.throw(status, error, translate);
}
}
/**
* @access public
* @version 2.0.0
* @desc same as {@link assert}, but automatically sets the status to 400 BAD REQUEST
* @param {boolean} condition if set to false; assert will fail and throw.
* @param {string | object} [error] the error(s) to be yielded by the request, default to "Bad request"
* @param {boolean} translate indicates whether the message should be translated or not
* @throws {ErrorApp} thrown error, should the assert fail.
* @return { }
*/
assertBadRequest(condition, error, translate = false) {
this.assert(condition, Route.StatusCode.badRequest, error || 'Bad request', translate);
}
/**
* @access public
* @version 2.0.0
* @desc same as {@link assert}, but automatically sets the status to 401 UNAUTHORIZED
* @param {boolean} condition if set to false; assert will fail and throw.
* @param {string | object} [error] the error(s) to be yielded by the request, default to "Unauthorized"
* @param {boolean} translate indicates whether the message should be translated or not
* @throws {ErrorApp} thrown error, should the assert fail.
* @return { }
*/
assertUnauthorized(condition, error, translate = false) {
this.assert(condition, Route.StatusCode.unauthorized, error || 'Unauthorized', translate);
}
/**
* @access public
* @version 2.0.0
* @desc same as {@link assert}, but automatically sets the status to 403 FORBIDDEN
* @param {boolean} condition if set to false; assert will fail and throw.
* @param {string | object} [error] the error(s) to be yielded by the request, default to "Forbidden"
* @param {boolean} translate indicates whether the message should be translated or not
* @throws {ErrorApp} thrown error, should the assert fail.
* @return { }
*/
assertForbidden(condition, error, translate = false) {
this.assert(condition, Route.StatusCode.forbidden, error || 'Forbidden', translate);
}
/**
* @access public
* @version 2.0.0
* @desc same as {@link assert}, but automatically sets the status to 400 BAD REQUEST
* @param {boolean} condition if set to false; assert will fail and throw.
* @param {string | object} [error] the error(s) to be yielded by the request, default to "Not found"
* @param {boolean} translate indicates whether the message should be translated or not
* @throws {ErrorApp} thrown error, should the assert fail.
* @return { }
*/
assertNotFound(condition, error, translate = false) {
this.assert(condition, Route.StatusCode.notFound, error || 'Not found', translate);
}
}