-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparam-decorators.ts
506 lines (445 loc) · 14.8 KB
/
param-decorators.ts
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
import * as express from 'express'
import * as core from 'express-serve-static-core'
import { RequestHeader } from '@reflet/http'
import { ClassType } from './interfaces'
import { RefletExpressError } from './reflet-error'
import { getOwnMetadata, defineMetadata } from './metadata-map'
const METAKEY_PARAM = Symbol('param')
/**
* Injects Request object in the method's parameters.
* @see https://expressjs.com/en/4x/api.html#req
* @example
* ```ts
* // Without invokation:
* @Get('/some')
* get(@Req req: Req) {}
*
* // With invokation:
* @Post('/some')
* create(@Req() req: Req) {}
* ```
* ------
* @public
*/
export function Req(): Req.Decorator
export function Req(...args: Parameters<Req.Decorator>): void
export function Req() {
if (arguments.length === 3 && typeof arguments[2] === 'number') {
return (createParamDecorator((req) => req) as Function)(...arguments)
} else {
return createParamDecorator((req) => req)
}
}
export type Req<
P = core.ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = core.Query,
Locals extends Record<string, any> = Record<string, any>
> = express.Request<P, ResBody, ReqBody, ReqQuery, Locals>
export namespace Req {
/**
* Equivalent to `ParameterDecorator`.
* @public
*/
export type Decorator = ParameterDecorator & { __expressReq?: never; __expressHandlerParameter?: never }
}
/**
* Inject Response object in the method's parameters.
* @see https://expressjs.com/en/4x/api.html#res
* @example
* ```ts
* // Without invokation:
* @Get('/some')
* get(@Res res: Res) {}
*
* // With invokation:
* @Post('/some')
* create(@Res() res: Res) {}
* ```
* ------
* @public
*/
export function Res(): Res.Decorator
export function Res(...args: Parameters<Res.Decorator>): void
export function Res() {
if (arguments.length === 3 && typeof arguments[2] === 'number') {
return (createParamDecorator((req, res: express.Response) => res) as Function)(...arguments)
} else {
return createParamDecorator((req, res: express.Response) => res)
}
}
export type Res<ResBody = any, Locals extends Record<string, any> = Record<string, any>> = express.Response<
ResBody,
Locals
>
export namespace Res {
/**
* Equivalent to `ParameterDecorator`.
* @public
*/
export type Decorator = ParameterDecorator & { __expressRes?: never; __expressHandlerParameter?: never }
}
/**
* Injects `next` callback function in the method's parameters.
* @see https://expressjs.com/en/guide/writing-middleware.html
* @example
* ```ts
* // Without invokation:
* @Get('/some')
* get(@Next next: Next) {}
*
* // With invokation:
* @Post('/some')
* create(@Next() next: Next) {}
* ```
* ------
* @public
*/
export function Next(): Next.Decorator
export function Next(...args: Parameters<Next.Decorator>): void
export function Next() {
if (arguments.length === 3 && typeof arguments[2] === 'number') {
// next is not defined in the public method signature, but is still used later
// by the route params extractor so we must pass it as optional for the compiler
return (createParamDecorator((req, res, next?: express.NextFunction) => next!) as Function)(...arguments)
} else {
return createParamDecorator((req, res, next?: express.NextFunction) => next!)
}
}
export type Next = express.NextFunction
export namespace Next {
/**
* Equivalent to `ParameterDecorator`.
* @public
*/
export type Decorator = ParameterDecorator & { __expressNext?: never; __expressHandlerParameter?: never }
}
/** default parser middlewares to apply with @Body decorator */
const bodyParsers: createParamDecorator.Middleware[] = [
{ handler: express.json(), dedupe: true },
{ handler: express.urlencoded({ extended: true }), dedupe: true },
]
/**
* Injects request body in the method's parameters.
* @param key - directly injects a body property.
* @see https://expressjs.com/en/4x/api.html#req.body
* @example
* ```ts
* // Whole body without invokation:
* @Post('/some')
* create(@Body body: object) {}
*
* // Whole body with invokation:
* @Put('/some')
* replace(@Body() body: object) {}
*
* // Sub property:
* @Patch('/some')
* update(@Body<User>('email') email: string) {}
* ```
* ------
* @public
*/
export function Body<T extends object>(key?: keyof T): Body.Decorator
// todo: https://codewithstyle.info/Deep-property-access-in-TypeScript/
export function Body(...args: Parameters<Body.Decorator>): void
export function Body<T extends object>(
keyOrTarget?: keyof T | object,
propertyKey?: string | symbol,
parameterIndex?: number
) {
if (arguments.length === 3 && typeof keyOrTarget === 'object') {
const target = keyOrTarget
return createParamDecorator((req) => req.body, bodyParsers)(target, propertyKey!, parameterIndex!)
} else {
const subKey = keyOrTarget as keyof T | undefined
return createParamDecorator((req) => (subKey ? req.body[subKey] : req.body), bodyParsers)
}
}
export namespace Body {
/**
* Equivalent to `ParameterDecorator`.
* @public
*/
export type Decorator = ParameterDecorator & { __expressBody?: never; __expressHandlerParameter?: never }
}
/**
* Injects named route parameters in the method's parameters.
* @param name - directly injects a single route parameter.
* @see https://expressjs.com/en/4x/api.html#req.params
* @example
* ```ts
* // Route parameters object without invokation:
* @Get('/:col/:id')
* get(@Params params: Params<'col' | 'id'>) {}
*
* // Route parameters object with invokation:
* @Get('/:col/:id')
* get(@Params() params: Params<'col' | 'id'>) {}
*
* // Single route parameter:
* @Get('/:col/:id')
* get(@Params('col') col: string, @Params('id') id: string) {}
* ```
* ------
* @public
*/
export function Params(name?: string): Params.Decorator
export function Params(...args: Parameters<Params.Decorator>): void
export function Params(nameOrTarget?: string | object, propertyKey?: string | symbol, parameterIndex?: number) {
if (arguments.length === 3 && typeof nameOrTarget === 'object') {
const target = nameOrTarget
return createParamDecorator((req) => req.params)(target, propertyKey!, parameterIndex!)
} else {
const subKey = nameOrTarget as string | undefined
return createParamDecorator((req) => (subKey ? req.params[subKey] : req.params))
}
}
export type Params<P extends string = string> = Record<P, string>
export namespace Params {
/**
* Equivalent to `ParameterDecorator`.
* @public
*/
export type Decorator = ParameterDecorator & { __expressParams?: never; __expressHandlerParameter?: never }
}
/**
* Injects query string parameters in the method's parameters.
* @param field - directly injects a value.
* @see https://expressjs.com/en/4x/api.html#req.query
* @example
* ```ts
* // Query string parameters object without invokation:
* @Get('/search')
* search(@Query query: Query) {}
*
* // Query string parameters object with invokation:
* @Get('/search')
* search(@Query() query: Query) {}
*
* // Single query string parameter:
* @Get('/search')
* search(@Query('name') name: string, @Query('sort') sort: string) {}
* ```
* ------
* @public
*/
export function Query(field?: string): Query.Decorator
export function Query(...args: Parameters<Query.Decorator>): void
export function Query(fieldOrTarget?: string | object, propertyKey?: string | symbol, parameterIndex?: number) {
if (arguments.length === 3 && typeof fieldOrTarget === 'object') {
const target = fieldOrTarget
return createParamDecorator((req) => req.query)(target, propertyKey!, parameterIndex!)
} else {
const subKey = fieldOrTarget as string | undefined
return createParamDecorator((req) => (subKey ? req.query[subKey] : req.query))
}
}
export type Query = { [key: string]: undefined | string | string[] | Query | Query[] }
export namespace Query {
/**
* Equivalent to `ParameterDecorator`.
* @public
*/
export type Decorator = ParameterDecorator & { __expressQuery?: never; __expressHandlerParameter?: never }
}
/**
* Injects request headers object in the method's parameters.
* @param headerName - directly injects a specific header.
* @see https://nodejs.org/api/http.html#http_message_headers
* @example
* ```ts
* // Request headers object without invokation:
* @Get('/some')
* get(@Headers headers: Headers) {}
*
* // Request headers object with invokation:
* @Get('/some')
* get(@Headers() headers: Headers) {}
*
* // Single request header:
* @Get('/some')
* get(@Headers('user-agent') userAgent: string) {}
* ```
* ------
* @public
*/
export function Headers(headerName?: RequestHeader): Headers.Decorator
export function Headers(...args: Parameters<Headers.Decorator>): void
export function Headers(nameOrTarget?: string | object, propertyKey?: string | symbol, parameterIndex?: number) {
if (arguments.length === 3 && typeof nameOrTarget === 'object') {
const target = nameOrTarget
return createParamDecorator((req) => req.headers)(target, propertyKey!, parameterIndex!)
} else {
const subKey = nameOrTarget as string | undefined
return createParamDecorator((req) => (subKey ? req.headers[subKey] : req.headers))
}
}
export type Headers = RequestHeader.Record
export namespace Headers {
/**
* Equivalent to `ParameterDecorator`.
* @public
*/
export type Decorator = ParameterDecorator & { __expressHeaders?: never; __expressHandlerParameter?: never }
}
/**
* Creates a parameter decorator, to inject anything we want in decorated routes.
*
* @param mapper - function that should return the thing we want to inject from the Request object.
* @param use - adds middlewares to the route if the mapper needs them (_e.g. we need body-parser middlewares to retrieve `req.body`_). You can pass options to deduplicate middlewares based on the handler function reference or name (_e.g. if 'jsonParser' is already in use locally or globally, it won't be added again_).
*
* @remarks
* We can create decorators with or without options.
* Simple decorators without options are applied without being invoked.
*
* ------
* @example
* ```ts
* // Simple decorator:
* const CurrentUser = createParamDecorator((req) => req.user)
* class Foo {
* @Get('/me')
* get(@CurrentUser user: User) {}
* }
* ```
* ------
* @example
* ```ts
* // Advanced decorator (with option and middleware):
* const BodyTrimmed = (key: string) => createParamDecorator(
* (req) => req.body[key].trim(),
* [{ handler: express.json(), dedupe: true }]
* )
* class Foo {
* @Post('/message')
* create(@BodyTrimmed('text') text: string) {}
* }
* ```
* ------
* @public
*/
export function createParamDecorator<T = any>(
mapper: (req: express.Request, res: express.Response) => T,
use?: createParamDecorator.Middleware[]
): createParamDecorator.Decorator {
return (target, key, index) => {
const params: createParamDecorator.Options[] = getOwnMetadata(METAKEY_PARAM, target, key!) || []
if (params[index]) {
const codePath = `${target.constructor.name}.${String(key)}`
throw new RefletExpressError(
'MULTIPLE_PARAMETER_DECORATORS',
`Parameter ${index} of "${codePath}" should have a single express decorator.`
)
}
params[index] = { mapper, use }
defineMetadata(METAKEY_PARAM, params, target, key!)
}
}
export namespace createParamDecorator {
/**
* @public
*/
export type Options = {
readonly mapper: (req: express.Request, res: express.Response, next?: express.NextFunction) => any
readonly use?: Middleware[]
}
/**
* @public
*/
export type Middleware =
| express.RequestHandler
| { handler: express.RequestHandler; dedupe?: boolean | 'by-name' | 'by-reference' }
/**
* Equivalent to `ParameterDecorator`.
* @public
*/
export type Decorator = ParameterDecorator & { __expressHandlerParameter?: never }
}
/**
* Used to intercept a decorated handler execution and extract the Request, Response, Next,
* or Request properties, by applying the mapper defined in the metadata.
*
* @internal
*/
export function extractParams(
target: ClassType,
key: string | symbol,
{ req, res, next }: { req: express.Request; res: express.Response; next: express.NextFunction }
): any[] {
const params: createParamDecorator.Options[] = getOwnMetadata(METAKEY_PARAM, target.prototype, key) || []
// No decorator found in the method: simply return the original arguments in the original order
if (!params.length) return [req, res, next]
const args: any[] = []
for (let index = 0; index < params.length; index++) {
const { mapper } = params[index]
args[index] = mapper(req, res, next)
}
return args
}
/**
* Retrieve added middlewares to use custom param decorator.
*
* Dedupe/remove middlewares if they're already applied on method or class,
* by comparing by references and function names (used to compare function bodies,
* but could not distinguish functions wrapped in a higher order one).
*
* Extracted separately from the mapper, because middlewares are applied on route registering,
* and the mapper is applied later inside a closure on route handling.
*
* @internal
*/
export function extractParamsMiddlewares(
target: ClassType,
key: string | symbol,
alreadyMwares: express.RequestHandler[][]
): express.RequestHandler[] {
const params: createParamDecorator.Options[] = getOwnMetadata(METAKEY_PARAM, target.prototype, key) || []
if (!params.length) return []
const paramMwares: express.RequestHandler[] = []
let alreadyNames: string[] = []
for (const { use } of params) {
if (!use) continue
for (const mware of use) {
if (typeof mware === 'function') {
// If the same param decorator is used twice, we prevent adding its middlewares twice
// whether or not it's marked for dedupe, to do that we simply compare by reference.
if (paramMwares.includes(mware)) {
continue
}
paramMwares.push(mware)
} else {
if (paramMwares.includes(mware.handler)) {
continue
}
// Dedupe middlewares in upper layers.
if (mware.dedupe === true || mware.dedupe === 'by-reference') {
const sameRef = alreadyMwares.some((alreadyMware) => alreadyMware.includes(mware.handler))
// console.log('dedupe-by-reference:', mware.handler.name, sameRef)
if (sameRef) {
continue
}
}
if (mware.dedupe === true || mware.dedupe === 'by-name') {
// Perform the flatmap only if one of the parameter requires deduplication by name.
if (!alreadyNames.length) {
alreadyNames = alreadyMwares.flat().map((m) => m.name)
}
const sameName = !!mware.handler.name && alreadyNames.includes(mware.handler.name)
// console.log('dedupe-by-name:', mware.handler.name, sameName)
if (sameName) {
continue
}
}
paramMwares.push(mware.handler)
}
// todo?: alreadyNames.push(mware.name)
// Should we dedupe by *name* the same middleware on different param decorators ?
// Or should we just warn the user of a potential conflict, and suggest to move
// the middleware to an explicit place on the router as an easy fix ?
// See 'param middlewares deduplication' tests.
}
}
return paramMwares
}