@e22m4u/ts-rest-router 0.0.7 → 0.1.0

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.
Files changed (62) hide show
  1. package/README-ru.md +114 -91
  2. package/README.md +106 -85
  3. package/dist/cjs/index.cjs +427 -123
  4. package/dist/esm/controller-registry.d.ts +53 -11
  5. package/dist/esm/controller-registry.js +242 -104
  6. package/dist/esm/debuggable-service.js +1 -1
  7. package/dist/esm/decorators/after/after-decorator.d.ts +9 -0
  8. package/dist/esm/decorators/after/after-decorator.js +22 -0
  9. package/dist/esm/decorators/after/after-decorator.spec.d.ts +1 -0
  10. package/dist/esm/decorators/after/after-decorator.spec.js +115 -0
  11. package/dist/esm/decorators/after/after-metadata.d.ts +13 -0
  12. package/dist/esm/decorators/after/after-metadata.js +5 -0
  13. package/dist/esm/decorators/after/after-reflector.d.ts +22 -0
  14. package/dist/esm/decorators/after/after-reflector.js +29 -0
  15. package/dist/esm/decorators/after/after-reflector.spec.d.ts +1 -0
  16. package/dist/esm/decorators/after/after-reflector.spec.js +102 -0
  17. package/dist/esm/decorators/after/index.d.ts +3 -0
  18. package/dist/esm/decorators/after/index.js +3 -0
  19. package/dist/esm/decorators/before/before-decorator.d.ts +9 -0
  20. package/dist/esm/decorators/before/before-decorator.js +22 -0
  21. package/dist/esm/decorators/before/before-decorator.spec.d.ts +1 -0
  22. package/dist/esm/decorators/before/before-decorator.spec.js +115 -0
  23. package/dist/esm/decorators/before/before-metadata.d.ts +13 -0
  24. package/dist/esm/decorators/before/before-metadata.js +5 -0
  25. package/dist/esm/decorators/before/before-reflector.d.ts +22 -0
  26. package/dist/esm/decorators/before/before-reflector.js +29 -0
  27. package/dist/esm/decorators/before/before-reflector.spec.d.ts +1 -0
  28. package/dist/esm/decorators/before/before-reflector.spec.js +102 -0
  29. package/dist/esm/decorators/before/index.d.ts +3 -0
  30. package/dist/esm/decorators/before/index.js +3 -0
  31. package/dist/esm/decorators/controller/controller-decorator.d.ts +2 -1
  32. package/dist/esm/decorators/controller/controller-decorator.js +26 -1
  33. package/dist/esm/decorators/controller/controller-decorator.spec.js +28 -0
  34. package/dist/esm/decorators/index.d.ts +2 -0
  35. package/dist/esm/decorators/index.js +2 -0
  36. package/dist/esm/decorators/request-data/request-data-decorator.d.ts +1 -1
  37. package/dist/esm/decorators/request-data/request-data-decorator.js +1 -1
  38. package/dist/esm/decorators/request-data/request-data-decorator.spec.js +5 -5
  39. package/dist/esm/utils/create-debugger.d.ts +35 -2
  40. package/dist/esm/utils/create-debugger.js +71 -5
  41. package/package.json +1 -1
  42. package/src/controller-registry.spec.ts +601 -275
  43. package/src/controller-registry.ts +263 -128
  44. package/src/debuggable-service.ts +1 -1
  45. package/src/decorators/after/after-decorator.spec.ts +92 -0
  46. package/src/decorators/after/after-decorator.ts +40 -0
  47. package/src/decorators/after/after-metadata.ts +17 -0
  48. package/src/decorators/after/after-reflector.spec.ts +107 -0
  49. package/src/decorators/after/after-reflector.ts +45 -0
  50. package/src/decorators/after/index.ts +3 -0
  51. package/src/decorators/before/before-decorator.spec.ts +92 -0
  52. package/src/decorators/before/before-decorator.ts +40 -0
  53. package/src/decorators/before/before-metadata.ts +17 -0
  54. package/src/decorators/before/before-reflector.spec.ts +111 -0
  55. package/src/decorators/before/before-reflector.ts +50 -0
  56. package/src/decorators/before/index.ts +3 -0
  57. package/src/decorators/controller/controller-decorator.spec.ts +22 -0
  58. package/src/decorators/controller/controller-decorator.ts +29 -1
  59. package/src/decorators/index.ts +2 -0
  60. package/src/decorators/request-data/request-data-decorator.spec.ts +5 -5
  61. package/src/decorators/request-data/request-data-decorator.ts +1 -1
  62. package/src/utils/create-debugger.ts +84 -7
