@catbee/utils 0.0.3 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +693 -245
- package/build/esm/config.d.ts +18 -7
- package/build/esm/config.js +23 -7
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +2 -0
- package/build/esm/index.js +2 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/utils/cache.utils.js +16 -16
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +1 -1
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +3 -2
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +292 -17
- package/build/esm/utils/decorators.utils.js +372 -40
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +186 -23
- package/build/esm/utils/env.utils.js +494 -91
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.js +1 -1
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +107 -0
- package/build/esm/utils/logger.utils.js +210 -19
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +42 -34
- package/build/esm/utils/middleware.utils.js +88 -51
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/request.utils.d.ts +77 -0
- package/build/esm/utils/request.utils.js +173 -0
- package/build/esm/utils/request.utils.js.map +1 -0
- package/build/esm/utils/response.utils.js +4 -4
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esnext/config.d.ts +18 -7
- package/build/esnext/config.js +23 -7
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +2 -0
- package/build/esnext/index.js +2 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +16 -16
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +1 -1
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +3 -2
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +292 -17
- package/build/esnext/utils/decorators.utils.js +348 -21
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +186 -23
- package/build/esnext/utils/env.utils.js +445 -77
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.js +1 -1
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +107 -0
- package/build/esnext/utils/logger.utils.js +181 -19
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +42 -34
- package/build/esnext/utils/middleware.utils.js +86 -51
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/request.utils.d.ts +77 -0
- package/build/esnext/utils/request.utils.js +145 -0
- package/build/esnext/utils/request.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.js +4 -4
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/src/config.d.ts +18 -7
- package/build/src/config.js +26 -8
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +2 -0
- package/build/src/index.js +5 -0
- package/build/src/index.js.map +1 -1
- package/build/src/utils/cache.utils.js +15 -15
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +1 -1
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +2 -1
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +292 -17
- package/build/src/utils/decorators.utils.js +350 -21
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +186 -23
- package/build/src/utils/env.utils.js +444 -76
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.js +1 -1
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +107 -0
- package/build/src/utils/logger.utils.js +187 -19
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +42 -34
- package/build/src/utils/middleware.utils.js +86 -50
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/request.utils.d.ts +77 -0
- package/build/src/utils/request.utils.js +152 -0
- package/build/src/utils/request.utils.js.map +1 -0
- package/build/src/utils/response.utils.js +4 -4
- package/build/src/utils/response.utils.js.map +1 -1
- package/package.json +11 -6
|
@@ -8,13 +8,28 @@ exports.HttpCode = HttpCode;
|
|
|
8
8
|
exports.Header = Header;
|
|
9
9
|
exports.Before = Before;
|
|
10
10
|
exports.After = After;
|
|
11
|
+
exports.Roles = Roles;
|
|
12
|
+
exports.Redirect = Redirect;
|
|
11
13
|
exports.registerControllers = registerControllers;
|
|
12
14
|
require("reflect-metadata");
|
|
13
|
-
|
|
15
|
+
const http_status_codes_1 = require("./http-status-codes");
|
|
16
|
+
const exception_utils_1 = require("./exception.utils");
|
|
17
|
+
// Metadata keys
|
|
14
18
|
const ROUTES_KEY = Symbol('routes');
|
|
15
19
|
const MIDDLEWARE_KEY = Symbol('middlewares');
|
|
16
20
|
const PARAMS_KEY = Symbol('params');
|
|
17
|
-
|
|
21
|
+
const HTTP_CODE_KEY = Symbol('httpCode');
|
|
22
|
+
const HEADER_KEY = Symbol('headers');
|
|
23
|
+
const BEFORE_KEY = Symbol('before');
|
|
24
|
+
const AFTER_KEY = Symbol('after');
|
|
25
|
+
const ROLES_KEY = Symbol('roles');
|
|
26
|
+
const REDIRECT_KEY = Symbol('redirect');
|
|
27
|
+
/**
|
|
28
|
+
* Factory function that creates HTTP method decorators.
|
|
29
|
+
*
|
|
30
|
+
* @param method - HTTP method to create decorator for
|
|
31
|
+
* @returns A method decorator function
|
|
32
|
+
*/
|
|
18
33
|
function createRouteDecorator(method) {
|
|
19
34
|
return (path) => {
|
|
20
35
|
return (target, propertyKey, descriptor) => {
|
|
@@ -28,29 +43,134 @@ function createRouteDecorator(method) {
|
|
|
28
43
|
};
|
|
29
44
|
};
|
|
30
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* Decorator for GET HTTP method routes.
|
|
48
|
+
*
|
|
49
|
+
* @param path - URL path for the route
|
|
50
|
+
* @returns Method decorator
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* @Get('/users')
|
|
55
|
+
* getUsers() {
|
|
56
|
+
* return this.userService.findAll();
|
|
57
|
+
* }
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
31
60
|
exports.Get = createRouteDecorator('get');
|
|
61
|
+
/**
|
|
62
|
+
* Decorator for POST HTTP method routes.
|
|
63
|
+
*
|
|
64
|
+
* @param path - URL path for the route
|
|
65
|
+
* @returns Method decorator
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* @Post('/users')
|
|
70
|
+
* createUser(@Body() userData: any) {
|
|
71
|
+
* return this.userService.create(userData);
|
|
72
|
+
* }
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
32
75
|
exports.Post = createRouteDecorator('post');
|
|
76
|
+
/**
|
|
77
|
+
* Decorator for PUT HTTP method routes.
|
|
78
|
+
*
|
|
79
|
+
* @param path - URL path for the route
|
|
80
|
+
* @returns Method decorator
|
|
81
|
+
*/
|
|
33
82
|
exports.Put = createRouteDecorator('put');
|
|
83
|
+
/**
|
|
84
|
+
* Decorator for PATCH HTTP method routes.
|
|
85
|
+
*
|
|
86
|
+
* @param path - URL path for the route
|
|
87
|
+
* @returns Method decorator
|
|
88
|
+
*/
|
|
34
89
|
exports.Patch = createRouteDecorator('patch');
|
|
90
|
+
/**
|
|
91
|
+
* Decorator for DELETE HTTP method routes.
|
|
92
|
+
*
|
|
93
|
+
* @param path - URL path for the route
|
|
94
|
+
* @returns Method decorator
|
|
95
|
+
*/
|
|
35
96
|
exports.Delete = createRouteDecorator('delete');
|
|
97
|
+
/**
|
|
98
|
+
* Decorator for OPTIONS HTTP method routes.
|
|
99
|
+
*
|
|
100
|
+
* @param path - URL path for the route
|
|
101
|
+
* @returns Method decorator
|
|
102
|
+
*/
|
|
36
103
|
exports.Options = createRouteDecorator('options');
|
|
104
|
+
/**
|
|
105
|
+
* Decorator for HEAD HTTP method routes.
|
|
106
|
+
*
|
|
107
|
+
* @param path - URL path for the route
|
|
108
|
+
* @returns Method decorator
|
|
109
|
+
*/
|
|
37
110
|
exports.Head = createRouteDecorator('head');
|
|
111
|
+
/**
|
|
112
|
+
* Decorator for TRACE HTTP method routes.
|
|
113
|
+
*
|
|
114
|
+
* @param path - URL path for the route
|
|
115
|
+
* @returns Method decorator
|
|
116
|
+
*/
|
|
38
117
|
exports.Trace = createRouteDecorator('trace');
|
|
118
|
+
/**
|
|
119
|
+
* Decorator for CONNECT HTTP method routes.
|
|
120
|
+
*
|
|
121
|
+
* @param path - URL path for the route
|
|
122
|
+
* @returns Method decorator
|
|
123
|
+
*/
|
|
39
124
|
exports.Connect = createRouteDecorator('connect');
|
|
40
|
-
|
|
125
|
+
/**
|
|
126
|
+
* Decorator that marks a class as a controller with a base path.
|
|
127
|
+
* Used as the entry point for routing configuration.
|
|
128
|
+
*
|
|
129
|
+
* @param basePath - Base URL path for all routes in this controller
|
|
130
|
+
* @returns Class decorator
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* ```ts
|
|
134
|
+
* @Controller('/api/users')
|
|
135
|
+
* class UserController {
|
|
136
|
+
* // Controller methods...
|
|
137
|
+
* }
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
41
140
|
function Controller(basePath) {
|
|
42
141
|
return target => {
|
|
43
142
|
Reflect.defineMetadata('basePath', basePath, target);
|
|
44
143
|
};
|
|
45
144
|
}
|
|
46
|
-
|
|
145
|
+
/**
|
|
146
|
+
* Decorator that applies middleware to a controller method.
|
|
147
|
+
* Multiple middlewares can be applied and will execute in order.
|
|
148
|
+
*
|
|
149
|
+
* @param middlewares - Express middleware functions to apply
|
|
150
|
+
* @returns Method decorator
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```ts
|
|
154
|
+
* @Get('/protected')
|
|
155
|
+
* @Use(authMiddleware, loggingMiddleware)
|
|
156
|
+
* getProtectedResource() {
|
|
157
|
+
* // This route is protected by auth middleware
|
|
158
|
+
* }
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
47
161
|
function Use(...middlewares) {
|
|
48
|
-
return (target, propertyKey,
|
|
162
|
+
return (target, propertyKey, _descriptor) => {
|
|
49
163
|
const existing = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey) || [];
|
|
50
164
|
Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey);
|
|
51
165
|
};
|
|
52
166
|
}
|
|
53
|
-
|
|
167
|
+
/**
|
|
168
|
+
* Factory function that creates parameter decorators.
|
|
169
|
+
*
|
|
170
|
+
* @param type - Parameter type to extract from request
|
|
171
|
+
* @param key - Optional fixed key for extraction
|
|
172
|
+
* @returns Parameter decorator function
|
|
173
|
+
*/
|
|
54
174
|
function createParamDecorator(type, key) {
|
|
55
175
|
return (paramKey) => {
|
|
56
176
|
return (target, propertyKey, parameterIndex) => {
|
|
@@ -62,45 +182,237 @@ function createParamDecorator(type, key) {
|
|
|
62
182
|
};
|
|
63
183
|
};
|
|
64
184
|
}
|
|
185
|
+
/**
|
|
186
|
+
* Decorator that extracts query parameters from request.
|
|
187
|
+
*
|
|
188
|
+
* @param paramKey - Optional key to extract specific query parameter
|
|
189
|
+
* @returns Parameter decorator
|
|
190
|
+
*
|
|
191
|
+
* @example
|
|
192
|
+
* ```ts
|
|
193
|
+
* @Get('/search')
|
|
194
|
+
* search(@Query('term') searchTerm: string) {
|
|
195
|
+
* // searchTerm will contain the value of req.query.term
|
|
196
|
+
* }
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
65
199
|
exports.Query = createParamDecorator('query');
|
|
200
|
+
/**
|
|
201
|
+
* Decorator that extracts route parameters from request.
|
|
202
|
+
*
|
|
203
|
+
* @param paramKey - Optional key to extract specific route parameter
|
|
204
|
+
* @returns Parameter decorator
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```ts
|
|
208
|
+
* @Get('/users/:id')
|
|
209
|
+
* getUser(@Param('id') userId: string) {
|
|
210
|
+
* // userId will contain the value of req.params.id
|
|
211
|
+
* }
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
66
214
|
exports.Param = createParamDecorator('param');
|
|
215
|
+
/**
|
|
216
|
+
* Decorator that extracts body or body property from request.
|
|
217
|
+
*
|
|
218
|
+
* @param paramKey - Optional key to extract specific body property
|
|
219
|
+
* @returns Parameter decorator
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```ts
|
|
223
|
+
* @Post('/users')
|
|
224
|
+
* createUser(@Body() userData: any) {
|
|
225
|
+
* // userData will contain the entire req.body
|
|
226
|
+
* }
|
|
227
|
+
*
|
|
228
|
+
* @Post('/update')
|
|
229
|
+
* updateName(@Body('name') name: string) {
|
|
230
|
+
* // name will contain the value of req.body.name
|
|
231
|
+
* }
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
67
234
|
exports.Body = createParamDecorator('body');
|
|
235
|
+
/**
|
|
236
|
+
* Decorator that injects the entire request object.
|
|
237
|
+
*
|
|
238
|
+
* @returns Parameter decorator
|
|
239
|
+
*
|
|
240
|
+
* @example
|
|
241
|
+
* ```ts
|
|
242
|
+
* @Get('/complex')
|
|
243
|
+
* complex(@Req() req: Request) {
|
|
244
|
+
* // Access the full request object
|
|
245
|
+
* console.log(req.headers);
|
|
246
|
+
* }
|
|
247
|
+
* ```
|
|
248
|
+
*/
|
|
68
249
|
exports.Req = createParamDecorator('req');
|
|
250
|
+
/**
|
|
251
|
+
* Decorator that injects the response object.
|
|
252
|
+
*
|
|
253
|
+
* @returns Parameter decorator
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* ```ts
|
|
257
|
+
* @Get('/custom')
|
|
258
|
+
* custom(@Res() res: Response) {
|
|
259
|
+
* // Direct access to response object
|
|
260
|
+
* return res.status(201).send('Created');
|
|
261
|
+
* }
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
69
264
|
exports.Res = createParamDecorator('res');
|
|
70
|
-
|
|
71
|
-
|
|
265
|
+
/**
|
|
266
|
+
* Decorator that sets a custom HTTP status code for a response.
|
|
267
|
+
*
|
|
268
|
+
* @param status - HTTP status code to use
|
|
269
|
+
* @returns Method decorator
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* ```ts
|
|
273
|
+
* @Post('/users')
|
|
274
|
+
* @HttpCode(201)
|
|
275
|
+
* createUser(@Body() userData: any) {
|
|
276
|
+
* // Response will have 201 Created status code
|
|
277
|
+
* return { id: '123', ...userData };
|
|
278
|
+
* }
|
|
279
|
+
* ```
|
|
280
|
+
*/
|
|
72
281
|
function HttpCode(status) {
|
|
73
|
-
return (target, propertyKey,
|
|
282
|
+
return (target, propertyKey, _descriptor) => {
|
|
74
283
|
Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey);
|
|
75
284
|
};
|
|
76
285
|
}
|
|
77
|
-
|
|
78
|
-
|
|
286
|
+
/**
|
|
287
|
+
* Decorator that adds a custom HTTP header to the response.
|
|
288
|
+
*
|
|
289
|
+
* @param name - Header name
|
|
290
|
+
* @param value - Header value
|
|
291
|
+
* @returns Method decorator
|
|
292
|
+
*
|
|
293
|
+
* @example
|
|
294
|
+
* ```ts
|
|
295
|
+
* @Get('/data')
|
|
296
|
+
* @Header('Cache-Control', 'max-age=60')
|
|
297
|
+
* getData() {
|
|
298
|
+
* // Response will include the Cache-Control header
|
|
299
|
+
* return { data: '...' };
|
|
300
|
+
* }
|
|
301
|
+
* ```
|
|
302
|
+
*/
|
|
79
303
|
function Header(name, value) {
|
|
80
|
-
return (target, propertyKey,
|
|
304
|
+
return (target, propertyKey, _descriptor) => {
|
|
81
305
|
const headers = Reflect.getMetadata(HEADER_KEY, target, propertyKey) || {};
|
|
82
306
|
headers[name] = value;
|
|
83
307
|
Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey);
|
|
84
308
|
};
|
|
85
309
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
310
|
+
/**
|
|
311
|
+
* Decorator that registers a function to run before route handler execution.
|
|
312
|
+
* Useful for pre-processing or logging.
|
|
313
|
+
*
|
|
314
|
+
* @param fn - Function to execute before the handler
|
|
315
|
+
* @returns Method decorator
|
|
316
|
+
*
|
|
317
|
+
* @example
|
|
318
|
+
* ```ts
|
|
319
|
+
* @Get('/users/:id')
|
|
320
|
+
* @Before((req, res) => console.log(`Accessing user ${req.params.id}`))
|
|
321
|
+
* getUser(@Param('id') id: string) {
|
|
322
|
+
* // Function will log before this handler runs
|
|
323
|
+
* }
|
|
324
|
+
* ```
|
|
325
|
+
*/
|
|
89
326
|
function Before(fn) {
|
|
90
|
-
return (target, propertyKey,
|
|
327
|
+
return (target, propertyKey, _descriptor) => {
|
|
91
328
|
const hooks = Reflect.getMetadata(BEFORE_KEY, target, propertyKey) || [];
|
|
92
329
|
hooks.push(fn);
|
|
93
330
|
Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey);
|
|
94
331
|
};
|
|
95
332
|
}
|
|
333
|
+
/**
|
|
334
|
+
* Decorator that registers a function to run after route handler execution.
|
|
335
|
+
* Can access the handler's result.
|
|
336
|
+
*
|
|
337
|
+
* @param fn - Function to execute after the handler
|
|
338
|
+
* @returns Method decorator
|
|
339
|
+
*
|
|
340
|
+
* @example
|
|
341
|
+
* ```ts
|
|
342
|
+
* @Get('/users/:id')
|
|
343
|
+
* @After((req, res, result) => console.log(`User data sent: ${JSON.stringify(result)}`))
|
|
344
|
+
* getUser(@Param('id') id: string) {
|
|
345
|
+
* // After this handler, the function will log the returned data
|
|
346
|
+
* return { id, name: 'Example' };
|
|
347
|
+
* }
|
|
348
|
+
* ```
|
|
349
|
+
*/
|
|
96
350
|
function After(fn) {
|
|
97
|
-
return (target, propertyKey,
|
|
351
|
+
return (target, propertyKey, _descriptor) => {
|
|
98
352
|
const hooks = Reflect.getMetadata(AFTER_KEY, target, propertyKey) || [];
|
|
99
353
|
hooks.push(fn);
|
|
100
354
|
Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey);
|
|
101
355
|
};
|
|
102
356
|
}
|
|
103
|
-
|
|
357
|
+
/**
|
|
358
|
+
* Decorator that requires specific roles for accessing a route.
|
|
359
|
+
* Must be used with authentication middleware.
|
|
360
|
+
*
|
|
361
|
+
* @param roles - List of roles that can access this route
|
|
362
|
+
* @returns Method decorator
|
|
363
|
+
*
|
|
364
|
+
* @example
|
|
365
|
+
* ```ts
|
|
366
|
+
* @Get('/admin/settings')
|
|
367
|
+
* @Roles('admin', 'superuser')
|
|
368
|
+
* getSettings() {
|
|
369
|
+
* // Only admins and superusers can access
|
|
370
|
+
* return { settings: [...] };
|
|
371
|
+
* }
|
|
372
|
+
* ```
|
|
373
|
+
*/
|
|
374
|
+
function Roles(...roles) {
|
|
375
|
+
return (target, propertyKey, _descriptor) => {
|
|
376
|
+
Reflect.defineMetadata(ROLES_KEY, roles, target, propertyKey);
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Decorator that redirects to another URL.
|
|
381
|
+
*
|
|
382
|
+
* @param url - URL to redirect to (can be absolute or relative)
|
|
383
|
+
* @param statusCode - HTTP status code for redirect (default: 302)
|
|
384
|
+
* @returns Method decorator
|
|
385
|
+
*
|
|
386
|
+
* @example
|
|
387
|
+
* ```ts
|
|
388
|
+
* @Get('/old-path')
|
|
389
|
+
* @Redirect('/new-path', 301)
|
|
390
|
+
* redirectToNewPath() {
|
|
391
|
+
* // This method won't be executed; automatic redirect happens
|
|
392
|
+
* }
|
|
393
|
+
*
|
|
394
|
+
* @Get('/dynamic-redirect')
|
|
395
|
+
* @Redirect()
|
|
396
|
+
* getDynamicRedirect() {
|
|
397
|
+
* // Return an object with url and optionally statusCode
|
|
398
|
+
* return { url: '/calculated-path', statusCode: 307 };
|
|
399
|
+
* }
|
|
400
|
+
* ```
|
|
401
|
+
*/
|
|
402
|
+
function Redirect(url, statusCode = 302) {
|
|
403
|
+
return (target, propertyKey, descriptor) => {
|
|
404
|
+
// Store the redirect information in metadata
|
|
405
|
+
Reflect.defineMetadata(REDIRECT_KEY, { url, statusCode }, target, propertyKey);
|
|
406
|
+
return descriptor;
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Registers all controller classes with the provided router.
|
|
411
|
+
* This function processes all decorators and sets up the Express routes.
|
|
412
|
+
*
|
|
413
|
+
* @param router - Express router instance
|
|
414
|
+
* @param controllers - Array of controller classes
|
|
415
|
+
*/
|
|
104
416
|
function registerControllers(router, controllers) {
|
|
105
417
|
controllers.forEach(ControllerClass => {
|
|
106
418
|
const instance = new ControllerClass();
|
|
@@ -113,9 +425,20 @@ function registerControllers(router, controllers) {
|
|
|
113
425
|
const headers = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};
|
|
114
426
|
const beforeHooks = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];
|
|
115
427
|
const afterHooks = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];
|
|
428
|
+
const roles = Reflect.getMetadata(ROLES_KEY, instance, handlerName) || [];
|
|
429
|
+
const redirect = Reflect.getMetadata(REDIRECT_KEY, instance, handlerName);
|
|
116
430
|
const handler = async (req, res, next) => {
|
|
117
|
-
var _a, _b;
|
|
431
|
+
var _a, _b, _c, _d;
|
|
118
432
|
try {
|
|
433
|
+
// Handle roles-based access control
|
|
434
|
+
if (roles.length && !((_b = (_a = req === null || req === void 0 ? void 0 : req.user) === null || _a === void 0 ? void 0 : _a.roles) === null || _b === void 0 ? void 0 : _b.some((role) => roles.includes(role)))) {
|
|
435
|
+
res.status(http_status_codes_1.HttpStatusCodes.FORBIDDEN).json(new exception_utils_1.ForbiddenException('Forbidden Insufficient Roles'));
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
// Process static redirect if configured
|
|
439
|
+
if (redirect && redirect.url) {
|
|
440
|
+
return res.redirect(redirect.statusCode, redirect.url);
|
|
441
|
+
}
|
|
119
442
|
for (const fn of beforeHooks)
|
|
120
443
|
await fn(req, res);
|
|
121
444
|
const args = [];
|
|
@@ -144,11 +467,17 @@ function registerControllers(router, controllers) {
|
|
|
144
467
|
const result = instance[handlerName](...args);
|
|
145
468
|
// Support both sync and async handlers
|
|
146
469
|
const awaited = result instanceof Promise ? await result : result;
|
|
470
|
+
// Handle dynamic redirects
|
|
471
|
+
if (redirect && awaited && typeof awaited === 'object' && 'url' in awaited) {
|
|
472
|
+
const redirectUrl = awaited.url;
|
|
473
|
+
const redirectStatus = awaited.statusCode || redirect.statusCode;
|
|
474
|
+
return res.redirect(redirectStatus, redirectUrl);
|
|
475
|
+
}
|
|
147
476
|
if (!res.headersSent && typeof awaited !== 'undefined') {
|
|
148
477
|
if (httpCode)
|
|
149
|
-
(
|
|
478
|
+
(_c = res.status) === null || _c === void 0 ? void 0 : _c.call(res, httpCode);
|
|
150
479
|
for (const [k, v] of Object.entries(headers))
|
|
151
|
-
(
|
|
480
|
+
(_d = res.set) === null || _d === void 0 ? void 0 : _d.call(res, k, v);
|
|
152
481
|
res.json(awaited);
|
|
153
482
|
}
|
|
154
483
|
for (const fn of afterHooks)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":";AAAA,sDAAsD;;;AAmEtD,gCAIC;AAGD,kBAKC;AAuBD,4BAIC;AAID,wBAMC;A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C,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport 'reflect-metadata';\n\n// --- Sample Express interfaces for type safety ---\ninterface Request {\n query: any;\n params: any;\n body?: any;\n [key: string]: any;\n}\ninterface Response {\n json: (body: any) => void;\n headersSent: boolean;\n [key: string]: any;\n}\ntype NextFunction = (err?: any) => void;\ntype RequestHandler = (req: Request, res: Response, next: NextFunction) => any;\ninterface Router {\n [method: string]: (path: string, ...handlers: RequestHandler[]) => void;\n}\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator('get');\nexport const Post = createRouteDecorator('post');\nexport const Put = createRouteDecorator('put');\nexport const Patch = createRouteDecorator('patch');\nexport const Delete = createRouteDecorator('delete');\nexport const Options = createRouteDecorator('options');\nexport const Head = createRouteDecorator('head');\nexport const Trace = createRouteDecorator('trace');\nexport const Connect = createRouteDecorator('connect');\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator('query');\nexport const Param = createParamDecorator('param');\nexport const Body = createParamDecorator('body');\nexport const Req = createParamDecorator('req');\nexport const Res = createParamDecorator('res');\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol('httpCode');\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol('headers');\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":";AAAA,sDAAsD;;;AA0KtD,gCAIC;AAkBD,kBAKC;AA0HD,4BAIC;AAmBD,wBAMC;AAkBD,wBAMC;AAmBD,sBAMC;AAmBD,sBAIC;AAyBD,4BAMC;AASD,kDAkFC;AA3hBD,4BAA0B;AAC1B,2DAAsD;AACtD,uDAAuD;AAEvD,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,aAAa,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AACzC,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACrC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAClC,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAClC,MAAM,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AA+BxC;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,MAAkB;IAC9C,OAAO,CAAC,IAAY,EAAmB,EAAE;QACvC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE;YACzC,MAAM,MAAM,GAAsB,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;YAC5F,MAAM,CAAC,IAAI,CAAC;gBACV,IAAI;gBACJ,MAAM;gBACN,WAAW,EAAE,WAAqB;aACnC,CAAC,CAAC;YACH,OAAO,CAAC,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,MA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,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type { RequestHandler, Router } from 'express';\nimport 'reflect-metadata';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ForbiddenException } from './exception.utils';\n\n// Metadata keys\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\nconst HTTP_CODE_KEY = Symbol('httpCode');\nconst HEADER_KEY = Symbol('headers');\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nconst ROLES_KEY = Symbol('roles');\nconst REDIRECT_KEY = Symbol('redirect');\n\n/**\n * Supported HTTP methods for route decorators\n */\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\n/**\n * Represents a route definition for controller methods\n */\ninterface RouteDefinition {\n /** The URL path for this route */\n path: string;\n /** HTTP method for this route */\n method: HttpMethod;\n /** Name of the handler method in the controller class */\n handlerName: string;\n}\n\n/**\n * Parameter decoration definition for method parameters\n */\ninterface ParamDefinition {\n /** Parameter position in method signature */\n index: number;\n /** Type of parameter (query, body, etc.) */\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n /** Optional key for extracting specific property */\n key?: string;\n}\n\n/**\n * Factory function that creates HTTP method decorators.\n *\n * @param method - HTTP method to create decorator for\n * @returns A method decorator function\n */\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\n/**\n * Decorator for GET HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users')\n * getUsers() {\n * return this.userService.findAll();\n * }\n * ```\n */\nexport const Get = createRouteDecorator('get');\n\n/**\n * Decorator for POST HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * return this.userService.create(userData);\n * }\n * ```\n */\nexport const Post = createRouteDecorator('post');\n\n/**\n * Decorator for PUT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Put = createRouteDecorator('put');\n\n/**\n * Decorator for PATCH HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Patch = createRouteDecorator('patch');\n\n/**\n * Decorator for DELETE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Delete = createRouteDecorator('delete');\n\n/**\n * Decorator for OPTIONS HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Options = createRouteDecorator('options');\n\n/**\n * Decorator for HEAD HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Head = createRouteDecorator('head');\n\n/**\n * Decorator for TRACE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Trace = createRouteDecorator('trace');\n\n/**\n * Decorator for CONNECT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Connect = createRouteDecorator('connect');\n\n/**\n * Decorator that marks a class as a controller with a base path.\n * Used as the entry point for routing configuration.\n *\n * @param basePath - Base URL path for all routes in this controller\n * @returns Class decorator\n *\n * @example\n * ```ts\n * @Controller('/api/users')\n * class UserController {\n * // Controller methods...\n * }\n * ```\n */\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n/**\n * Decorator that applies middleware to a controller method.\n * Multiple middlewares can be applied and will execute in order.\n *\n * @param middlewares - Express middleware functions to apply\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/protected')\n * @Use(authMiddleware, loggingMiddleware)\n * getProtectedResource() {\n * // This route is protected by auth middleware\n * }\n * ```\n */\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n/**\n * Factory function that creates parameter decorators.\n *\n * @param type - Parameter type to extract from request\n * @param key - Optional fixed key for extraction\n * @returns Parameter decorator function\n */\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\n/**\n * Decorator that extracts query parameters from request.\n *\n * @param paramKey - Optional key to extract specific query parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/search')\n * search(@Query('term') searchTerm: string) {\n * // searchTerm will contain the value of req.query.term\n * }\n * ```\n */\nexport const Query = createParamDecorator('query');\n\n/**\n * Decorator that extracts route parameters from request.\n *\n * @param paramKey - Optional key to extract specific route parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * getUser(@Param('id') userId: string) {\n * // userId will contain the value of req.params.id\n * }\n * ```\n */\nexport const Param = createParamDecorator('param');\n\n/**\n * Decorator that extracts body or body property from request.\n *\n * @param paramKey - Optional key to extract specific body property\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * // userData will contain the entire req.body\n * }\n *\n * @Post('/update')\n * updateName(@Body('name') name: string) {\n * // name will contain the value of req.body.name\n * }\n * ```\n */\nexport const Body = createParamDecorator('body');\n\n/**\n * Decorator that injects the entire request object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/complex')\n * complex(@Req() req: Request) {\n * // Access the full request object\n * console.log(req.headers);\n * }\n * ```\n */\nexport const Req = createParamDecorator('req');\n\n/**\n * Decorator that injects the response object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/custom')\n * custom(@Res() res: Response) {\n * // Direct access to response object\n * return res.status(201).send('Created');\n * }\n * ```\n */\nexport const Res = createParamDecorator('res');\n\n/**\n * Decorator that sets a custom HTTP status code for a response.\n *\n * @param status - HTTP status code to use\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * @HttpCode(201)\n * createUser(@Body() userData: any) {\n * // Response will have 201 Created status code\n * return { id: '123', ...userData };\n * }\n * ```\n */\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that adds a custom HTTP header to the response.\n *\n * @param name - Header name\n * @param value - Header value\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/data')\n * @Header('Cache-Control', 'max-age=60')\n * getData() {\n * // Response will include the Cache-Control header\n * return { data: '...' };\n * }\n * ```\n */\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run before route handler execution.\n * Useful for pre-processing or logging.\n *\n * @param fn - Function to execute before the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @Before((req, res) => console.log(`Accessing user ${req.params.id}`))\n * getUser(@Param('id') id: string) {\n * // Function will log before this handler runs\n * }\n * ```\n */\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run after route handler execution.\n * Can access the handler's result.\n *\n * @param fn - Function to execute after the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @After((req, res, result) => console.log(`User data sent: ${JSON.stringify(result)}`))\n * getUser(@Param('id') id: string) {\n * // After this handler, the function will log the returned data\n * return { id, name: 'Example' };\n * }\n * ```\n */\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that requires specific roles for accessing a route.\n * Must be used with authentication middleware.\n *\n * @param roles - List of roles that can access this route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/admin/settings')\n * @Roles('admin', 'superuser')\n * getSettings() {\n * // Only admins and superusers can access\n * return { settings: [...] };\n * }\n * ```\n */\nexport function Roles(...roles: string[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(ROLES_KEY, roles, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that redirects to another URL.\n *\n * @param url - URL to redirect to (can be absolute or relative)\n * @param statusCode - HTTP status code for redirect (default: 302)\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/old-path')\n * @Redirect('/new-path', 301)\n * redirectToNewPath() {\n * // This method won't be executed; automatic redirect happens\n * }\n *\n * @Get('/dynamic-redirect')\n * @Redirect()\n * getDynamicRedirect() {\n * // Return an object with url and optionally statusCode\n * return { url: '/calculated-path', statusCode: 307 };\n * }\n * ```\n */\nexport function Redirect(url?: string, statusCode: number = 302): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n // Store the redirect information in metadata\n Reflect.defineMetadata(REDIRECT_KEY, { url, statusCode }, target, propertyKey as string);\n return descriptor;\n };\n}\n\n/**\n * Registers all controller classes with the provided router.\n * This function processes all decorators and sets up the Express routes.\n *\n * @param router - Express router instance\n * @param controllers - Array of controller classes\n */\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n const roles: string[] = Reflect.getMetadata(ROLES_KEY, instance, handlerName) || [];\n const redirect: { url?: string; statusCode: number } | undefined = Reflect.getMetadata(\n REDIRECT_KEY,\n instance,\n handlerName\n );\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n // Handle roles-based access control\n if (roles.length && !(req as any)?.user?.roles?.some((role: string) => roles.includes(role))) {\n res.status(HttpStatusCodes.FORBIDDEN).json(new ForbiddenException('Forbidden Insufficient Roles'));\n return;\n }\n\n // Process static redirect if configured\n if (redirect && redirect.url) {\n return res.redirect(redirect.statusCode, redirect.url);\n }\n\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n\n // Handle dynamic redirects\n if (redirect && awaited && typeof awaited === 'object' && 'url' in awaited) {\n const redirectUrl = awaited.url as string;\n const redirectStatus = (awaited.statusCode as number) || redirect.statusCode;\n return res.redirect(redirectStatus, redirectUrl);\n }\n\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|