@meghjs/mcp 0.0.0-stage → 0.7.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.
- package/LICENSE +21 -0
- package/README.md +141 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +37 -0
- package/dist/docs/advanced/caching.md +72 -0
- package/dist/docs/advanced/database.md +328 -0
- package/dist/docs/advanced/events.md +169 -0
- package/dist/docs/advanced/file-uploads.md +141 -0
- package/dist/docs/advanced/health.md +81 -0
- package/dist/docs/advanced/logging.md +96 -0
- package/dist/docs/advanced/mail.md +439 -0
- package/dist/docs/advanced/orm/migrations.md +210 -0
- package/dist/docs/advanced/orm/models.md +291 -0
- package/dist/docs/advanced/orm/queries.md +169 -0
- package/dist/docs/advanced/orm/query-builder.md +120 -0
- package/dist/docs/advanced/orm/relations.md +179 -0
- package/dist/docs/advanced/orm/seeding.md +129 -0
- package/dist/docs/advanced/orm.md +145 -0
- package/dist/docs/advanced/plugins.md +90 -0
- package/dist/docs/advanced/queue.md +217 -0
- package/dist/docs/advanced/scheduler.md +253 -0
- package/dist/docs/advanced/testing.md +257 -0
- package/dist/docs/advanced/views.md +335 -0
- package/dist/docs/ai/mcp.md +162 -0
- package/dist/docs/cli/basic.md +133 -0
- package/dist/docs/cli/database.md +112 -0
- package/dist/docs/cli/generators.md +605 -0
- package/dist/docs/cli/scaffold/auth.md +172 -0
- package/dist/docs/cli/scaffold/domains.md +224 -0
- package/dist/docs/cli/scaffold/index.md +77 -0
- package/dist/docs/cli/scaffold/rbac.md +118 -0
- package/dist/docs/cli/scaffold/templates.md +235 -0
- package/dist/docs/core-concept/authentication.md +162 -0
- package/dist/docs/core-concept/configuration.md +268 -0
- package/dist/docs/core-concept/controller.md +350 -0
- package/dist/docs/core-concept/dependency-injection.md +213 -0
- package/dist/docs/core-concept/error-handling.md +185 -0
- package/dist/docs/core-concept/middleware.md +143 -0
- package/dist/docs/core-concept/request-context.md +110 -0
- package/dist/docs/core-concept/validation.md +355 -0
- package/dist/docs/getting-started/application.md +233 -0
- package/dist/docs/getting-started/installation.md +166 -0
- package/dist/docs/getting-started/introduction.md +136 -0
- package/dist/docs/getting-started/upgrading-0.4.md +125 -0
- package/dist/docs/getting-started/upgrading-0.5.md +293 -0
- package/dist/docs/getting-started/upgrading-0.6.md +251 -0
- package/dist/docs/getting-started/upgrading-0.7.md +225 -0
- package/dist/docs/getting-started/upgrading-megh.md +91 -0
- package/dist/docs/getting-started/upgrading-next.md +12 -0
- package/dist/docs/getting-started/upgrading.md +137 -0
- package/dist/docs/getting-started/usage.md +194 -0
- package/dist/docs/index.md +58 -0
- package/dist/docs/microservices/openapi.md +387 -0
- package/dist/docs/microservices/websocket.md +165 -0
- package/dist/docs/production/deployment.md +256 -0
- package/dist/docs/production/security.md +307 -0
- package/dist/docs/reference/api.md +999 -0
- package/dist/docs/reference/faq.md +227 -0
- package/dist/docs/reference/versioning.md +105 -0
- package/dist/docs.d.ts +30 -0
- package/dist/docs.js +126 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +22 -0
- package/dist/megh.d.ts +59 -0
- package/dist/megh.js +207 -0
- package/dist/prompts.d.ts +3 -0
- package/dist/prompts.js +47 -0
- package/dist/result.d.ts +18 -0
- package/dist/result.js +48 -0
- package/dist/server.d.ts +17 -0
- package/dist/server.js +40 -0
- package/dist/tools/context.d.ts +11 -0
- package/dist/tools/context.js +2 -0
- package/dist/tools/database.d.ts +8 -0
- package/dist/tools/database.js +58 -0
- package/dist/tools/docs.d.ts +3 -0
- package/dist/tools/docs.js +63 -0
- package/dist/tools/generate.d.ts +10 -0
- package/dist/tools/generate.js +177 -0
- package/dist/tools/project.d.ts +3 -0
- package/dist/tools/project.js +84 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +10 -0
- package/package.json +58 -4
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Error Handling
|
|
3
|
+
description: HTTP exceptions, the default error response, and custom exception filters.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Error Handling
|
|
7
|
+
|
|
8
|
+
Throw an exception anywhere in a request (a controller, a service, a middleware
|
|
9
|
+
or an authorizer) and Megh turns it into a JSON response.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { ApiController, Get, Param, NotFoundException } from '@meghjs/core';
|
|
13
|
+
|
|
14
|
+
@ApiController('/users')
|
|
15
|
+
export class UsersController {
|
|
16
|
+
@Get('/:id')
|
|
17
|
+
async findOne(@Param('id') id: number) {
|
|
18
|
+
const user = await this.users.findByPk(id);
|
|
19
|
+
if (!user) throw new NotFoundException('User not found');
|
|
20
|
+
return user;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{ "code": 404, "status": "Error", "message": "User not found", "data": { "message": "User not found" } }
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## HTTP exceptions
|
|
30
|
+
|
|
31
|
+
| Class | Status | Factory |
|
|
32
|
+
| ------------------------------- | ------ | ------------------------------------- |
|
|
33
|
+
| `BadRequestException` | 400 | `HttpExceptions.badRequest()` |
|
|
34
|
+
| `ValidationErrorException` | 400 | `HttpExceptions.validationError()` |
|
|
35
|
+
| `UnauthorizedException` | 401 | `HttpExceptions.unauthorized()` |
|
|
36
|
+
| `ForbiddenException` | 403 | `HttpExceptions.forbidden()` |
|
|
37
|
+
| `NotFoundException` | 404 | `HttpExceptions.notFound()` |
|
|
38
|
+
| `MethodNotAllowedException` | 405 | `HttpExceptions.methodNotAllowed()` |
|
|
39
|
+
| `NotAcceptableException` | 406 | |
|
|
40
|
+
| `RequestTimeoutException` | 408 | |
|
|
41
|
+
| `ConflictException` | 409 | `HttpExceptions.conflict()` |
|
|
42
|
+
| `GoneException` | 410 | `HttpExceptions.gone()` |
|
|
43
|
+
| `PayloadTooLargeException` | 413 | `HttpExceptions.payloadTooLarge()` |
|
|
44
|
+
| `UnsupportedMediaTypeException` | 415 | `HttpExceptions.unsupportedMediaType()` |
|
|
45
|
+
| `UnprocessableEntityException` | 422 | `HttpExceptions.unprocessableEntity()` |
|
|
46
|
+
| `TooManyRequestsException` | 429 | `HttpExceptions.tooManyRequests()` |
|
|
47
|
+
| `InternalErrorException` | 500 | `HttpExceptions.internalError()` |
|
|
48
|
+
| `NotImplementedException` | 501 | `HttpExceptions.notImplemented()` |
|
|
49
|
+
| `BadGatewayException` | 502 | |
|
|
50
|
+
| `ServiceUnavailableException` | 503 | `HttpExceptions.serviceUnavailable()` |
|
|
51
|
+
| `GatewayTimeoutException` | 504 | |
|
|
52
|
+
| `HttpException` | any | `HttpExceptions.status(code, msg)` |
|
|
53
|
+
|
|
54
|
+
The message can be a string or an object; an object is sent as `data`. The
|
|
55
|
+
second argument sets response headers and keeps the original error as `cause`
|
|
56
|
+
for logs:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
throw new TooManyRequestsException('Slow down', { headers: { 'Retry-After': 30 } });
|
|
60
|
+
throw new ServiceUnavailableException('Payments are down', { cause: err });
|
|
61
|
+
throw new HttpException(402, 'Payment required');
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## The default response
|
|
65
|
+
|
|
66
|
+
Without filters, Megh answers like this:
|
|
67
|
+
|
|
68
|
+
- **HTTP exceptions** keep their status. For 4xx the message and `data` are
|
|
69
|
+
sent. For 5xx they are sent only when `NODE_ENV=development`; otherwise
|
|
70
|
+
the message is `Internal Server Error`.
|
|
71
|
+
- **Validation failures**, from DTOs or the route schema, are a 400 with the
|
|
72
|
+
individual issues in `errors`.
|
|
73
|
+
- **Framework errors** keep their status: malformed JSON (400), body too large
|
|
74
|
+
(413), unsupported content type (415), rate limited (429) and so on.
|
|
75
|
+
- **Unknown routes** are a 404: `Route GET /nope not found`.
|
|
76
|
+
- **Anything else** is a 500. In development the body adds `error` and the
|
|
77
|
+
first lines of `stack`.
|
|
78
|
+
|
|
79
|
+
Errors answered this way are logged: 4xx as warnings, the rest as errors with
|
|
80
|
+
the stack. Replace the logger, or turn it off, with `useErrorLogger`:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
app.useErrorLogger((error, request, response) => {
|
|
84
|
+
if (response.statusCode >= 500) Sentry.captureException(error);
|
|
85
|
+
});
|
|
86
|
+
app.useErrorLogger(false);
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Custom error handler
|
|
90
|
+
|
|
91
|
+
For a quick change, register a function. It sees every error, and
|
|
92
|
+
`response` holds what Megh would send by default:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
app.useErrorHandler((error, { response }) => ({
|
|
96
|
+
success: false,
|
|
97
|
+
message: response.body.message,
|
|
98
|
+
}));
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
What the handler does decides what happens next:
|
|
102
|
+
|
|
103
|
+
| The handler… | Result |
|
|
104
|
+
| -------------------------------------------- | ----------------------------------------------- |
|
|
105
|
+
| returns a value | sent as the body, with `response.statusCode` |
|
|
106
|
+
| calls `reply.code(...)` and returns a value | sent with that status |
|
|
107
|
+
| sends the reply itself (`reply.send(...)`) | nothing else runs |
|
|
108
|
+
| returns an `Error` | replaces the error; the next filter handles it |
|
|
109
|
+
| returns nothing | the next filter, then the default response |
|
|
110
|
+
| throws | logged; the default response is sent |
|
|
111
|
+
|
|
112
|
+
## Exception filters
|
|
113
|
+
|
|
114
|
+
A filter is a class with a `catch(error, ctx)` method, following the same
|
|
115
|
+
rules. `@Catch(...)` limits it to some error classes (subclasses included),
|
|
116
|
+
and its constructor can take services from the container.
|
|
117
|
+
|
|
118
|
+
```ts [src/filters/out-of-stock.filter.ts]
|
|
119
|
+
import { Catch, ConflictException, ExceptionFilter } from '@meghjs/core';
|
|
120
|
+
import { OutOfStockError } from '../errors/out-of-stock.error';
|
|
121
|
+
|
|
122
|
+
// Map a domain error to a 409, then let later filters format it.
|
|
123
|
+
@Catch(OutOfStockError)
|
|
124
|
+
export class OutOfStockFilter implements ExceptionFilter<OutOfStockError> {
|
|
125
|
+
catch(error: OutOfStockError) {
|
|
126
|
+
return new ConflictException(error.message);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
```ts [src/filters/problem-json.filter.ts]
|
|
132
|
+
import { Catch, ErrorContext, ExceptionFilter } from '@meghjs/core';
|
|
133
|
+
|
|
134
|
+
// Answer every error as RFC 9457 problem details.
|
|
135
|
+
@Catch()
|
|
136
|
+
export class ProblemJsonFilter implements ExceptionFilter {
|
|
137
|
+
catch(error: unknown, { reply, request, response }: ErrorContext) {
|
|
138
|
+
reply.type('application/problem+json');
|
|
139
|
+
return {
|
|
140
|
+
type: 'about:blank',
|
|
141
|
+
status: response.statusCode,
|
|
142
|
+
title: response.body.message,
|
|
143
|
+
instance: request.url,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
```ts [src/app.ts]
|
|
150
|
+
app.useExceptionFilters([OutOfStockFilter, ProblemJsonFilter]);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Global filters run in registration order. `ctx.response` is already
|
|
154
|
+
redacted in production, so building on it does not leak 5xx details.
|
|
155
|
+
|
|
156
|
+
### Per controller or route
|
|
157
|
+
|
|
158
|
+
`@UseFilters` applies filters to one controller or one route. They run
|
|
159
|
+
before the global ones: route filters first, then controller filters.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import { ApiController, Post, UseFilters } from '@meghjs/core';
|
|
163
|
+
|
|
164
|
+
@UseFilters(PaymentErrorFilter)
|
|
165
|
+
@ApiController('/payments')
|
|
166
|
+
export class PaymentsController {
|
|
167
|
+
@UseFilters((error, { reply }) => {
|
|
168
|
+
reply.code(409);
|
|
169
|
+
return { message: 'Refund already issued' };
|
|
170
|
+
})
|
|
171
|
+
@Post('/:id/refund')
|
|
172
|
+
refund() {
|
|
173
|
+
// ...
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`useExceptionFilters`, `useErrorHandler` and `@UseFilters` take filter
|
|
179
|
+
classes, filter instances or functions. Register global filters before
|
|
180
|
+
`app.run()`.
|
|
181
|
+
|
|
182
|
+
## Testing
|
|
183
|
+
|
|
184
|
+
`MeghTest` uses the same error handling as `run()`, filters included, so
|
|
185
|
+
tests see the responses production sends.
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Middleware
|
|
3
|
+
description: Creating and applying Megh middleware.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Middleware
|
|
7
|
+
|
|
8
|
+
Middleware runs before your route handler and can inspect or modify the request,
|
|
9
|
+
or reject it outright.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npx megh make:middleware logger
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The command generates:
|
|
16
|
+
|
|
17
|
+
```ts [src/middlewares/logger.middleware.ts]
|
|
18
|
+
import { AppMiddleware, MeghMiddleware, IRequest, IResponse } from '@meghjs/core';
|
|
19
|
+
|
|
20
|
+
@AppMiddleware
|
|
21
|
+
export class LoggerMiddleware extends MeghMiddleware {
|
|
22
|
+
/**
|
|
23
|
+
* Return the request to continue, or throw to stop the pipeline.
|
|
24
|
+
*/
|
|
25
|
+
async invoke(req: IRequest, res?: IResponse) {
|
|
26
|
+
console.log('url:', req.url);
|
|
27
|
+
return req;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
A middleware extends `MeghMiddleware` and implements `invoke`. Returning the
|
|
33
|
+
request continues the pipeline; throwing an `HttpExceptions` error stops it:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { AppMiddleware, MeghMiddleware, IRequest, HttpExceptions } from '@meghjs/core';
|
|
37
|
+
|
|
38
|
+
@AppMiddleware
|
|
39
|
+
export class ApiKeyMiddleware extends MeghMiddleware {
|
|
40
|
+
async invoke(req: IRequest) {
|
|
41
|
+
if (req.headers['x-api-key'] !== process.env.API_KEY) {
|
|
42
|
+
throw HttpExceptions.unauthorized('Invalid API key');
|
|
43
|
+
}
|
|
44
|
+
return req;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Applying middleware
|
|
50
|
+
|
|
51
|
+
Middleware can be applied at three levels.
|
|
52
|
+
|
|
53
|
+
### Global
|
|
54
|
+
|
|
55
|
+
Runs for every request. Note the plural — `useMiddlewares`:
|
|
56
|
+
|
|
57
|
+
```ts [app.ts]
|
|
58
|
+
import { Megh } from '@meghjs/core';
|
|
59
|
+
import { LoggerMiddleware } from './middlewares/logger.middleware';
|
|
60
|
+
|
|
61
|
+
const app = Megh.createApplication();
|
|
62
|
+
|
|
63
|
+
app.useMiddlewares([LoggerMiddleware]);
|
|
64
|
+
|
|
65
|
+
export default app;
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Controller scoped
|
|
69
|
+
|
|
70
|
+
Runs for every route on that controller:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { ApiController, Get, UseMiddleware } from '@meghjs/core';
|
|
74
|
+
import { LoggerMiddleware } from '../middlewares/logger.middleware';
|
|
75
|
+
|
|
76
|
+
@UseMiddleware(LoggerMiddleware)
|
|
77
|
+
@ApiController('/home')
|
|
78
|
+
export class HomeController {
|
|
79
|
+
@Get()
|
|
80
|
+
sayHello() {
|
|
81
|
+
return 'Hello';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Route scoped
|
|
87
|
+
|
|
88
|
+
Runs for a single route:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { ApiController, Get, UseMiddleware } from '@meghjs/core';
|
|
92
|
+
import { LoggerMiddleware } from '../middlewares/logger.middleware';
|
|
93
|
+
|
|
94
|
+
@ApiController('/home')
|
|
95
|
+
export class HomeController {
|
|
96
|
+
@UseMiddleware(LoggerMiddleware)
|
|
97
|
+
@Get()
|
|
98
|
+
sayHello() {
|
|
99
|
+
return 'Hello';
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
A class is resolved through the DI container when the route is registered, so
|
|
105
|
+
it can use constructor injection. You can also pass an instance, for example to
|
|
106
|
+
give it settings. `UseMiddleware` also accepts an array, and both forms can be
|
|
107
|
+
mixed:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
@UseMiddleware([LoggerMiddleware, new RateLimitMiddleware(100)])
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
::: tip
|
|
114
|
+
Passing a class to `@UseMiddleware` crashed `app.run()` before 0.5.2.
|
|
115
|
+
:::
|
|
116
|
+
|
|
117
|
+
::: info
|
|
118
|
+
`@UseMiddleware` must sit above `@ApiController` on a class, and above the route
|
|
119
|
+
decorator on a method — decorators apply bottom-up.
|
|
120
|
+
:::
|
|
121
|
+
|
|
122
|
+
## Pipeline order
|
|
123
|
+
|
|
124
|
+
Each request passes through these stages:
|
|
125
|
+
|
|
126
|
+
1. Global middlewares (`useMiddlewares`)
|
|
127
|
+
2. Class `@UseMiddleware`, then method `@UseMiddleware`
|
|
128
|
+
3. Authentication (sets `request.user`)
|
|
129
|
+
4. Class `@Authorized`, then method `@Authorized`
|
|
130
|
+
5. Parameter and DTO validation
|
|
131
|
+
6. The route handler
|
|
132
|
+
|
|
133
|
+
Middleware runs before authentication, so it can reject a request early (an
|
|
134
|
+
API key check, an IP allowlist) but cannot read `request.user`. Put checks
|
|
135
|
+
that need the user in an authorization handler. Inline routes follow the
|
|
136
|
+
same order.
|
|
137
|
+
|
|
138
|
+
::: warning Changed in 0.5.5
|
|
139
|
+
`@UseMiddleware` used to run after `@Authorized`. See
|
|
140
|
+
[Upgrading to 0.5.5](/getting-started/upgrading-0.5#breaking-in-0-5-5).
|
|
141
|
+
:::
|
|
142
|
+
|
|
143
|
+
See [Authentication](/core-concept/authentication) for steps 3 and 4.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Request Context
|
|
3
|
+
description: Per-request values (the user, a tenant, a transaction) readable anywhere in the request, without passing them through every call.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Request Context
|
|
7
|
+
|
|
8
|
+
Services are singletons, so a service deep in the call chain can't see the
|
|
9
|
+
request it's working for. `requestContext` holds values for the request being
|
|
10
|
+
handled and makes them readable anywhere in its async call chain, such as
|
|
11
|
+
services, repositories and event listeners, without passing `req` through
|
|
12
|
+
every call. Each request gets its own values.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { createContextKey, requestContext } from '@meghjs/core';
|
|
16
|
+
|
|
17
|
+
export const TENANT = createContextKey<string>('tenant');
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Set a value early in the request, for example in middleware or an
|
|
21
|
+
authenticator:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
@AppMiddleware
|
|
25
|
+
export class TenantMiddleware extends MeghMiddleware {
|
|
26
|
+
invoke(req: IRequest) {
|
|
27
|
+
requestContext.set(TENANT, String(req.headers['x-tenant']));
|
|
28
|
+
return req;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Read it wherever you need it:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
@AppService
|
|
37
|
+
export class InvoiceService {
|
|
38
|
+
list() {
|
|
39
|
+
const tenant = requestContext.get(TENANT); // string | undefined
|
|
40
|
+
// ...
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## The current user
|
|
46
|
+
|
|
47
|
+
After `useAuthentication()` resolves a user, it is on `requestContext.user`
|
|
48
|
+
as well as `req.user`. Use `getUser<T>()` for a typed value:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
const user = requestContext.getUser<User>(); // User | undefined
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
It is `undefined` for anonymous requests, before authentication runs (in
|
|
55
|
+
middleware), and outside a request.
|
|
56
|
+
|
|
57
|
+
## API
|
|
58
|
+
|
|
59
|
+
| | |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `createContextKey<T>(name)` | A typed key. Two keys with the same name are still different keys, so libraries can't clash. Plain strings work too, typed as you pass them. |
|
|
62
|
+
| `get(key)` | The value, or `undefined`. |
|
|
63
|
+
| `getOrThrow(key)` | The value; throws when it isn't set or outside a request. |
|
|
64
|
+
| `has(key)`, `delete(key)` | Check for or remove a value. |
|
|
65
|
+
| `set(key, value)` | Set a value for the rest of this request. Throws outside a request. |
|
|
66
|
+
| `user`, `getUser<T>()` | The authenticated user. |
|
|
67
|
+
| `requestId` | Same as `getRequestId()`. `undefined` when request IDs are off. |
|
|
68
|
+
| `active` | `true` inside a request or `run()`. |
|
|
69
|
+
| `run(fn, init?)` | Run `fn` in a fresh context, with optional `{ requestId, user, values }`. |
|
|
70
|
+
|
|
71
|
+
## What keeps the context
|
|
72
|
+
|
|
73
|
+
The context follows the request's async chain:
|
|
74
|
+
|
|
75
|
+
- awaited calls, promises and timers started in the request;
|
|
76
|
+
- event listeners, including `dispatch(event, { queue: true })` and delayed
|
|
77
|
+
dispatches on the in-memory queue. Each queued event runs in the context it
|
|
78
|
+
was dispatched in.
|
|
79
|
+
|
|
80
|
+
It does **not** cross process boundaries. BullMQ jobs run in a worker, so put
|
|
81
|
+
what the job needs (a tenant ID, a user ID) in the job data, and use `run()`
|
|
82
|
+
in the worker if the code you call reads the context:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
@MeghWorker({ queue: 'invoices' })
|
|
86
|
+
export class InvoiceWorker extends MeghWorkerBase<{ tenant: string }> {
|
|
87
|
+
private readonly invoices = inject(InvoiceService);
|
|
88
|
+
|
|
89
|
+
process(job: Job<{ tenant: string }>) {
|
|
90
|
+
return requestContext.run(() => this.invoices.generate(), {
|
|
91
|
+
values: [[TENANT, job.data.tenant]],
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Socket.IO handlers aren't requests either. They have their own context (see
|
|
98
|
+
[WebSocket](/microservices/websocket)).
|
|
99
|
+
|
|
100
|
+
## Tests and scripts
|
|
101
|
+
|
|
102
|
+
Code that reads the context works outside a request too: `get` returns
|
|
103
|
+
`undefined`. To give it values, wrap the call in `run()`:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
const invoices = await requestContext.run(() => service.list(), {
|
|
107
|
+
values: [[TENANT, 'acme']],
|
|
108
|
+
user: { id: 1 },
|
|
109
|
+
});
|
|
110
|
+
```
|