package/README-ru.md CHANGED
@@ -32,57 +32,35 @@ npm install @e22m4u/ts-rest-router
32
32
 
33
33
  ## Базовое использование
34
34
 
35
- Создание контроллера
35
+ Создание контроллера и методов
36
36
 
37
37
  ```ts
38
- import {controller, get, post} from '@e22m4u/ts-rest-router';
39
-
40
- @controller()
41
- class UserController {
42
- @get('/users')
43
- async getUsers() {
44
- return { users: [] };
45
- }
46
-
47
- @post('/users')
48
- async createUser(
49
- @body() userData: UserDTO,
50
- ) {
51
- return { success: true };
52
- }
53
- }
54
- ```
55
-
56
- Работа с параметрами запроса
57
-
58
- ```ts
59
- @controller()
60
- class ProductController {
61
- @get('/products/:id')
62
- async getProduct(
63
- @param('id') productId: string,
64
- @query('fields') fields?: string,
65
- @headers('authorization') auth?: string,
38
+ import {get} from '@e22m4u/ts-rest-router';
39
+ import {post} from '@e22m4u/ts-rest-router';
40
+ import {bodyProp} from '@e22m4u/ts-rest-router';
41
+ import {DataType} from '@e22m4u/ts-rest-router';
42
+ import {controller} from '@e22m4u/ts-rest-router';
43
+
44
+ @controller('/users') // путь контроллера
45
+ class UserController { // класс контроллера
46
+ @post('/login') // метод POST /users/login
47
+ async login(
48
+ @bodyProp('username', { // свойство тела запроса "username"
49
+ type: DataType.STRING, // тип параметра допускает только строки
50
+ required: true, // параметр является обязательным
51
+ })
52
+ username: string,
53
+ @bodyProp('password', { // свойство тела запроса "password"
54
+ type: DataType.STRING, // тип параметра допускает только строки
55
+ required: true, // параметр является обязательным
56
+ })
57
+ password: string,
66
58
  ) {
67
- // ...
68
- }
69
- }
70
- ```
71
-
72
- Middleware и хуки
73
-
74
- ```ts
75
- @controller({
76
- path: '/api',
77
- before: [authMiddleware],
78
- after: [loggerMiddleware],
79
- })
80
- class ApiController {
81
- @get('/secure', {
82
- before: [checkPermissions],
83
- })
84
- secureEndpoint() {
85
- // ...
59
+ return { // если метод возвращает объект,
60
+ id: '123', // то результат будет представлен как
61
+ firstName: 'John', // "Content-Type: application/json"
62
+ lastName: 'Doe',
63
+ };
86
64
  }
87
65
  }
88
66
  ```
