@e22m4u/ts-rest-router 0.0.6 → 0.0.7
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-ru.md +204 -0
- package/README.md +206 -0
- package/dist/cjs/index.cjs +22 -31
- package/dist/esm/decorators/action/action-decorator.d.ts +7 -8
- package/dist/esm/decorators/action/action-decorator.js +1 -5
- package/dist/esm/decorators/action/action-decorator.spec.js +16 -16
- package/dist/esm/decorators/action/action-metadata.d.ts +0 -1
- package/dist/esm/decorators/controller/controller-decorator.js +1 -5
- package/dist/esm/decorators/controller/controller-decorator.spec.js +9 -15
- package/dist/esm/decorators/controller/controller-metadata.d.ts +0 -1
- package/dist/esm/decorators/request-context/request-context-decorator.d.ts +2 -3
- package/dist/esm/decorators/request-context/request-context-decorator.js +3 -6
- package/dist/esm/decorators/request-context/request-context-decorator.spec.js +2 -17
- package/dist/esm/decorators/request-context/request-context-metadata.d.ts +0 -1
- package/dist/esm/decorators/request-data/request-data-decorator.d.ts +6 -2
- package/dist/esm/decorators/request-data/request-data-decorator.js +16 -16
- package/dist/esm/decorators/request-data/request-data-decorator.spec.js +7 -5
- package/dist/esm/decorators/request-data/request-data-metadata.d.ts +0 -1
- package/package.json +17 -17
- package/src/decorators/action/action-decorator.spec.ts +16 -16
- package/src/decorators/action/action-decorator.ts +10 -12
- package/src/decorators/action/action-metadata.ts +0 -1
- package/src/decorators/controller/controller-decorator.spec.ts +11 -16
- package/src/decorators/controller/controller-decorator.ts +4 -5
- package/src/decorators/controller/controller-metadata.ts +0 -1
- package/src/decorators/request-context/request-context-decorator.spec.ts +2 -15
- package/src/decorators/request-context/request-context-decorator.ts +3 -8
- package/src/decorators/request-context/request-context-metadata.ts +0 -1
- package/src/decorators/request-data/request-data-decorator.spec.ts +7 -6
- package/src/decorators/request-data/request-data-decorator.ts +41 -16
- package/src/decorators/request-data/request-data-metadata.ts +0 -1
package/README-ru.md
CHANGED
@@ -4,6 +4,14 @@
|
|
4
4
|
|
5
5
|
Реализация REST маршрутизатора на основе контроллеров для TypeScript.
|
6
6
|
|
7
|
+
#### Основные возможности
|
8
|
+
|
9
|
+
- Декларативное определение маршрутов через декораторы.
|
10
|
+
- Типизированные параметры запросов (body, query, params).
|
11
|
+
- Поддержка middleware до и после обработки запроса.
|
12
|
+
- Валидация входящих данных.
|
13
|
+
- Поддержка всех HTTP методов (GET, POST, PUT, DELETE и т.д.).
|
14
|
+
|
7
15
|
## Установка
|
8
16
|
|
9
17
|
```bash
|
@@ -22,6 +30,202 @@ npm install @e22m4u/ts-rest-router
|
|
22
30
|
}
|
23
31
|
```
|
24
32
|
|
33
|
+
## Базовое использование
|
34
|
+
|
35
|
+
Создание контроллера
|
36
|
+
|
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,
|
66
|
+
) {
|
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
|
+
// ...
|
86
|
+
}
|
87
|
+
}
|
88
|
+
```
|
89
|
+
|
90
|
+
Регистрация контроллеров и запуск сервера
|
91
|
+
|
92
|
+
```ts
|
93
|
+
import http from 'http';
|
94
|
+
import {RestRouter} from '@e22m4u/ts-rest-router';
|
95
|
+
|
96
|
+
// создание роутера и регистрация контроллеров
|
97
|
+
const router = new RestRouter();
|
98
|
+
router.registerController(UserController);
|
99
|
+
router.registerController(ProductController);
|
100
|
+
|
101
|
+
// создание сервера и регистрация обработчика запросов
|
102
|
+
const server = new http.Server();
|
103
|
+
server.on('request', router.requestListener);
|
104
|
+
|
105
|
+
// запуск сервера
|
106
|
+
server.listen('8080', '0.0.0.0', () => {
|
107
|
+
console.log(`Server is running on http://localhost:8080`);
|
108
|
+
});
|
109
|
+
```
|
110
|
+
|
111
|
+
## Декораторы
|
112
|
+
|
113
|
+
Контроллер и методы
|
114
|
+
|
115
|
+
- `@controller` - определяет класс как контроллер
|
116
|
+
- `@action` - базовый декоратор для методов
|
117
|
+
- `@get` - GET запросы
|
118
|
+
- `@post` - POST запросы
|
119
|
+
- `@put` - PUT запросы
|
120
|
+
- `@patch` - PATCH запросы
|
121
|
+
- `@del` - DELETE запросы
|
122
|
+
|
123
|
+
Параметры запроса
|
124
|
+
|
125
|
+
- `@param` - один параметр URL
|
126
|
+
- `@params` - все параметры URL как объект
|
127
|
+
- `@query` - один query параметр
|
128
|
+
- `@queries` - все query параметры как объект
|
129
|
+
- `@body` - тело запроса
|
130
|
+
- `@bodyParam` - конкретное поле из тела запроса
|
131
|
+
- `@header` - один заголовок
|
132
|
+
- `@headers` - все заголовки как объект
|
133
|
+
- `@cookie` - одна cookie
|
134
|
+
- `@cookies` - все cookies как объект
|
135
|
+
- `@requestContext` - доступ к контексту запроса
|
136
|
+
- `@requestData` - универсальный декоратор для доступа к данным запроса
|
137
|
+
|
138
|
+
#### `@controller(options?: ControllerOptions)`
|
139
|
+
|
140
|
+
Декоратор для определения класса как REST API контроллера.
|
141
|
+
|
142
|
+
```typescript
|
143
|
+
@controller()
|
144
|
+
class UserController {
|
145
|
+
// методы контроллера
|
146
|
+
}
|
147
|
+
```
|
148
|
+
|
149
|
+
Дополнительные параметры декоратора.
|
150
|
+
|
151
|
+
```typescript
|
152
|
+
@controller({
|
153
|
+
path: '/api'
|
154
|
+
before: [authMiddleware],
|
155
|
+
after: [loggerMiddleware],
|
156
|
+
})
|
157
|
+
class UserController {
|
158
|
+
// методы контроллера
|
159
|
+
}
|
160
|
+
```
|
161
|
+
|
162
|
+
### `@get(path: string, options?: ActionOptions)`
|
163
|
+
|
164
|
+
Декоратор для определения метода GET.
|
165
|
+
|
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}};
|
179
|
+
}
|
180
|
+
}
|
181
|
+
```
|
182
|
+
|
183
|
+
Дополнительные параметры декоратора.
|
184
|
+
|
185
|
+
```typescript
|
186
|
+
@controller()
|
187
|
+
class UserController {
|
188
|
+
@get('/users', {
|
189
|
+
before: [authMiddleware],
|
190
|
+
after: [loggerMiddleware],
|
191
|
+
})
|
192
|
+
async getUsers() {
|
193
|
+
return {users: []};
|
194
|
+
}
|
195
|
+
}
|
196
|
+
```
|
197
|
+
|
198
|
+
### `@requestContext(propertyName?: string)`
|
199
|
+
|
200
|
+
Декоратор для доступа к контексту запроса.
|
201
|
+
|
202
|
+
```typescript
|
203
|
+
@controller()
|
204
|
+
class UserController {
|
205
|
+
@get('/users')
|
206
|
+
getUsers(
|
207
|
+
@requestContext('req') req: IncomingMessage,
|
208
|
+
@requestContext('res') res: ServerResponse,
|
209
|
+
) {
|
210
|
+
// Доступ к оригинальным объектам запроса/ответа
|
211
|
+
}
|
212
|
+
}
|
213
|
+
```
|
214
|
+
|
215
|
+
Допустимые свойства:
|
216
|
+
|
217
|
+
- `container: ServiceContainer` экземпляр [сервис-контейнера](https://npmjs.com/package/@e22m4u/js-service)
|
218
|
+
- `req: IncomingMessage` нативный поток входящего запроса
|
219
|
+
- `res: ServerResponse` нативный поток ответа сервера
|
220
|
+
- `params: ParsedParams` объект ключ-значение с параметрами пути
|
221
|
+
- `query: ParsedQuery` объект ключ-значение с параметрами строки запроса
|
222
|
+
- `headers: ParsedHeaders` объект ключ-значение с заголовками запроса
|
223
|
+
- `cookie: ParsedCookie` объект ключ-значение разобранного заголовка `cookie`
|
224
|
+
- `method: string` метод запроса в верхнем регистре, например `GET`, `POST` и т.д.
|
225
|
+
- `path: string` путь включающий строку запроса, например `/myPath?foo=bar`
|
226
|
+
- `pathname: string` путь запроса, например `/myMath`
|
227
|
+
- `body: unknown` тело запроса
|
228
|
+
|
25
229
|
## Отладка
|
26
230
|
|
27
231
|
Установка переменной `DEBUG` включает вывод логов.
|
package/README.md
CHANGED
@@ -4,6 +4,14 @@
|
|
4
4
|
|
5
5
|
Controllers-based REST router implementation for TypeScript.
|
6
6
|
|
7
|
+
#### Key Features
|
8
|
+
|
9
|
+
- Declarative route definition using decorators.
|
10
|
+
- Typed request parameters (body, query, params).
|
11
|
+
- Pre and post request middleware support.
|
12
|
+
- Input data validation.
|
13
|
+
- Support for all HTTP methods (GET, POST, PUT, DELETE, etc.).
|
14
|
+
|
7
15
|
## Installation
|
8
16
|
|
9
17
|
```bash
|
@@ -22,6 +30,204 @@ options to your `tsconfig.json` file.
|
|
22
30
|
}
|
23
31
|
```
|
24
32
|
|
33
|
+
## Basic Usage
|
34
|
+
|
35
|
+
Creating a controller.
|
36
|
+
|
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
|
+
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
|
+
// ...
|
86
|
+
}
|
87
|
+
}
|
88
|
+
```
|
89
|
+
|
90
|
+
Registering controllers and starting the server.
|
91
|
+
|
92
|
+
```ts
|
93
|
+
import http from 'http';
|
94
|
+
import {RestRouter} from '@e22m4u/ts-rest-router';
|
95
|
+
|
96
|
+
// create router and register controllers
|
97
|
+
const router = new RestRouter();
|
98
|
+
router.registerController(UserController);
|
99
|
+
router.registerController(ProductController);
|
100
|
+
|
101
|
+
// create server and register request handler
|
102
|
+
const server = new http.Server();
|
103
|
+
server.on('request', router.requestListener);
|
104
|
+
|
105
|
+
// start server
|
106
|
+
server.listen('8080', '0.0.0.0', () => {
|
107
|
+
console.log(`Server is running on http://localhost:8080`);
|
108
|
+
});
|
109
|
+
```
|
110
|
+
|
111
|
+
## Decorators
|
112
|
+
|
113
|
+
Controller and methods:
|
114
|
+
|
115
|
+
- `@controller` - defines a class as a controller
|
116
|
+
- `@action` - base decorator for methods
|
117
|
+
- `@get` - GET requests
|
118
|
+
- `@post` - POST requests
|
119
|
+
- `@put` - PUT requests
|
120
|
+
- `@patch` - PATCH requests
|
121
|
+
- `@del` - DELETE requests
|
122
|
+
|
123
|
+
Request parameters:
|
124
|
+
|
125
|
+
- `@param` - single URL parameter
|
126
|
+
- `@params` - all URL parameters as an object
|
127
|
+
- `@query` - single query parameter
|
128
|
+
- `@queries` - all query parameters as an object
|
129
|
+
- `@body` - request body
|
130
|
+
- `@bodyParam` - specific field from request body
|
131
|
+
- `@header` - single header
|
132
|
+
- `@headers` - all headers as an object
|
133
|
+
- `@cookie` - single cookie
|
134
|
+
- `@cookies` - all cookies as an object
|
135
|
+
- `@requestContext` - access to request context
|
136
|
+
- `@requestData` - universal decorator for accessing request data
|
137
|
+
|
138
|
+
#### `@controller(options?: ControllerOptions)`
|
139
|
+
|
140
|
+
Decorator for defining a class as a REST API controller.
|
141
|
+
|
142
|
+
```ts
|
143
|
+
@controller()
|
144
|
+
class UserController {
|
145
|
+
// controller methods
|
146
|
+
}
|
147
|
+
```
|
148
|
+
|
149
|
+
Additional decorator parameters.
|
150
|
+
|
151
|
+
```ts
|
152
|
+
@controller({
|
153
|
+
path: '/api'
|
154
|
+
before: [authMiddleware],
|
155
|
+
after: [loggerMiddleware],
|
156
|
+
})
|
157
|
+
class UserController {
|
158
|
+
// controller methods
|
159
|
+
}
|
160
|
+
```
|
161
|
+
|
162
|
+
### `@get(path: string, options?: ActionOptions)`
|
163
|
+
|
164
|
+
Decorator for defining GET method.
|
165
|
+
|
166
|
+
```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}};
|
179
|
+
}
|
180
|
+
}
|
181
|
+
```
|
182
|
+
|
183
|
+
Additional decorator parameters.
|
184
|
+
|
185
|
+
```ts
|
186
|
+
@controller()
|
187
|
+
class UserController {
|
188
|
+
@get('/users', {
|
189
|
+
before: [authMiddleware],
|
190
|
+
after: [loggerMiddleware],
|
191
|
+
})
|
192
|
+
async getUsers() {
|
193
|
+
return {users: []};
|
194
|
+
}
|
195
|
+
}
|
196
|
+
```
|
197
|
+
|
198
|
+
### `@requestContext(propertyName?: string)`
|
199
|
+
|
200
|
+
Decorator for accessing request context.
|
201
|
+
|
202
|
+
```ts
|
203
|
+
import {IncomingMessage, ServerResponse} from 'http';
|
204
|
+
|
205
|
+
@controller()
|
206
|
+
class UserController {
|
207
|
+
@get('/users')
|
208
|
+
getUsers(
|
209
|
+
@requestContext('req') req: IncomingMessage,
|
210
|
+
@requestContext('res') res: ServerResponse,
|
211
|
+
) {
|
212
|
+
// Access to original request/response objects
|
213
|
+
}
|
214
|
+
}
|
215
|
+
```
|
216
|
+
|
217
|
+
Available properties:
|
218
|
+
|
219
|
+
- `container: ServiceContainer` instance of [service container](https://npmjs.com/package/@e22m4u/js-service)
|
220
|
+
- `req: IncomingMessage` native incoming request stream
|
221
|
+
- `res: ServerResponse` native server response stream
|
222
|
+
- `params: ParsedParams` key-value object with path parameters
|
223
|
+
- `query: ParsedQuery` key-value object with query string parameters
|
224
|
+
- `headers: ParsedHeaders` key-value object with request headers
|
225
|
+
- `cookie: ParsedCookie` key-value object of parsed `cookie` header
|
226
|
+
- `method: string` request method in uppercase, e.g. `GET`, `POST`, etc.
|
227
|
+
- `path: string` path including query string, e.g. `/myPath?foo=bar`
|
228
|
+
- `pathname: string` request path, e.g. `/myMath`
|
229
|
+
- `body: unknown` request body
|
230
|
+
|
25
231
|
## Debugging
|
26
232
|
|
27
233
|
Set the `DEBUG` variable to enable log output.
|
package/dist/cjs/index.cjs
CHANGED
@@ -29,8 +29,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
29
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
30
30
|
|
31
31
|
// dist/esm/index.js
|
32
|
-
var
|
33
|
-
__export(
|
32
|
+
var index_exports = {};
|
33
|
+
__export(index_exports, {
|
34
34
|
ACTIONS_METADATA_KEY: () => ACTIONS_METADATA_KEY,
|
35
35
|
ActionReflector: () => ActionReflector,
|
36
36
|
CONTROLLER_METADATA_KEY: () => CONTROLLER_METADATA_KEY,
|
@@ -69,7 +69,7 @@ __export(esm_exports, {
|
|
69
69
|
response: () => response,
|
70
70
|
toCamelCase: () => toCamelCase
|
71
71
|
});
|
72
|
-
module.exports = __toCommonJS(
|
72
|
+
module.exports = __toCommonJS(index_exports);
|
73
73
|
|
74
74
|
// dist/esm/utils/capitalize.js
|
75
75
|
function capitalize(input) {
|
@@ -176,11 +176,7 @@ function action(options) {
|
|
176
176
|
const decoratorType = (0, import_ts_reflector4.getDecoratorTargetType)(target, propertyKey, descriptor);
|
177
177
|
if (decoratorType !== import_ts_reflector3.DecoratorTargetType.INSTANCE_METHOD)
|
178
178
|
throw new Error("@action decorator is only supported on an instance method.");
|
179
|
-
|
180
|
-
...options,
|
181
|
-
propertyKey
|
182
|
-
};
|
183
|
-
ActionReflector.setMetadata(metadata, target.constructor, propertyKey);
|
179
|
+
ActionReflector.setMetadata({ ...options, propertyKey }, target.constructor, propertyKey);
|
184
180
|
};
|
185
181
|
}
|
186
182
|
__name(action, "action");
|
@@ -238,11 +234,7 @@ function controller(options) {
|
|
238
234
|
const decoratorType = (0, import_ts_reflector8.getDecoratorTargetType)(target);
|
239
235
|
if (decoratorType !== import_ts_reflector7.DecoratorTargetType.CONSTRUCTOR)
|
240
236
|
throw new Error("@controller decorator is only supported on a class.");
|
241
|
-
|
242
|
-
...options,
|
243
|
-
className: target.name
|
244
|
-
};
|
245
|
-
ControllerReflector.setMetadata(metadata, target);
|
237
|
+
ControllerReflector.setMetadata({ ...options, className: target.name }, target);
|
246
238
|
};
|
247
239
|
}
|
248
240
|
__name(controller, "controller");
|
@@ -296,23 +288,23 @@ __name(_RequestDataReflector, "RequestDataReflector");
|
|
296
288
|
var RequestDataReflector = _RequestDataReflector;
|
297
289
|
|
298
290
|
// dist/esm/decorators/request-data/request-data-decorator.js
|
299
|
-
function requestData(
|
291
|
+
function requestData(options) {
|
300
292
|
return function(target, propertyKey, indexOrDescriptor) {
|
301
293
|
const decoratorType = (0, import_ts_reflector12.getDecoratorTargetType)(target, propertyKey, indexOrDescriptor);
|
302
294
|
if (decoratorType !== import_ts_reflector11.DecoratorTargetType.INSTANCE_METHOD_PARAMETER)
|
303
295
|
throw new Error("@requestData decorator is only supported on an instance method parameter.");
|
304
|
-
RequestDataReflector.setMetadata(
|
296
|
+
RequestDataReflector.setMetadata(options, target.constructor, indexOrDescriptor, propertyKey);
|
305
297
|
};
|
306
298
|
}
|
307
299
|
__name(requestData, "requestData");
|
308
|
-
function
|
300
|
+
function createRequestDataDecoratorWithSource(source) {
|
309
301
|
return function() {
|
310
302
|
const schema = { type: import_ts_data_schema.DataType.OBJECT };
|
311
303
|
return requestData({ schema, source });
|
312
304
|
};
|
313
305
|
}
|
314
|
-
__name(
|
315
|
-
function
|
306
|
+
__name(createRequestDataDecoratorWithSource, "createRequestDataDecoratorWithSource");
|
307
|
+
function createRequestDataPropertyDecoratorWithSource(source) {
|
316
308
|
return function(propertyKey, schemaOrType) {
|
317
309
|
const properties = {};
|
318
310
|
const rootSchema = { type: import_ts_data_schema.DataType.OBJECT };
|
@@ -330,16 +322,16 @@ function createPropertyDecorator(source) {
|
|
330
322
|
});
|
331
323
|
};
|
332
324
|
}
|
333
|
-
__name(
|
334
|
-
var params =
|
335
|
-
var param =
|
336
|
-
var queries =
|
337
|
-
var query =
|
338
|
-
var headers =
|
339
|
-
var header =
|
340
|
-
var cookies =
|
341
|
-
var cookie =
|
342
|
-
var bodyParam =
|
325
|
+
__name(createRequestDataPropertyDecoratorWithSource, "createRequestDataPropertyDecoratorWithSource");
|
326
|
+
var params = createRequestDataDecoratorWithSource(RequestDataSource.PARAMS);
|
327
|
+
var param = createRequestDataPropertyDecoratorWithSource(RequestDataSource.PARAMS);
|
328
|
+
var queries = createRequestDataDecoratorWithSource(RequestDataSource.QUERY);
|
329
|
+
var query = createRequestDataPropertyDecoratorWithSource(RequestDataSource.QUERY);
|
330
|
+
var headers = createRequestDataDecoratorWithSource(RequestDataSource.HEADERS);
|
331
|
+
var header = createRequestDataPropertyDecoratorWithSource(RequestDataSource.HEADERS);
|
332
|
+
var cookies = createRequestDataDecoratorWithSource(RequestDataSource.COOKIE);
|
333
|
+
var cookie = createRequestDataPropertyDecoratorWithSource(RequestDataSource.COOKIE);
|
334
|
+
var bodyParam = createRequestDataPropertyDecoratorWithSource(RequestDataSource.BODY);
|
343
335
|
function body(schemaOrType) {
|
344
336
|
let schema;
|
345
337
|
if (typeof schemaOrType === "object") {
|
@@ -393,13 +385,12 @@ __name(_RequestContextReflector, "RequestContextReflector");
|
|
393
385
|
var RequestContextReflector = _RequestContextReflector;
|
394
386
|
|
395
387
|
// dist/esm/decorators/request-context/request-context-decorator.js
|
396
|
-
function requestContext(
|
388
|
+
function requestContext(propertyName) {
|
397
389
|
return function(target, propertyKey, indexOrDescriptor) {
|
398
390
|
const decoratorType = (0, import_ts_reflector16.getDecoratorTargetType)(target, propertyKey, indexOrDescriptor);
|
399
391
|
if (decoratorType !== import_ts_reflector15.DecoratorTargetType.INSTANCE_METHOD_PARAMETER)
|
400
392
|
throw new Error("@requestContext decorator is only supported on an instance method parameter.");
|
401
|
-
|
402
|
-
RequestContextReflector.setMetadata(metadata, target.constructor, indexOrDescriptor, propertyKey);
|
393
|
+
RequestContextReflector.setMetadata({ property: propertyName }, target.constructor, indexOrDescriptor, propertyKey);
|
403
394
|
};
|
404
395
|
}
|
405
396
|
__name(requestContext, "requestContext");
|
@@ -12,42 +12,41 @@ export type ActionOptions = Flatten<Omit<ActionMetadata, 'propertyKey'>>;
|
|
12
12
|
*/
|
13
13
|
export declare function action<T extends object>(options: ActionOptions): (target: Prototype<T>, propertyKey: string, descriptor: PropertyDescriptor) => void;
|
14
14
|
/**
|
15
|
-
* Action
|
15
|
+
* Action method options.
|
16
16
|
*/
|
17
|
-
type
|
17
|
+
export type ActionMethodOptions = Flatten<Omit<ActionOptions, 'method' | 'path'>>;
|
18
18
|
/**
|
19
19
|
* Get decorator.
|
20
20
|
*
|
21
21
|
* @param path
|
22
22
|
* @param options
|
23
23
|
*/
|
24
|
-
export declare const get: (path: string, options?:
|
24
|
+
export declare const get: (path: string, options?: ActionMethodOptions) => (target: Prototype<object>, propertyKey: string, descriptor: PropertyDescriptor) => void;
|
25
25
|
/**
|
26
26
|
* Post decorator.
|
27
27
|
*
|
28
28
|
* @param path
|
29
29
|
* @param options
|
30
30
|
*/
|
31
|
-
export declare const post: (path: string, options?:
|
31
|
+
export declare const post: (path: string, options?: ActionMethodOptions) => (target: Prototype<object>, propertyKey: string, descriptor: PropertyDescriptor) => void;
|
32
32
|
/**
|
33
33
|
* Put decorator.
|
34
34
|
*
|
35
35
|
* @param path
|
36
36
|
* @param options
|
37
37
|
*/
|
38
|
-
export declare const put: (path: string, options?:
|
38
|
+
export declare const put: (path: string, options?: ActionMethodOptions) => (target: Prototype<object>, propertyKey: string, descriptor: PropertyDescriptor) => void;
|
39
39
|
/**
|
40
40
|
* Patch decorator.
|
41
41
|
*
|
42
42
|
* @param path
|
43
43
|
* @param options
|
44
44
|
*/
|
45
|
-
export declare const patch: (path: string, options?:
|
45
|
+
export declare const patch: (path: string, options?: ActionMethodOptions) => (target: Prototype<object>, propertyKey: string, descriptor: PropertyDescriptor) => void;
|
46
46
|
/**
|
47
47
|
* Del decorator.
|
48
48
|
*
|
49
49
|
* @param path
|
50
50
|
* @param options
|
51
51
|
*/
|
52
|
-
export declare const del: (path: string, options?:
|
53
|
-
export {};
|
52
|
+
export declare const del: (path: string, options?: ActionMethodOptions) => (target: Prototype<object>, propertyKey: string, descriptor: PropertyDescriptor) => void;
|
@@ -12,11 +12,7 @@ export function action(options) {
|
|
12
12
|
const decoratorType = getDecoratorTargetType(target, propertyKey, descriptor);
|
13
13
|
if (decoratorType !== DecoratorTargetType.INSTANCE_METHOD)
|
14
14
|
throw new Error('@action decorator is only supported on an instance method.');
|
15
|
-
|
16
|
-
...options,
|
17
|
-
propertyKey,
|
18
|
-
};
|
19
|
-
ActionReflector.setMetadata(metadata, target.constructor, propertyKey);
|
15
|
+
ActionReflector.setMetadata({ ...options, propertyKey }, target.constructor, propertyKey);
|
20
16
|
};
|
21
17
|
}
|
22
18
|
/**
|
@@ -13,47 +13,47 @@ import { HttpMethod } from '@e22m4u/js-trie-router';
|
|
13
13
|
import { ActionReflector } from './action-reflector.js';
|
14
14
|
describe('action', function () {
|
15
15
|
it('sets given options to the target metadata', function () {
|
16
|
-
const
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
16
|
+
const options = {
|
17
|
+
method: HttpMethod.GET,
|
18
|
+
path: 'myPath',
|
19
|
+
before: () => undefined,
|
20
|
+
after: () => undefined,
|
21
|
+
customOption: 'customOption',
|
22
|
+
};
|
21
23
|
class Target {
|
22
24
|
method() { }
|
23
25
|
}
|
24
26
|
__decorate([
|
25
|
-
action(
|
27
|
+
action(options),
|
26
28
|
__metadata("design:type", Function),
|
27
29
|
__metadata("design:paramtypes", []),
|
28
30
|
__metadata("design:returntype", void 0)
|
29
31
|
], Target.prototype, "method", null);
|
30
32
|
const res = ActionReflector.getMetadata(Target);
|
31
33
|
expect(res.get('method')).to.be.eql({
|
34
|
+
...options,
|
32
35
|
propertyKey: 'method',
|
33
|
-
method,
|
34
|
-
path,
|
35
|
-
before,
|
36
|
-
after,
|
37
|
-
customOption,
|
38
36
|
});
|
39
37
|
});
|
40
38
|
it('overrides a given "propertyKey" option by the target method name', function () {
|
41
|
-
const
|
42
|
-
|
39
|
+
const options = {
|
40
|
+
propertyKey: 'myMethod',
|
41
|
+
method: HttpMethod.GET,
|
42
|
+
path: 'myPath',
|
43
|
+
};
|
43
44
|
class Target {
|
44
45
|
method() { }
|
45
46
|
}
|
46
47
|
__decorate([
|
47
|
-
action(
|
48
|
+
action(options),
|
48
49
|
__metadata("design:type", Function),
|
49
50
|
__metadata("design:paramtypes", []),
|
50
51
|
__metadata("design:returntype", void 0)
|
51
52
|
], Target.prototype, "method", null);
|
52
53
|
const res = ActionReflector.getMetadata(Target);
|
53
54
|
expect(res.get('method')).to.be.eql({
|
55
|
+
...options,
|
54
56
|
propertyKey: 'method',
|
55
|
-
method,
|
56
|
-
path,
|
57
57
|
});
|
58
58
|
});
|
59
59
|
});
|