0
# Controller Decorators
1
2
Decorator-based routing system for defining controllers and HTTP endpoints. Provides method decorators for all HTTP verbs and parameter decorators for request data extraction with full TypeScript support.
3
4
## Capabilities
5
6
### Controller Decorator
7
8
Class decorator for defining controllers with path routing and middleware support.
9
10
```typescript { .api }
11
/**
12
* Marks a class as a controller with the specified route path
13
* @param path - Base path for all routes in this controller
14
* @param middleware - Optional middleware to apply to all routes in this controller
15
*/
16
function controller(path: string, ...middleware: Middleware[]): ClassDecorator;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { controller, httpGet, BaseHttpController } from "inversify-express-utils";
23
24
@controller("/users")
25
class UserController extends BaseHttpController {
26
// Routes will be prefixed with /users
27
}
28
29
@controller("/api/products", authMiddleware, loggingMiddleware)
30
class ProductController extends BaseHttpController {
31
// Routes prefixed with /api/products and protected by middleware
32
}
33
```
34
35
### HTTP Method Decorators
36
37
Method decorators for defining HTTP endpoints with specific verbs.
38
39
```typescript { .api }
40
/**
41
* Defines a GET endpoint
42
* @param path - Route path relative to controller
43
* @param middleware - Optional middleware for this specific route
44
*/
45
function httpGet(path: string, ...middleware: Middleware[]): MethodDecorator;
46
47
/**
48
* Defines a POST endpoint
49
* @param path - Route path relative to controller
50
* @param middleware - Optional middleware for this specific route
51
*/
52
function httpPost(path: string, ...middleware: Middleware[]): MethodDecorator;
53
54
/**
55
* Defines a PUT endpoint
56
* @param path - Route path relative to controller
57
* @param middleware - Optional middleware for this specific route
58
*/
59
function httpPut(path: string, ...middleware: Middleware[]): MethodDecorator;
60
61
/**
62
* Defines a PATCH endpoint
63
* @param path - Route path relative to controller
64
* @param middleware - Optional middleware for this specific route
65
*/
66
function httpPatch(path: string, ...middleware: Middleware[]): MethodDecorator;
67
68
/**
69
* Defines a DELETE endpoint
70
* @param path - Route path relative to controller
71
* @param middleware - Optional middleware for this specific route
72
*/
73
function httpDelete(path: string, ...middleware: Middleware[]): MethodDecorator;
74
75
/**
76
* Defines a HEAD endpoint
77
* @param path - Route path relative to controller
78
* @param middleware - Optional middleware for this specific route
79
*/
80
function httpHead(path: string, ...middleware: Middleware[]): MethodDecorator;
81
82
/**
83
* Defines an OPTIONS endpoint
84
* @param path - Route path relative to controller
85
* @param middleware - Optional middleware for this specific route
86
*/
87
function httpOptions(path: string, ...middleware: Middleware[]): MethodDecorator;
88
89
/**
90
* Defines an endpoint that responds to all HTTP methods
91
* @param path - Route path relative to controller
92
* @param middleware - Optional middleware for this specific route
93
*/
94
function all(path: string, ...middleware: Middleware[]): MethodDecorator;
95
96
/**
97
* Generic HTTP method decorator
98
* @param method - HTTP verb enum value
99
* @param path - Route path relative to controller
100
* @param middleware - Optional middleware for this specific route
101
*/
102
function httpMethod(
103
method: HTTP_VERBS_ENUM,
104
path: string,
105
...middleware: Middleware[]
106
): MethodDecorator;
107
```
108
109
**Usage Examples:**
110
111
```typescript
112
@controller("/users")
113
class UserController extends BaseHttpController {
114
@httpGet("/:id")
115
getUser(@requestParam("id") id: string) {
116
return this.ok({ id, name: "John Doe" });
117
}
118
119
@httpPost("/", validationMiddleware)
120
createUser(@requestBody() userData: any) {
121
return this.created("/users/123", userData);
122
}
123
124
@httpPut("/:id")
125
updateUser(@requestParam("id") id: string, @requestBody() userData: any) {
126
return this.ok({ id, ...userData });
127
}
128
129
@httpDelete("/:id", adminOnlyMiddleware)
130
deleteUser(@requestParam("id") id: string) {
131
return this.ok();
132
}
133
}
134
```
135
136
### Parameter Decorators
137
138
Parameter decorators for extracting data from HTTP requests.
139
140
```typescript { .api }
141
/**
142
* Injects the entire Express request object
143
*/
144
function request(): ParameterDecorator;
145
146
/**
147
* Injects the entire Express response object
148
*/
149
function response(): ParameterDecorator;
150
151
/**
152
* Injects Express next function
153
*/
154
function next(): ParameterDecorator;
155
156
/**
157
* Injects route parameters
158
* @param paramName - Specific parameter name to extract, or omit for all params
159
*/
160
function requestParam(paramName?: string): ParameterDecorator;
161
162
/**
163
* Injects query string parameters
164
* @param queryParamName - Specific query parameter name to extract, or omit for all query params
165
*/
166
function queryParam(queryParamName?: string): ParameterDecorator;
167
168
/**
169
* Injects the request body
170
*/
171
function requestBody(): ParameterDecorator;
172
173
/**
174
* Injects request headers
175
* @param headerName - Specific header name to extract, or omit for all headers
176
*/
177
function requestHeaders(headerName?: string): ParameterDecorator;
178
179
/**
180
* Injects cookies
181
* @param cookieName - Specific cookie name to extract, or omit for all cookies
182
*/
183
function cookies(cookieName?: string): ParameterDecorator;
184
185
/**
186
* Injects the authenticated user principal
187
*/
188
function principal(): ParameterDecorator;
189
190
/**
191
* Generic parameter decorator factory
192
* @param type - Parameter type enum value
193
* @param parameterName - Optional parameter name
194
*/
195
function params(type: PARAMETER_TYPE, parameterName?: string | symbol): ParameterDecorator;
196
```
197
198
**Usage Examples:**
199
200
```typescript
201
@controller("/users")
202
class UserController extends BaseHttpController {
203
@httpGet("/:id")
204
getUser(
205
@requestParam("id") userId: string,
206
@queryParam("include") include: string,
207
@requestHeaders("authorization") auth: string
208
) {
209
return this.ok({ userId, include, isAuthenticated: !!auth });
210
}
211
212
@httpPost("/")
213
createUser(
214
@requestBody() userData: CreateUserDto,
215
@principal() user: Principal,
216
@request() req: Request
217
) {
218
console.log("Creating user:", userData);
219
console.log("Current user:", user.details);
220
return this.created(`/users/${Date.now()}`, userData);
221
}
222
223
@httpGet("/")
224
getUsers(
225
@queryParam() query: any,
226
@requestHeaders() headers: any,
227
@cookies("session") sessionId: string
228
) {
229
return this.ok({
230
filters: query,
231
userAgent: headers["user-agent"],
232
session: sessionId
233
});
234
}
235
}
236
```
237
238
### Middleware Decorator
239
240
Decorator for applying middleware to controllers or methods.
241
242
```typescript { .api }
243
/**
244
* Applies middleware to a controller class or method
245
* @param middleware - Middleware functions or service identifiers to apply
246
*/
247
function withMiddleware(...middleware: Middleware[]): ClassDecorator | MethodDecorator;
248
```
249
250
**Usage Examples:**
251
252
```typescript
253
@controller("/admin")
254
@withMiddleware(authMiddleware, adminMiddleware)
255
class AdminController extends BaseHttpController {
256
@httpGet("/users")
257
@withMiddleware(cacheMiddleware)
258
getUsers() {
259
return this.ok(["user1", "user2"]);
260
}
261
}
262
```
263
264
### HTTP Context Injection
265
266
Special injection decorator for accessing HTTP context.
267
268
```typescript { .api }
269
/**
270
* Injects HTTP context into controller properties or method parameters
271
*/
272
const injectHttpContext: <T = unknown>(
273
target: DecoratorTarget,
274
targetKey?: string | symbol,
275
indexOrPropertyDescriptor?: number | TypedPropertyDescriptor<T>
276
) => void;
277
```
278
279
**Usage Examples:**
280
281
```typescript
282
@controller("/context")
283
class ContextController {
284
@injectHttpContext
285
private httpContext: HttpContext;
286
287
@httpGet("/info")
288
getContextInfo() {
289
return {
290
hasContainer: !!this.httpContext.container,
291
userAuthenticated: this.httpContext.user.isAuthenticated(),
292
requestPath: this.httpContext.request.path
293
};
294
}
295
}
296
```
297
298
### Supporting Types
299
300
```typescript { .api }
301
type HandlerDecorator = (
302
target: DecoratorTarget,
303
key: string,
304
value: unknown
305
) => void;
306
307
type DecoratorTarget<T = unknown> = ConstructorFunction<T> | Prototype<T>;
308
309
type Middleware = interfaces.ServiceIdentifier | RequestHandler;
310
```