@@ -110,7 +88,7 @@ server.listen('8080', '0.0.0.0', () => {
110
88
 
111
89
  ## Декораторы
112
90
 
113
- Контроллер и методы
91
+ Контроллер и методы:
114
92
 
115
93
  - `@controller` - определяет класс как контроллер
116
94
  - `@action` - базовый декоратор для методов
@@ -120,14 +98,19 @@ server.listen('8080', '0.0.0.0', () => {
120
98
  - `@patch` - PATCH запросы
121
99
  - `@del` - DELETE запросы
122
100
 
123
- Параметры запроса
101
+ Хуки запроса:
102
+
103
+ - `@before` - middleware перед обработкой запроса
104
+ - `@after` - middleware после обработки запроса
105
+
106
+ Параметры запроса:
124
107
 
125
108
  - `@param` - один параметр URL
126
109
  - `@params` - все параметры URL как объект
127
110
  - `@query` - один query параметр
128
111
  - `@queries` - все query параметры как объект
129
112
  - `@body` - тело запроса
130
- - `@bodyParam` - конкретное поле из тела запроса
113
+ - `@bodyProp` - свойство из тела запроса
131
114
  - `@header` - один заголовок
132
115
  - `@headers` - все заголовки как объект
133
116
  - `@cookie` - одна cookie
@@ -137,82 +120,122 @@ server.listen('8080', '0.0.0.0', () => {
137
120
 
138
121
  #### `@controller(options?: ControllerOptions)`
139
122
 
140
- Декоратор для определения класса как REST API контроллера.
123
+ Определение контроллера.
141
124
 
142
- ```typescript
125
+ ```ts
143
126
  @controller()
144
127
  class UserController {
145
128
  // методы контроллера
146
129
  }
147
130
  ```
148
131
 
132
+ Определение пути контроллера.
133
+
134
+ ```ts
135
+ @controller('/users') // путь контроллера
136
+ class UserController {
137
+ // методы контроллера
138
+ }
139
+ ```
140
+
149
141
  Дополнительные параметры декоратора.
150
142
 
151
- ```typescript
143
+ ```ts
152
144
  @controller({
153
- path: '/api'
154
- before: [authMiddleware],
155
- after: [loggerMiddleware],
145
+ path: '/api', // путь контроллера
146
+ before: [authMiddleware], // middleware до обработки запроса
147
+ after: [loggerMiddleware], // middleware после обработки запроса
156
148
  })
157
149
  class UserController {
158
150
  // методы контроллера
159
151
  }
160
152
  ```
161
153
 
162
- ### `@get(path: string, options?: ActionOptions)`
154
+ #### `@get(path: string, options?: ActionOptions)`
163
155
 
164
- Декоратор для определения метода GET.
156
+ Определение метода GET.
165
157
 
166
- ```typescript
167
- @controller()
168
- class UserController {
169
- @get('/users')
170
- async getUsers() {
171
- return {users: []};
172
- }
173
-
174
- @get('/users/:id')
175
- getUser(
176
- @param('id') userId: string,
177
- ) {
178
- return {user: {id: userId}};
158
+ ```ts
159
+ @controller('/users') // путь контроллера
160
+ class UserController { // класс контроллера
161
+ @get('/whoAmI') // маршрут GET /users/whoAmI
162
+ async whoAmI() {
163
+ return { // если метод возвращает объект,
164
+ name: 'John', // то результат будет представлен
165
+ surname: 'Doe', // как "Content-Type: application/json"
166
+ };
179
167
  }
180
168
  }
181
169
  ```
182
170
 
183
171
  Дополнительные параметры декоратора.
184
172
 
185
- ```typescript
186
- @controller()
187
- class UserController {
188
- @get('/users', {
189
- before: [authMiddleware],
190
- after: [loggerMiddleware],
173
+ ```ts
174
+ @controller('/users') // путь контроллера
175
+ class UserController { // класс контроллера
176
+ @get('/whoAmI', { // маршрут GET /users/whoAmI
177
+ before: [authMiddleware], // middleware до обработки запроса
178
+ after: [loggerMiddleware], // middleware после обработки запроса
191
179
  })
192
- async getUsers() {
193
- return {users: []};
180
+ async whoAmI() {
181
+ return {
182
+ name: 'John',
183
+ surname: 'Doe',
184
+ };
194
185
  }
195
186
  }
196
187
  ```
197
188
 
198
- ### `@requestContext(propertyName?: string)`
189
+ #### `@requestContext(propertyName?: string)`
199
190
 
200
- Декоратор для доступа к контексту запроса.
191
+ Доступ к контексту запроса.
201
192
 
202
- ```typescript
203
- @controller()
204
- class UserController {
205
- @get('/users')
206
- getUsers(
207
- @requestContext('req') req: IncomingMessage,
208
- @requestContext('res') res: ServerResponse,
193
+ ```ts
194
+ import {RequestContext} from '@e22m4u/js-trie-router';
195
+
196
+ @controller('/users') // путь контроллера
197
+ class UserController { // класс контроллера
198
+ @get('/:id') // маршрут GET /users/:id
199
+ findById(
200
+ @requestContext() // включениее контекста запроса
201
+ ctx: RequestContext, // в качестве параметра метода
202
+ ) {
203
+ console.log(ctx.req); // IncomingMessage
204
+ console.log(ctx.res); // ServerResponse
205
+ console.log(ctx.params); // {id: 10}
206
+ console.log(ctx.query); // {include: 'city'}
207
+ console.log(ctx.headers); // {cookie: 'foo=bar; baz=qux;'}
208
+ console.log(ctx.cookie); // {foo: 'bar', baz: 'qux'}
209
+ console.log(ctx.method); // "GET"
210
+ console.log(ctx.path); // "/users/10?include=city"
211
+ console.log(ctx.pathname); // "/users/10"
212
+ // ...
213
+ }
214
+ }
215
+ ```
216
+
217
+ Доступ к свойствам контекста.
218
+
219
+ ```ts
220
+ import {ServerResponse} from 'http';
221
+ import {IncomingMessage} from 'http';
222
+
223
+ @controller('/users') // путь контроллера
224
+ class UserController { // класс контроллера
225
+ @get('/:id') // маршрут GET /users/:id
226
+ findById(
227
+ @requestContext('req') // декоратор контекста запроса
228
+ req: IncomingMessage, // включающий свойство "req"
229
+ @requestContext('res') // декоратор контекста запроса
230
+ res: ServerResponse, // включающий свойство "res"
209
231
  ) {
210
- // Доступ к оригинальным объектам запроса/ответа
232
+ console.log(req); // IncomingMessage
233
+ console.log(res); // ServerResponse
211
234
  }
212
235
  }
213
236
  ```
214
237
 
215
- Допустимые свойства:
238
+ Свойства контекста:
216
239
 
217
240
  - `container: ServiceContainer` экземпляр [сервис-контейнера](https://npmjs.com/package/@e22m4u/js-service)
218
241
  - `req: IncomingMessage` нативный поток входящего запроса
package/README.md CHANGED
@@ -32,57 +32,35 @@ options to your `tsconfig.json` file.
32
32
 
33
33
  ## Basic Usage
34
34
 
35
- Creating a controller.
35
+ Creating a controller and methods.
36
36
 
37
37
  ```ts
38
- import {controller, get, post} from '@e22m4u/ts-rest-router';
39
-
40
- @controller()
41
- class UserController {
42
- @get('/users')
43
- async getUsers() {
44
- return { users: [] };
45
- }
46
-
47
- @post('/users')
48
- async createUser(
49
- @body() userData: UserDTO,
38
+ import {get} from '@e22m4u/ts-rest-router';
39
+ import {post} from '@e22m4u/ts-rest-router';
40
+ import {bodyProp} from '@e22m4u/ts-rest-router';
41
+ import {DataType} from '@e22m4u/ts-rest-router';
42
+ import {controller} from '@e22m4u/ts-rest-router';
43
+
44
+ @controller('/users') // controller path
45
+ class UserController { // controller class
46
+ @post('/login') // POST /users/login method
47
+ async login(
48
+ @bodyProp('username', { // "username" is request body property
49
+ type: DataType.STRING, // parameter type allows only strings
50
+ required: true, // parameter is required
51
+ })
52
+ username: string,
53
+ @bodyProp('password', { // "password" is request body property
54
+ type: DataType.STRING, // parameter type allows only strings
55
+ required: true, // parameter is required
56
+ })
57
+ password: string,
50
58
  ) {
51
- return { success: true };
52
- }
53
- }
54
- ```
55
-
56
- Request parameters.
57
-
58
- ```ts
59
- @controller()
60
- class ProductController {
61
- @get('/products/:id')
62
- async getProduct(
63
- @param('id') productId: string,
64
- @query('fields') fields?: string,
65
- @headers('authorization') auth?: string,
66
- ) {
67
- // ...
68
- }
69
- }
70
- ```
71
-
72
- Middleware and hooks.
73
-
74
- ```ts
75
- @controller({
76
- path: '/api',
77
- before: [authMiddleware],
78
- after: [loggerMiddleware],
79
- })
80
- class ApiController {
81
- @get('/secure', {
82
- before: [checkPermissions],
83
- })
84
- secureEndpoint() {
85
- // ...
59
+ return { // if method returns an object,
60
+ id: '123', // the result will be presented as
61
+ firstName: 'John', // "Content-Type: application/json"
62
+ lastName: 'Doe',
63
+ };
86
64
  }
87
65
  }
88
66
  ```
@@ -120,6 +98,11 @@ Controller and methods:
120
98
  - `@patch` - PATCH requests
121
99
  - `@del` - DELETE requests
122
100
 
101
+ Request hooks:
102
+
103
+ - `@before` - middleware before request handling
104
+ - `@after` - middleware after request handling
105
+
123
106
  Request parameters:
124
107
 
125
108
  - `@param` - single URL parameter
@@ -127,7 +110,7 @@ Request parameters:
127
110
  - `@query` - single query parameter
128
111
  - `@queries` - all query parameters as an object
129
112
  - `@body` - request body
130
- - `@bodyParam` - specific field from request body
113
+ - `@bodyProp` - property from request body
131
114
  - `@header` - single header
132
115
  - `@headers` - all headers as an object
133
116
  - `@cookie` - single cookie
@@ -137,7 +120,7 @@ Request parameters:
137
120
 
138
121
  #### `@controller(options?: ControllerOptions)`
139
122
 
140
- Decorator for defining a class as a REST API controller.
123
+ Defining a controller.
141
124
 
142
125
  ```ts
143
126
  @controller()
@@ -146,36 +129,41 @@ class UserController {
146
129
  }
147
130
  ```
148
131
 
132
+ Defining controller path.
133
+
134
+ ```ts
135
+ @controller('/users') // controller path
136
+ class UserController {
137
+ // controller methods
138
+ }
139
+ ```
140
+
149
141
  Additional decorator parameters.
150
142
 
151
143
  ```ts
152
144
  @controller({
153
- path: '/api'
154
- before: [authMiddleware],
155
- after: [loggerMiddleware],
145
+ path: '/api', // controller path
146
+ before: [authMiddleware], // middleware before request processing
147
+ after: [loggerMiddleware], // middleware after request processing
156
148
  })
157
149
  class UserController {
158
150
  // controller methods
159
151
  }
160
152
  ```
161
153
 
162
- ### `@get(path: string, options?: ActionOptions)`
154
+ #### `@get(path: string, options?: ActionOptions)`
163
155
 
164
- Decorator for defining GET method.
156
+ Defining GET method.
165
157
 
166
158
  ```ts
167
- @controller()
168
- class UserController {
169
- @get('/users')
170
- async getUsers() {
171
- return {users: []};
172
- }
173
-
174
- @get('/users/:id')
175
- getUser(
176
- @param('id') userId: string,
177
- ) {
178
- return {user: {id: userId}};
159
+ @controller('/users') // controller path
160
+ class UserController { // controller class
161
+ @get('/whoAmI') // GET /users/whoAmI route
162
+ async whoAmI() {
163
+ return { // if method returns an object,
164
+ name: 'John', // the result will be presented
165
+ surname: 'Doe', // as "Content-Type: application/json"
166
+ };
179
167
  }
180
168
  }
181
169
  ```
@@ -183,38 +171,71 @@ class UserController {
183
171
  Additional decorator parameters.
184
172
 
185
173
  ```ts
186
- @controller()
187
- class UserController {
188
- @get('/users', {
189
- before: [authMiddleware],
190
- after: [loggerMiddleware],
174
+ @controller('/users') // controller path
175
+ class UserController { // controller class
176
+ @get('/whoAmI', { // GET /users/whoAmI route
177
+ before: [authMiddleware], // middleware before request processing
178
+ after: [loggerMiddleware], // middleware after request processing
191
179
  })
192
- async getUsers() {
193
- return {users: []};
180
+ async whoAmI() {
181
+ return {
182
+ name: 'John',
183
+ surname: 'Doe',
184
+ };
194
185
  }
195
186
  }
196
187
  ```
197
188
 
198
- ### `@requestContext(propertyName?: string)`
189
+ #### `@requestContext(propertyName?: string)`
199
190
 
200
- Decorator for accessing request context.
191
+ Access to request context.
201
192
 
202
193
  ```ts
203
- import {IncomingMessage, ServerResponse} from 'http';
194
+ import {RequestContext} from '@e22m4u/js-trie-router';
195
+
196
+ @controller('/users') // controller path
197
+ class UserController { // controller class
198
+ @get('/:id') // GET /users/:id route
199
+ findById(
200
+ @requestContext() // including request context
201
+ ctx: RequestContext, // as method parameter
202
+ ) {
203
+ console.log(ctx.req); // IncomingMessage
204
+ console.log(ctx.res); // ServerResponse
205
+ console.log(ctx.params); // {id: 10}
206
+ console.log(ctx.query); // {include: 'city'}
207
+ console.log(ctx.headers); // {cookie: 'foo=bar; baz=qux;'}
208
+ console.log(ctx.cookie); // {foo: 'bar', baz: 'qux'}
209
+ console.log(ctx.method); // "GET"
210
+ console.log(ctx.path); // "/users/10?include=city"
211
+ console.log(ctx.pathname); // "/users/10"
212
+ // ...
213
+ }
214
+ }
215
+ ```
204
216
 
205
- @controller()
206
- class UserController {
207
- @get('/users')
208
- getUsers(
209
- @requestContext('req') req: IncomingMessage,
210
- @requestContext('res') res: ServerResponse,
217
+ Access to context properties.
218
+
219
+ ```ts
220
+ import {ServerResponse} from 'http';
221
+ import {IncomingMessage} from 'http';
222
+
223
+ @controller('/users') // controller path
224
+ class UserController { // controller class
225
+ @get('/:id') // GET /users/:id route
226
+ findById(
227
+ @requestContext('req') // request context decorator
228
+ req: IncomingMessage, // including "req" property
229
+ @requestContext('res') // request context decorator
230
+ res: ServerResponse, // including "res" property
211
231
  ) {
212
- // Access to original request/response objects
232
+ console.log(req); // IncomingMessage
233
+ console.log(res); // ServerResponse
213
234
  }
214
235
  }
215
236
  ```
216
237
 
217
- Available properties:
238
+ Context properties:
218
239
 
219
240
  - `container: ServiceContainer` instance of [service container](https://npmjs.com/package/@e22m4u/js-service)
220
241
  - `req: IncomingMessage` native incoming request stream