@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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/docs/advanced/caching.md +72 -0
  6. package/dist/docs/advanced/database.md +328 -0
  7. package/dist/docs/advanced/events.md +169 -0
  8. package/dist/docs/advanced/file-uploads.md +141 -0
  9. package/dist/docs/advanced/health.md +81 -0
  10. package/dist/docs/advanced/logging.md +96 -0
  11. package/dist/docs/advanced/mail.md +439 -0
  12. package/dist/docs/advanced/orm/migrations.md +210 -0
  13. package/dist/docs/advanced/orm/models.md +291 -0
  14. package/dist/docs/advanced/orm/queries.md +169 -0
  15. package/dist/docs/advanced/orm/query-builder.md +120 -0
  16. package/dist/docs/advanced/orm/relations.md +179 -0
  17. package/dist/docs/advanced/orm/seeding.md +129 -0
  18. package/dist/docs/advanced/orm.md +145 -0
  19. package/dist/docs/advanced/plugins.md +90 -0
  20. package/dist/docs/advanced/queue.md +217 -0
  21. package/dist/docs/advanced/scheduler.md +253 -0
  22. package/dist/docs/advanced/testing.md +257 -0
  23. package/dist/docs/advanced/views.md +335 -0
  24. package/dist/docs/ai/mcp.md +162 -0
  25. package/dist/docs/cli/basic.md +133 -0
  26. package/dist/docs/cli/database.md +112 -0
  27. package/dist/docs/cli/generators.md +605 -0
  28. package/dist/docs/cli/scaffold/auth.md +172 -0
  29. package/dist/docs/cli/scaffold/domains.md +224 -0
  30. package/dist/docs/cli/scaffold/index.md +77 -0
  31. package/dist/docs/cli/scaffold/rbac.md +118 -0
  32. package/dist/docs/cli/scaffold/templates.md +235 -0
  33. package/dist/docs/core-concept/authentication.md +162 -0
  34. package/dist/docs/core-concept/configuration.md +268 -0
  35. package/dist/docs/core-concept/controller.md +350 -0
  36. package/dist/docs/core-concept/dependency-injection.md +213 -0
  37. package/dist/docs/core-concept/error-handling.md +185 -0
  38. package/dist/docs/core-concept/middleware.md +143 -0
  39. package/dist/docs/core-concept/request-context.md +110 -0
  40. package/dist/docs/core-concept/validation.md +355 -0
  41. package/dist/docs/getting-started/application.md +233 -0
  42. package/dist/docs/getting-started/installation.md +166 -0
  43. package/dist/docs/getting-started/introduction.md +136 -0
  44. package/dist/docs/getting-started/upgrading-0.4.md +125 -0
  45. package/dist/docs/getting-started/upgrading-0.5.md +293 -0
  46. package/dist/docs/getting-started/upgrading-0.6.md +251 -0
  47. package/dist/docs/getting-started/upgrading-0.7.md +225 -0
  48. package/dist/docs/getting-started/upgrading-megh.md +91 -0
  49. package/dist/docs/getting-started/upgrading-next.md +12 -0
  50. package/dist/docs/getting-started/upgrading.md +137 -0
  51. package/dist/docs/getting-started/usage.md +194 -0
  52. package/dist/docs/index.md +58 -0
  53. package/dist/docs/microservices/openapi.md +387 -0
  54. package/dist/docs/microservices/websocket.md +165 -0
  55. package/dist/docs/production/deployment.md +256 -0
  56. package/dist/docs/production/security.md +307 -0
  57. package/dist/docs/reference/api.md +999 -0
  58. package/dist/docs/reference/faq.md +227 -0
  59. package/dist/docs/reference/versioning.md +105 -0
  60. package/dist/docs.d.ts +30 -0
  61. package/dist/docs.js +126 -0
  62. package/dist/index.d.ts +10 -0
  63. package/dist/index.js +22 -0
  64. package/dist/megh.d.ts +59 -0
  65. package/dist/megh.js +207 -0
  66. package/dist/prompts.d.ts +3 -0
  67. package/dist/prompts.js +47 -0
  68. package/dist/result.d.ts +18 -0
  69. package/dist/result.js +48 -0
  70. package/dist/server.d.ts +17 -0
  71. package/dist/server.js +40 -0
  72. package/dist/tools/context.d.ts +11 -0
  73. package/dist/tools/context.js +2 -0
  74. package/dist/tools/database.d.ts +8 -0
  75. package/dist/tools/database.js +58 -0
  76. package/dist/tools/docs.d.ts +3 -0
  77. package/dist/tools/docs.js +63 -0
  78. package/dist/tools/generate.d.ts +10 -0
  79. package/dist/tools/generate.js +177 -0
  80. package/dist/tools/project.d.ts +3 -0
  81. package/dist/tools/project.js +84 -0
  82. package/dist/version.d.ts +2 -0
  83. package/dist/version.js +10 -0
  84. package/package.json +58 -4
@@ -0,0 +1,999 @@
1
+ ---
2
+ title: API Reference
3
+ description: Every public export of @meghjs/core, grouped by area, with signatures for the application methods and decorators.
4
+ outline: [2, 3]
5
+ ---
6
+
7
+ # API Reference
8
+
9
+ This page lists the public exports of `@meghjs/core`, grouped by area. Each
10
+ group links to the guide that explains it in depth. Everything here is
11
+ imported from the package root:
12
+
13
+ ```ts
14
+ import { Megh, ApiController, Get, Results } from "@meghjs/core";
15
+ ```
16
+
17
+ The command-line tool, `@meghjs/cli`, is documented separately under
18
+ [CLI](/cli/basic).
19
+
20
+ Signatures are shown as TypeScript. Optional parameters end in `?`, and
21
+ `Constructor<T>` means a class that builds a `T`.
22
+
23
+ ## Application
24
+
25
+ Guides: [Usage](/getting-started/usage), [Application](/getting-started/application).
26
+
27
+ ### Creating an application
28
+
29
+ | Export | Kind | Description |
30
+ | --- | --- | --- |
31
+ | `Megh` | class | Entry point. `Megh.createApplication(options?)` returns the application; `Megh.createTestApplication(options)` returns a test client. |
32
+ | `MeghApplication` | class | The application object returned by `Megh.createApplication()`. Its methods are listed below. |
33
+
34
+ ```ts
35
+ Megh.createApplication(options?: MeghApplicationOptions): MeghApplication
36
+ Megh.createTestApplication(options: TestAppOptions): TestApplication
37
+ ```
38
+
39
+ `Megh.createApplication()` returns the same instance every time it's called in
40
+ a process.
41
+
42
+ `MeghApplicationOptions` fields:
43
+
44
+ | Option | Type | Description |
45
+ | --- | --- | --- |
46
+ | `server` | `FastifyServerOptions` | Options passed to the Fastify instance. |
47
+ | `requestId` | `RequestIdOptions` | Request ID header and generator, or `false` to turn request IDs off. |
48
+ | `experimental` | `ExperimentalOptions` | `{ compiledValidation?: boolean }`. Defaults to the `MEGH_COMPILED_VALIDATION` environment variable. |
49
+ | `plugins` | `MeghPlugin[]` | Plugins to register explicitly. |
50
+ | `autoloadPlugins` | `boolean` | Find plugins among the app's dependencies. Defaults to `true`. |
51
+
52
+ ### MeghApplication methods
53
+
54
+ Every `use*`, `on*` and `addHealthCheck` method returns the application, so
55
+ calls chain.
56
+
57
+ #### Features
58
+
59
+ | Method | Description |
60
+ | --- | --- |
61
+ | `useControllers(controllers: Constructor[] \| { auto: true; path?: string })` | Register controller classes, or scan a directory for them. |
62
+ | `useCors(options: CorsOptions)` | Enable CORS through `@fastify/cors`. |
63
+ | `useSecurityHeaders(options?: SecurityHeadersOptions)` | Send CSP, HSTS, `X-Frame-Options`, `nosniff` and other security headers on every response. Throws if called twice. See [Security](/production/security#add-security-headers). |
64
+ | `useRateLimit(options?: RateLimitOptions)` | Limit requests per client per window (default 100 a minute per IP, in memory) and answer 429 over it. Throws if called twice. See [Security](/production/security#add-rate-limits). |
65
+ | `useMultipart(options?: any)` | Enable multipart bodies through `@fastify/multipart`. Defaults: `attachFieldsToBody: true`, 10 MB file size limit. |
66
+ | `useStaticFiles(options?: any)` | Serve static files through `@fastify/static`. |
67
+ | `useCompression(options?: CompressionOptions)` | Compress responses through `@fastify/compress`. |
68
+ | `useMethodOverride()` | Route a form POST with `_method=PUT\|PATCH\|DELETE` (urlencoded or multipart) to that method's route, and parse urlencoded bodies. Throws if called twice. See [Views](/advanced/views#forms). |
69
+ | `setGlobalPrefix(prefix: string, options?: { exclude?: (string \| RegExp)[] })` | Serve controller and inline routes under `prefix`. |
70
+ | `useVersioning(options: VersioningOptions)` | Version controller routes by URI (`/v1/...`) or header. |
71
+ | `useEnvSchema(schema: Constructor)` | Validate environment variables against a DTO class at boot. |
72
+ | `useOpenApi(options?: OpenApiUiOptions \| Constructor<MeghConfig<OpenApiUiOptions>>)` | Generate the OpenAPI document and serve the docs page. |
73
+ | `useMiddlewares(middlewares: Constructor<MeghMiddleware>[])` | Register global middleware, run before every route. |
74
+ | `useAuthentication(authentication: Constructor<MeghAuthentication>)` | Register the authentication handler that sets `request.user`. |
75
+ | `useAuthorization(authorization: Constructor<any> \| Record<string, Constructor<any>>, options?: UseAuthorizationOptions)` | Register one authorization handler, or several by name. `{ default }` protects every route without `@Authorized` or `@Public`. See [Deny by default](/core-concept/authentication#deny-by-default). |
76
+ | `useExceptionFilters(filters: ExceptionFilterLike \| ExceptionFilterLike[])` | Register global exception filters, run in order before the default error response. |
77
+ | `useErrorHandler(handler: ErrorHandlerFunction)` | Register a function filter that sees every error. |
78
+ | `useErrorLogger(logger: ErrorLogger \| false)` | Replace how default error responses are logged, or turn logging off. |
79
+ | `useHealth(options?: HealthOptions)` | Serve `GET /health` (liveness) and `GET /ready` (readiness). |
80
+ | `addHealthCheck(name: string, check: HealthCheck)` | Add a readiness check reported by `GET /ready`. |
81
+ | `useCache(options?: CacheOptions)` | Configure `CacheManager` and register it in the container. |
82
+ | `useScheduler(tasks: Constructor[] \| { path: string })` | Register `@ScheduledTask` classes, or scan a directory for them. |
83
+ | `useWorker(workers: Constructor<any>[])` | Resolve and start `@Queue` and `@MeghWorker` classes. They close on shutdown. |
84
+ | `useMail(options?: MailConfig \| Constructor<MeghConfig<MailConfig>>)` | Configure `Mailer` over `MEGH_MAIL_*`, and start the mail queue's worker when `queue` is set. Throws when the default mailer is misconfigured. See [Mail](/advanced/mail). |
85
+ | `useSocketIo(options?: any)` | Enable Socket.IO through `fastify-socket.io`. |
86
+ | `useGlobal(options: GlobalOptions)` | Call several `use*` methods from one object (`cors`, `openApi`, `controllers`, `middlewares`, `authorization`, `multipart`, `staticFiles`, `securityHeaders`, `rateLimit`). |
87
+ | `useMeghORM(options?: DatabaseOptions \| MeghConfigClass<DatabaseOptions>)` | Connect Megh ORM. Added by the built-in ORM plugin. See [ORM](/advanced/orm). |
88
+ | `useDatabase(db: Kysely<any>)` | Deprecated. Use an existing Kysely instance as the ORM connection. Use `useMeghORM()` instead. |
89
+
90
+ #### Functional routes
91
+
92
+ | Method | Description |
93
+ | --- | --- |
94
+ | `mapGet(path: string, fn)` | Register a `GET` route handled by a function. |
95
+ | `mapPost(path: string, fn)` | Register a `POST` route handled by a function. |
96
+ | `mapPut(path: string, fn)` | Register a `PUT` route handled by a function. |
97
+ | `mapPatch(path: string, fn)` | Register a `PATCH` route handled by a function. |
98
+ | `mapDelete(path: string, fn)` | Register a `DELETE` route handled by a function. |
99
+
100
+ Each `map*` method returns a route builder with three chainable methods:
101
+ `useMiddleware(middleware | middleware[])`, `authorized(options?: string | { name?: string })`
102
+ and `useOpenApi(options: OpenApiOptions)`.
103
+
104
+ #### Lifecycle
105
+
106
+ | Method | Description |
107
+ | --- | --- |
108
+ | `run(port?: number, options?: RunOptions \| CallableFunction): Promise<void>` | Start the server. `port` defaults to `4000`. A function as the second argument is called once the server is listening. |
109
+ | `close(): Promise<void>` | Stop the server, scheduled tasks and workers, then run the `onClose` hooks. Calling it again returns the same promise. |
110
+ | `onInit(hook: LifecycleHook)` | Run `hook` during `run()`, after the database connects and before the server listens. |
111
+ | `onReady(hook: LifecycleHook)` | Run `hook` once the server is listening. |
112
+ | `onClose(hook: LifecycleHook)` | Run `hook` on shutdown (`close()`, SIGTERM or SIGINT), in reverse registration order. |
113
+
114
+ `RunOptions`:
115
+
116
+ | Option | Type | Description |
117
+ | --- | --- | --- |
118
+ | `host` | `string` | Interface to listen on. Defaults to `process.env.HOST`, else `0.0.0.0`. |
119
+ | `onListen` | `CallableFunction` | Called once the server is listening. |
120
+ | `shutdownTimeout` | `number` | Milliseconds to wait for a graceful shutdown before exiting with code 1. Defaults to `10000`. |
121
+
122
+ #### Other members
123
+
124
+ | Member | Description |
125
+ | --- | --- |
126
+ | `app: FastifyInstance` | The underlying Fastify instance. |
127
+ | `getPlugins(): readonly string[]` | Names of the registered plugins, in registration order. |
128
+ | `isDevelopment(): boolean` | `true` only when `NODE_ENV` is exactly `"development"`. |
129
+ | `installErrorHandling()` | Internal. Installs the error and not-found handlers. `run()` calls it. |
130
+ | `MeghApplication.getApp(options?)` | Static. Returns the shared instance, creating it on first call. Options passed to later calls are ignored, with a warning. `Megh.createApplication()` calls it. |
131
+ | `MeghApplication.getInternalApp(options?)` | Static, deprecated, internal. Creates a new, unshared instance. |
132
+
133
+ ### Application types
134
+
135
+ | Export | Kind | Description |
136
+ | --- | --- | --- |
137
+ | `MeghApplicationOptions` | type | Options for `Megh.createApplication()`. |
138
+ | `IMeghApplication` | interface | The core method set of `MeghApplication`. |
139
+ | `RunOptions` | type | Options for `app.run()`. |
140
+ | `LifecycleHook` | type | `() => void \| Promise<void>`. |
141
+ | `ExperimentalOptions` | type | `{ compiledValidation?: boolean }`. |
142
+ | `CorsOptions` | type | Options for `useCors()`. |
143
+ | `GlobalOptions` | type | Options for `useGlobal()`. |
144
+ | `AutoControllerOptions` | type | `{ auto: true; path?: string }` for `useControllers()`. |
145
+ | `CacheOptions` | type | `{ provider: "memory" \| "redis"; redisOptions?: RedisOptions }` for `useCache()`. |
146
+
147
+ ## Controllers and routing
148
+
149
+ Guide: [Controllers](/core-concept/controller).
150
+
151
+ ### Decorators
152
+
153
+ | Export | Kind | Signature | Description |
154
+ | --- | --- | --- | --- |
155
+ | `ApiController` | decorator | `@ApiController`, `@ApiController(path: string, options?: ControllerOptions)`, `@ApiController(options: ControllerOptions)` | Mark a class as a controller and register it for DI. Path defaults to `/`. |
156
+ | `Get` | decorator | `@Get(pathOrOptions?: string \| RouteMethodOptions, options?: RouteMethodOptions)` | Handle `GET` requests. Path defaults to `/`. |
157
+ | `Post` | decorator | same as `Get` | Handle `POST` requests. |
158
+ | `Put` | decorator | same as `Get` | Handle `PUT` requests. |
159
+ | `Patch` | decorator | same as `Get` | Handle `PATCH` requests. |
160
+ | `Delete` | decorator | same as `Get` | Handle `DELETE` requests. |
161
+ | `Options` | decorator | same as `Get` | Handle `OPTIONS` requests. |
162
+ | `All` | decorator | same as `Get` | Handle every HTTP method Fastify supports. |
163
+ | `Route` | decorator | `@Route(method: RouteMethods, pathOrOptions?, options?)` | Generic form of the method decorators above. |
164
+ | `HttpCode` | decorator | `@HttpCode(statusCode: number)` | Status code for a successful response. A returned `Results.*` or `HttpResponse.*` status wins. Throws for codes outside 100–599. |
165
+ | `Redirect` | decorator | `@Redirect(url: string, statusCode = 302)` | Redirect instead of sending the return value. Returning `{ url, statusCode }` overrides both. Throws for non-3xx codes. |
166
+ | `ResponseHeader` | decorator | `@ResponseHeader(name: string, value: string)` | Set a response header on the route. Stackable. |
167
+ | `Version` | decorator | `@Version(version: string \| string[])` | API version(s) of a controller or route, with `useVersioning()`. |
168
+ | `VersioningOptions` | type | `{ type: 'uri'; prefix?; defaultVersion? } \| { type: 'header'; header?; defaultVersion? }` | Options for `useVersioning()`. |
169
+
170
+ ### Types
171
+
172
+ | Export | Kind | Description |
173
+ | --- | --- | --- |
174
+ | `ControllerOptions` | type | `{ name?: string; path?: string }`. `name` is the OpenAPI tag; it defaults to the class name without `Controller`. |
175
+ | `RouteMethodOptions` | type | `{ method?: RouteMethods; path?: string; openapi?: OpenApiOptions; name?: string }`. |
176
+ | `RouteMethods` | type | `"GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE" \| "OPTIONS" \| "ALL"`. |
177
+
178
+ ## Parameters
179
+
180
+ Guide: [Controllers](/core-concept/controller).
181
+
182
+ The parameter decorators take an optional key and an optional options object,
183
+ in either order of presence:
184
+
185
+ ```ts
186
+ (key?: string | ParameterOptions, options?: ParameterOptions) => ParameterDecorator
187
+ // ParameterOptions: { required?: boolean; validate?: boolean; type?: any }
188
+ ```
189
+
190
+ `required` and `validate` default to `true`. `type` is only needed when the
191
+ compiler doesn't emit decorator metadata (tsx, esbuild, SWC).
192
+
193
+ | Export | Kind | Description |
194
+ | --- | --- | --- |
195
+ | `Param` | decorator | A route parameter (`@Param("id")`), or all of them with no key. |
196
+ | `Query` | decorator | A query string value, or the whole query (often a DTO) with no key. |
197
+ | `Body` | decorator | The request body, usually a DTO, or one field with a key. |
198
+ | `Header` | decorator | A request header, or all headers with no key. |
199
+ | `AuthUser` | decorator | `request.user`, as set by the authentication handler. |
200
+ | `MeghRequest` | decorator | `@MeghRequest()`. The request object itself. |
201
+ | `UploadFile` | decorator | `@UploadFile(fieldName: string)`. One uploaded file from a multipart field. |
202
+ | `UploadFiles` | decorator | `@UploadFiles(fieldName?: string)`. Uploaded files from a field, or from every field with no name. |
203
+
204
+ ## Responses
205
+
206
+ Guide: [Controllers](/core-concept/controller).
207
+
208
+ ### Results
209
+
210
+ | Export | Kind | Description |
211
+ | --- | --- | --- |
212
+ | `Results` | class | Static factories for route results (below). |
213
+ | `HttpResult` | abstract class | Base class for values that control status, headers and body. |
214
+ | `Ok` | class | `200 { data }`. |
215
+ | `Created` | class | `201 { data }`. |
216
+ | `NoContent` | class | `204` with an empty body. |
217
+ | `NotFound` | class | `404 { code, status, message }`. |
218
+ | `OkStream` | class | `200` with a stream body. |
219
+ | `RedirectResult` | class | A 3xx with `Location`; made by `Results.Redirect(url, statusCode?)`. |
220
+ | `OkStreamOptions` | type | `{ contentType?: string; filename?: string }`. With `filename`, the stream is sent as an attachment. |
221
+ | `RouteResult` | type | `typeof Results.Ok<T>`. |
222
+
223
+ ```ts
224
+ Results.Ok<T>(data: T): Ok<T>
225
+ Results.Created<T>(data: T): Created<T>
226
+ Results.NoContent(): NoContent
227
+ Results.NotFound<T>(message: T): NotFound<T>
228
+ Results.Redirect(url: string, statusCode = 302): RedirectResult
229
+ Results.OkStream(stream: Readable, options?: OkStreamOptions): OkStream
230
+ ```
231
+
232
+ ### HttpResponse
233
+
234
+ | Export | Kind | Description |
235
+ | --- | --- | --- |
236
+ | `HttpResponse` | class | Static factories that return `{ message, data }` bodies. |
237
+ | `IHttpResponse` | interface | `{ message: string; data: T \| null }`. |
238
+ | `withStatus` | function | `withStatus(body, statusCode)`. Attach a status code to a plain object without changing its JSON. |
239
+ | `HTTP_STATUS_KEY` | const | Symbol `withStatus` uses to store the status. |
240
+
241
+ ```ts
242
+ HttpResponse.Ok<T>(obj: any, dto?: ClassConstructor<T>): IHttpResponse<T> // 200
243
+ HttpResponse.Created<T>(obj: any, dto?: ClassConstructor<T>): IHttpResponse<T> // 201
244
+ HttpResponse.NoContent(): IHttpResponse<null> // 204
245
+ ```
246
+
247
+ With a DTO class, `Ok` and `Created` keep only the DTO's exposed fields
248
+ (class-transformer `excludeExtraneousValues`).
249
+
250
+ ### Pagination and collections
251
+
252
+ | Export | Kind | Description |
253
+ | --- | --- | --- |
254
+ | `paginated` | function | `paginated(data: T[], total, page, perPage): Paginated<T>`. Wrap a page of data with its `meta`. |
255
+ | `Paginated` | function and interface | As a type, `{ data: T[]; meta: PaginationMeta }`. As a function, `Paginated(Item)` marks a page of `Item` for OpenAPI: `@ApiResponse(200, Paginated(User))`. |
256
+ | `PaginationMeta` | interface | `{ total, page, perPage, lastPage, next, prev }`. |
257
+ | `PageRequest` | interface | `{ page?, perPage? }`, plus the deprecated `limit`, `take` and `skip`. |
258
+ | `normalizePageRequest` | function | Resolve a `PageRequest` into `{ page, perPage, offset }`. |
259
+ | `buildPaginationMeta` | function | `buildPaginationMeta(total, page, perPage): PaginationMeta`. |
260
+ | `DEFAULT_PER_PAGE` | const | `10`. |
261
+ | `PAGINATED_ITEM` | const | Symbol used by `Paginated(Item)`. |
262
+ | `PaginationResult` | type | Deprecated alias of `Paginated<T>`. |
263
+ | `List` | class | Small in-memory list with async `Find` and `FindOne`. `List.from(items)`. |
264
+ | `IList` | interface | The `List` surface. |
265
+ | `Collection` | class | In-memory collection: `Collection.from(items)` with `find`, `findOne`, their async forms and `clear`. |
266
+ | `BasicCollection` | interface | The `Collection` surface. |
267
+ | `IFindOneOptions` | interface | `{ where }` argument for `Collection.findOne`. |
268
+
269
+ ## Exceptions and error handling
270
+
271
+ Guide: [Error handling](/core-concept/error-handling).
272
+
273
+ ### HTTP exceptions
274
+
275
+ Every exception takes `(message?: any, options?: HttpExceptionOptions)`. A
276
+ string message is sent as `message`; an object is sent as `data`.
277
+ `HttpExceptionOptions` is `{ cause?: unknown; headers?: Record<string, string | number | string[]> }`.
278
+
279
+ | Export | Kind | Status |
280
+ | --- | --- | --- |
281
+ | `BaseHttpException` | abstract class | Base class. `code`, `statusCode`, `payload`, `headers`. |
282
+ | `HttpException` | class | Any status: `new HttpException(status: number, message?, options?)`. |
283
+ | `BadRequestException` | class | 400 |
284
+ | `ValidationErrorException` | class | 400. `new ValidationErrorException(message?, errors?: unknown[], options?)`; `errors` is sent in the response. |
285
+ | `UnauthorizedException` | class | 401 |
286
+ | `ForbiddenException` | class | 403 |
287
+ | `NotFoundException` | class | 404 |
288
+ | `MethodNotAllowedException` | class | 405 |
289
+ | `NotAcceptableException` | class | 406 |
290
+ | `RequestTimeoutException` | class | 408 |
291
+ | `ConflictException` | class | 409 |
292
+ | `GoneException` | class | 410 |
293
+ | `PayloadTooLargeException` | class | 413 |
294
+ | `UnsupportedMediaTypeException` | class | 415 |
295
+ | `UnprocessableEntityException` | class | 422 |
296
+ | `TooManyRequestsException` | class | 429 |
297
+ | `InternalErrorException` | class | 500 |
298
+ | `NotImplementedException` | class | 501 |
299
+ | `BadGatewayException` | class | 502 |
300
+ | `ServiceUnavailableException` | class | 503 |
301
+ | `GatewayTimeoutException` | class | 504 |
302
+ | `HttpExceptions` | const | Factory shortcuts, such as `HttpExceptions.notFound("User not found")` and `HttpExceptions.status(402, "Payment required")`. |
303
+ | `HttpExceptionOptions` | interface | `{ cause?, headers? }`. |
304
+ | `HttpExceptionTypes` | type | Union of the not-found, bad-request, unauthorized, internal-error and forbidden exceptions. |
305
+
306
+ ### Exception filters
307
+
308
+ | Export | Kind | Signature / description |
309
+ | --- | --- | --- |
310
+ | `Catch` | decorator | `@Catch(...types: ErrorClass[])`. Limit a filter class to these error classes and register it for DI. |
311
+ | `UseFilters` | decorator | `@UseFilters(...filters: ExceptionFilterLike[])`. Apply filters to a controller or route. They run before the global filters. |
312
+ | `ExceptionFilter` | interface | `{ catch(error: E, ctx: ErrorContext): unknown }`. |
313
+ | `ErrorHandlerFunction` | type | `(error: E, ctx: ErrorContext) => unknown`. |
314
+ | `ExceptionFilterLike` | type | A filter class, a filter instance or an `ErrorHandlerFunction`. |
315
+ | `ErrorContext` | interface | `{ request, reply, isDevelopment, response }`. |
316
+ | `ErrorResponse` | interface | `{ statusCode, headers?, body }`. |
317
+ | `ErrorResponseBody` | interface | The default JSON error body: `{ code, status, message, data?, errors?, error?, stack? }`. |
318
+ | `ErrorLogger` | type | `(error, request, response) => void`, for `useErrorLogger()`. |
319
+ | `ErrorHandlerOptions` | interface | `{ isDevelopment?: () => boolean; logger?: ErrorLogger \| false }`. |
320
+ | `defaultErrorResponse` | function | `defaultErrorResponse(error, isDevelopment): ErrorResponse`. The response Megh sends when no filter handles an error. |
321
+ | `defaultErrorLogger` | const | The default `ErrorLogger`: 4xx as warnings, others as errors with the stack. |
322
+ | `MeghErrorHandler` | class | Megh's request error handler. The application creates one; you don't normally construct it. |
323
+
324
+ ## Validation
325
+
326
+ Guide: [Validation](/core-concept/validation).
327
+
328
+ ### Validation decorators
329
+
330
+ Every decorator takes an optional last argument, `options?: ValidationOptions`
331
+ (`message`, `each`, `groups`, and so on, as in class-validator).
332
+
333
+ | Export | Kind | Signature |
334
+ | --- | --- | --- |
335
+ | `IsOptional` | decorator | `@IsOptional(options?)` |
336
+ | `ValidateIf` | decorator | `@ValidateIf(condition: (object, value) => boolean, options?)` |
337
+ | `Allow` | decorator | `@Allow(options?)` |
338
+ | `ValidateNested` | decorator | `@ValidateNested(options?)` |
339
+ | `IsDefined` | decorator | `@IsDefined(options?)` |
340
+ | `IsNotEmpty` | decorator | `@IsNotEmpty(options?)` |
341
+ | `IsEmpty` | decorator | `@IsEmpty(options?)` |
342
+ | `IsIn` | decorator | `@IsIn(values: readonly any[], options?)` |
343
+ | `IsNotIn` | decorator | `@IsNotIn(values: readonly any[], options?)` |
344
+ | `IsString` | decorator | `@IsString(options?)` |
345
+ | `IsNumber` | decorator | `@IsNumber(numberOptions?: IsNumberOptions, options?)` |
346
+ | `IsInt` | decorator | `@IsInt(options?)` |
347
+ | `IsBoolean` | decorator | `@IsBoolean(options?)` |
348
+ | `IsDate` | decorator | `@IsDate(options?)` |
349
+ | `IsArray` | decorator | `@IsArray(options?)` |
350
+ | `IsObject` | decorator | `@IsObject(options?)` |
351
+ | `IsEnum` | decorator | `@IsEnum(entity: object, options?)` |
352
+ | `Min` | decorator | `@Min(minValue: number, options?)` |
353
+ | `Max` | decorator | `@Max(maxValue: number, options?)` |
354
+ | `IsPositive` | decorator | `@IsPositive(options?)` |
355
+ | `IsNegative` | decorator | `@IsNegative(options?)` |
356
+ | `MinLength` | decorator | `@MinLength(min: number, options?)` |
357
+ | `MaxLength` | decorator | `@MaxLength(max: number, options?)` |
358
+ | `Length` | decorator | `@Length(min: number, max?: number, options?)` |
359
+ | `Matches` | decorator | `@Matches(pattern: RegExp, options?)` or `@Matches(pattern: string \| RegExp, modifiers?: string, options?)` |
360
+ | `IsEmail` | decorator | `@IsEmail(emailOptions?: object, options?)` |
361
+ | `IsUUID` | decorator | `@IsUUID(version?, options?)` |
362
+ | `IsUrl` | decorator | `@IsUrl(urlOptions?: object, options?)` |
363
+ | `ArrayMinSize` | decorator | `@ArrayMinSize(min: number, options?)` |
364
+ | `ArrayMaxSize` | decorator | `@ArrayMaxSize(max: number, options?)` |
365
+ | `ArrayNotEmpty` | decorator | `@ArrayNotEmpty(options?)` |
366
+ | `IsArrayNotEmpty` | decorator | `@IsArrayNotEmpty(validationOptions?)`. A class-validator decorator (requires `class-validator`). Prefer `ArrayNotEmpty`. |
367
+
368
+ ### Transformation
369
+
370
+ | Export | Kind | Signature / description |
371
+ | --- | --- | --- |
372
+ | `Type` | decorator | `@Type(typeFunction?: (options?: TypeHelpOptions) => Function, options?: TypeOptions)`. The class a property's value is converted to. Needed for `@ValidateNested` and for query values. |
373
+ | `Transform` | decorator | `@Transform(transformFn: (params: TransformFnParams) => any, options?: TransformDecoratorOptions)`. Change a property's value while the body becomes the DTO. |
374
+ | `TransformationType` | enum | The direction passed to a `@Transform` function, as in class-transformer. |
375
+
376
+ ### Mapped types
377
+
378
+ | Export | Kind | Signature |
379
+ | --- | --- | --- |
380
+ | `PartialType` | function | `PartialType(Base: Constructor<T>): Constructor<Partial<T>>` |
381
+ | `PickType` | function | `PickType(Base: Constructor<T>, keys: K[]): Constructor<Pick<T, K>>` |
382
+ | `OmitType` | function | `OmitType(Base: Constructor<T>, keys: K[]): Constructor<Omit<T, K>>` |
383
+
384
+ ### Running validation yourself
385
+
386
+ | Export | Kind | Description |
387
+ | --- | --- | --- |
388
+ | `validateDto` | function | `validateDto(target, value): DtoValidationResult<T>`. Convert and validate a value with Megh's decorators. |
389
+ | `transformAndValidate` | function | `transformAndValidate(target, value, options?): Promise<RequestValidationResult<T>>`. The same with class-validator and class-transformer. |
390
+ | `Validator` | class | Rule-based validator for plain objects: `new Validator(rules: ValidationProps, options?).validate(obj)` returns `[issues, obj]`. |
391
+ | `validateOrThrow` | function | `validateOrThrow(obj, rules: ValidationProps, options?)`. Validate with `Validator` and throw `BadRequestException` on failure. |
392
+ | `isMeghValidatorClass` | function | Whether a class uses Megh's validation decorators. |
393
+
394
+ ### Validation types
395
+
396
+ | Export | Kind | Description |
397
+ | --- | --- | --- |
398
+ | `ValidationOptions` | type | Options every validation decorator takes. |
399
+ | `ValidationArguments` | type | What a message function receives. |
400
+ | `IsNumberOptions` | type | `{ allowNaN?, allowInfinity?, maxDecimalPlaces? }`. |
401
+ | `TypeOptions` | type | Options for `@Type`. `discriminator` isn't supported yet. |
402
+ | `TypeHelpOptions` | type | What a `@Type` function receives. |
403
+ | `TransformFnParams` | type | What a `@Transform` function receives. |
404
+ | `TransformDecoratorOptions` | type | Options for `@Transform`. |
405
+ | `ValidationIssue` | type | One issue from `validateDto`. |
406
+ | `DtoValidationResult` | type | Result of `validateDto`. |
407
+ | `RequestValidationIssue` | type | One issue from `transformAndValidate`. |
408
+ | `RequestValidationResult` | type | Result of `transformAndValidate`. |
409
+ | `ValidationRule` | type | A `Validator` rule: `{ type: "string" \| "number" \| "boolean", required?, optional?, message?, min?, max?, exact? }`. |
410
+ | `ValidationProps` | type | `Record<string, ValidationRule>`. |
411
+ | `ValidateOptons` | type | `{ location?: "header" \| "queryparam" \| "param" \| "body" \| "custom" }`, for `Validator`. |
412
+ | `ValidatorIssue` | type | One issue from `Validator`. |
413
+
414
+ ## Dependency injection
415
+
416
+ Guide: [Dependency injection](/core-concept/dependency-injection).
417
+
418
+ | Export | Kind | Signature / description |
419
+ | --- | --- | --- |
420
+ | `Injectable` | decorator | `@Injectable()`. Make a class resolvable by the container. Constructor parameters are injected from their types. |
421
+ | `AppService` | decorator | `@AppService` or `@AppService()`. Same as `@Injectable()`, for service classes. |
422
+ | `Utility` | decorator | Alias of `Injectable`: `@Utility()`. |
423
+ | `Helper` | decorator | Alias of `Injectable`: `@Helper()`. |
424
+ | `inject` | function | `inject<T>(id: ServiceIdentifier<T>, options?: InjectOptions): T`. Resolve a dependency, usually in a field initializer. With `{ optional: true }` it returns `undefined` when nothing is registered. |
425
+ | `Inject` | decorator | `@Inject(id, options?: InjectOptions)`. Inject a token, string or class into a constructor parameter or property, for interface, union and primitive types. |
426
+ | `Optional` | decorator | `@Optional()`. Inject `undefined` into a constructor parameter that can't be resolved, instead of failing. |
427
+ | `createInjectDecorator` | function | `createInjectDecorator(factory: () => unknown)`. Build a property or parameter decorator that injects `factory()`. |
428
+ | `MeghContainer` | const | The container: `get(id)`, `set(id, value)`, `has(id)`, `reset()`. |
429
+ | `Token` | class | `new Token<T>(name?: string)`. A typed identifier for values that aren't classes. |
430
+ | `ContainerError` | class | Thrown when the container can't resolve or construct a service. |
431
+ | `ContainerApi` | interface | The `MeghContainer` surface. |
432
+ | `ServiceIdentifier` | type | A class, abstract class, `Token` or string. |
433
+ | `Constructable` | type | `new (...args: any[]) => T`. |
434
+ | `InjectOptions` | type | `{ optional?: boolean }`. |
435
+
436
+ ## Middleware
437
+
438
+ Guide: [Middleware](/core-concept/middleware).
439
+
440
+ | Export | Kind | Signature / description |
441
+ | --- | --- | --- |
442
+ | `MeghMiddleware` | abstract class | `invoke(req: IRequest, res?: IResponse): Promise<IRequest \| HttpException>`. |
443
+ | `AppMiddleware` | decorator | `@AppMiddleware`. Register a middleware class for DI. Throws if it has no `invoke` method. |
444
+ | `UseMiddleware` | decorator | `@UseMiddleware(middleware \| middleware[])`. Apply middleware classes or instances to a controller or route. |
445
+
446
+ Global middleware is registered with `app.useMiddlewares([...])`.
447
+
448
+ ## Authentication and authorization
449
+
450
+ Guide: [Authentication](/core-concept/authentication).
451
+
452
+ | Export | Kind | Signature / description |
453
+ | --- | --- | --- |
454
+ | `MeghAuthentication` | abstract class | `authenticate(request: IRequest): TUser \| null \| undefined \| Promise<...>`. The return value becomes `request.user`. Register with `app.useAuthentication()`. |
455
+ | `CanAuthorize` | decorator | `@CanAuthorize`. Mark a class with an `authorize(req, options?)` method as an authorization handler and register it for DI. |
456
+ | `Public` | decorator | `@Public()`. Leave a controller or route out of the `useAuthorization` default. Inline routes use `.public()`. |
457
+ | `UseAuthorizationOptions`, `AuthorizationDefault` | types | `{ default?: 'authenticated' \| true \| AuthorizedOptions }` for `useAuthorization()`. |
458
+ | `Authorized` | decorator | `@Authorized()`, `@Authorized(name: string)` or `@Authorized({ name?, ...options })`. Require authorization on a controller or route. Extra options are passed to `authorize()`. |
459
+ | `AuthorizeClass` | interface | `{ authorize(req: IRequest, options?: any): unknown }`. Return `false` or throw to deny with 403. |
460
+ | `AuthorizedOptions` | type | `string \| { name?: string; [key: string]: any }`. |
461
+
462
+ ## Security headers and rate limiting
463
+
464
+ Guide: [Security Hardening](/production/security#add-security-headers).
465
+
466
+ | Export | Kind | Signature / description |
467
+ | --- | --- | --- |
468
+ | `SecurityHeadersOptions` | type | `{ contentSecurityPolicy?, strictTransportSecurity?, frameOptions?, referrerPolicy?, crossOriginOpenerPolicy?, crossOriginResourcePolicy?, crossOriginEmbedderPolicy?, headers? }` for `useSecurityHeaders()`. `false` leaves a header out. |
469
+ | `ContentSecurityPolicyOptions` | type | `{ directives?: Record<string, CspDirectiveValue>; useDefaults?: boolean; reportOnly?: boolean }`. |
470
+ | `CspDirectiveValue` | type | `string \| string[] \| boolean`. `true` is a bare directive, `false` removes it. |
471
+ | `StrictTransportSecurityOptions` | type | `{ maxAge?: number; includeSubDomains?: boolean; preload?: boolean }`. |
472
+ | `ReferrerPolicy` | type | A `Referrer-Policy` token, such as `"no-referrer"`. |
473
+ | `RateLimit` | decorator | `@RateLimit(options: RouteRateLimitOptions \| false)`. A controller's or route's own limit and counter, or `false` for none. Works without `useRateLimit()`. |
474
+ | `RateLimitOptions` | type | `{ max?, window?, key?, ipv6Subnet?, skip?, store?, redis?, headers?, message?, failOpen?, global? }` for `useRateLimit()`. `ipv6Subnet` (default 64) groups IPv6 clients by prefix with the default key. |
475
+ | `RouteRateLimitOptions` | type | `{ max?: number; window?: RateLimitWindow; key?: (req) => string \| Promise<string> }`. |
476
+ | `RateLimitWindow` | type | `number \| string`. Milliseconds, or a duration such as `'30s'`, `'15m'`, `'1 hour'`. |
477
+ | `RateLimitStore` | interface | `{ hit(key, windowMs): RateLimitHit \| Promise<RateLimitHit>; reset?(key); close?() }`. Where counts live. |
478
+ | `RateLimitHit` | type | `{ count: number; resetAt: number }`. `resetAt` is epoch milliseconds. |
479
+ | `MemoryRateLimitStore` | class | The default store: fixed-window counts in memory, per process. `new MemoryRateLimitStore({ sweepIntervalMs?, maxKeys? })`; past `maxKeys` (default 100,000) the oldest windows are dropped. |
480
+ | `rateLimitIpKey` | function | `rateLimitIpKey(ip, ipv6Subnet = 64)`. The default key: IPv4 per address, IPv6 per prefix. Use it in a custom `key` that falls back to the IP. |
481
+ | `RedisRateLimitStore` | class | `new RedisRateLimitStore(redis, { prefix? })`. Counts in Redis, shared by replicas. Takes an ioredis client, which it does not close. |
482
+ | `RedisEvalClient` | interface | The part of an ioredis client the Redis store uses: `eval` and `del`. |
483
+
484
+ ## Configuration and environment
485
+
486
+ Guide: [Configuration](/core-concept/configuration).
487
+
488
+ | Export | Kind | Signature / description |
489
+ | --- | --- | --- |
490
+ | `MeghConfig` | abstract class | `config(env: Environment): T`. Base class for a config class. |
491
+ | `AppConfig` | decorator | `@AppConfig` or `@AppConfig({ schema })`. Register a `MeghConfig` subclass for DI; with `schema`, its `config()` result is validated against that DTO class on first use and at boot. |
492
+ | `AppConfigOptions` | type | `{ schema?: Constructor }`. |
493
+ | `validateEnv` | function | `validateEnv(EnvDto, source?)` validates environment variables against a DTO class and returns them converted. |
494
+ | `ConfigValidationError` | class | Thrown for an invalid environment or config; `source` and `issues` say what failed. |
495
+ | `GetConfig` | function | `GetConfig(ConfigClass)` returns the class's `config()` result; `GetConfig(token: string \| symbol)` returns the value registered for the token. |
496
+ | `MeghConfigClass` | type | A `MeghConfig` subclass. |
497
+ | `Environment` | class | Reads `.env` merged with `process.env` (which wins): `get(key)`, `getOrThrow(key)`, `getAll()`, and static `reload()` to re-read `.env`. |
498
+ | `EnvironmentVariableNotFound` | class | Error thrown by `getOrThrow()` for a missing variable; the name is in `key`. |
499
+
500
+ ## ORM
501
+
502
+ Guides: [ORM](/advanced/orm), [Models](/advanced/orm/models), [Queries](/advanced/orm/queries),
503
+ [Relations](/advanced/orm/relations), [Migrations](/advanced/orm/migrations),
504
+ [Seeding](/advanced/orm/seeding), [Query builder](/advanced/orm/query-builder).
505
+
506
+ The ORM ships inside `@meghjs/core` as a built-in plugin. Connect it with
507
+ `app.useMeghORM()`.
508
+
509
+ ### Models
510
+
511
+ | Export | Kind | Description |
512
+ | --- | --- | --- |
513
+ | `Model` | abstract class | Base class for models. Static query methods (`query`, `find`, `findOrFail`, `where`, `with`, `create`, `paginate`, `transaction`, …) and instance methods (`save`, `fill`, `delete`, `restore`, `related`, …). |
514
+ | `ModelQuery` | class | A query on a model. Nothing runs until `get()`, `first()`, `count()`, `paginate()`, `update()` or `delete()`. |
515
+ | `HasRelation` | class | A `hasMany` / `hasOne` relation of one model instance: `user.related("posts")`. |
516
+ | `PivotRelation` | class | The pivot rows of a `belongsToMany` relation: `user.related("roles").attach([1, 2])`. |
517
+ | `ORM_CONNECTION` | const | `Token<Kysely<any>>` holding the ORM's root Kysely instance. |
518
+ | `modelSchema` | function | `modelSchema(cls): SchemaObject \| undefined`. JSON schema for a model's columns. |
519
+ | `getModelMetadata` | function | `getModelMetadata(cls): ModelMetadata \| undefined`. Column and table metadata from the decorators. |
520
+
521
+ ### Model decorators
522
+
523
+ | Export | Kind | Signature |
524
+ | --- | --- | --- |
525
+ | `Table` | decorator | `@Table(name?: string)`. Defaults to the plural snake_case class name. |
526
+ | `Column` | decorator | `@Column(typeOrOptions?: ColumnType \| ColumnOptions, options?: ColumnOptions)` |
527
+ | `PrimaryKey` | decorator | `@PrimaryKey(options?: ColumnOptions)` |
528
+ | `AutoIncrement` | decorator | `@AutoIncrement()`. A generated integer column. |
529
+ | `Identity` | decorator | Alias of `AutoIncrement`. |
530
+ | `CreatedAt` | decorator | Set to the current time on insert. |
531
+ | `UpdatedAt` | decorator | Set to the current time on every insert and update. |
532
+ | `DeletedAt` | decorator | Soft deletes: `delete()` sets this column instead of removing the row. |
533
+ | `HasMany` | decorator and type | `@HasMany(related: () => C, options?: HasOptions)`. As a type, the field type of a one-to-many relation. |
534
+ | `HasOne` | decorator and type | `@HasOne(related: () => C, options?: HasOptions)`. |
535
+ | `BelongsTo` | decorator and type | `@BelongsTo(related: () => C, options?: BelongsToOptions)`. |
536
+ | `BelongsToMany` | decorator and type | `@BelongsToMany(related: () => C, options?: BelongsToManyDecoratorOptions)`. |
537
+
538
+ ### Relation functions
539
+
540
+ For models that declare relations as fields instead of decorators.
541
+
542
+ | Export | Kind | Signature |
543
+ | --- | --- | --- |
544
+ | `hasMany` | function | `hasMany(related: () => C, foreignKey?: string, localKey?: string)` |
545
+ | `hasOne` | function | `hasOne(related: () => C, foreignKey?: string, localKey?: string)` |
546
+ | `belongsTo` | function | `belongsTo(related: () => C, foreignKey?: string, ownerKey?: string)` |
547
+ | `belongsToMany` | function | `belongsToMany(related: () => C, options?: BelongsToManyOptions)` |
548
+
549
+ ### Connection and configuration
550
+
551
+ | Export | Kind | Description |
552
+ | --- | --- | --- |
553
+ | `createDatabase` | function | `createDatabase(options: ResolvedDatabaseOptions): Kysely<any>`. |
554
+ | `resolveDatabaseOptions` | function | `resolveDatabaseOptions(options?, env?)`. Apply environment variables and the URL to database options. |
555
+ | `DatabaseConfigError` | class | Thrown for invalid database settings. |
556
+ | `ormPlugin` | const | The ORM as a Megh plugin. Registered automatically. |
557
+ | `setNamingStrategy` | function | `setNamingStrategy("preserve" \| "snake_case")`. |
558
+ | `getNamingStrategy` | function | The current naming strategy. |
559
+ | `DatabaseOptions` | interface | Settings for `useMeghORM()`. |
560
+ | `ResolvedDatabaseOptions` | interface | Settings after the environment and URL are applied. |
561
+ | `Dialect` | type | `"postgres" \| "mysql" \| "sqlite" \| "mssql"`. |
562
+ | `PoolOptions` | interface | Connection pool settings. |
563
+ | `NamingStrategy` | type | `"preserve" \| "snake_case"`. |
564
+
565
+ ### Query builder
566
+
567
+ | Export | Kind | Description |
568
+ | --- | --- | --- |
569
+ | `DB` | const | Table queries without models: `DB.table(name)`, `DB.transaction(fn)`. |
570
+ | `TableQuery` | class | A query on one table, built with `DB.table()`. |
571
+ | `WhereClauses` | class | `where` conditions shared by queries and groups. |
572
+ | `WhereGroup` | class | The conditions inside `where((q) => …)`. |
573
+ | `Operator` | type | Comparison operators accepted by `TableQuery`. |
574
+
575
+ ### Schema and migrations
576
+
577
+ | Export | Kind | Description |
578
+ | --- | --- | --- |
579
+ | `Schema` | class | Creates, changes and drops tables. Migrations defined with `defineMigration` receive one. |
580
+ | `Blueprint` | class | The columns and indexes of a table being created or changed. |
581
+ | `ColumnDefinition` | class | A column being added. Columns are NOT NULL unless `nullable()`. |
582
+ | `ForeignKeyDefinition` | class | A foreign key: `table.foreign("user_id").references("users.id")`. |
583
+ | `SchemaError` | class | Thrown for invalid schema operations. |
584
+ | `Migrations` | class | `new Migrations(db, options)`. Runs and rolls back migrations. |
585
+ | `MigrationError` | class | Thrown when a migration fails. Carries the migration name and those completed. |
586
+ | `defineMigration` | function | `defineMigration({ up, down? })`. A migration written with the schema builder. |
587
+ | `readMigrationFolder` | function | `readMigrationFolder(folder): Promise<Record<string, Migration>>`. |
588
+ | `Migration` | interface | A migration as the runner calls it. |
589
+ | `SchemaMigration` | interface | A migration written with the schema builder. |
590
+ | `MigrationsOptions` | interface | Options for `Migrations`. |
591
+ | `MigrationStatus` | interface | One migration's status. |
592
+ | `ReferentialAction` | type | `ON DELETE` / `ON UPDATE` actions. |
593
+ | `SchemaDialect` | type | `"postgres" \| "mysql" \| "sqlite" \| "mssql"`. |
594
+
595
+ ### Seeders and factories
596
+
597
+ | Export | Kind | Description |
598
+ | --- | --- | --- |
599
+ | `Seeders` | class | `new Seeders(db, options?)`. Runs seeders. |
600
+ | `SeedError` | class | Thrown when a seeder fails. |
601
+ | `defineSeeder` | function | Identity helper that type-checks a seeder. |
602
+ | `readSeederFolder` | function | `readSeederFolder(folder): Promise<Record<string, Seeder>>`. |
603
+ | `seederName` | function | A seeder's name from its file name. |
604
+ | `ENTRY_SEEDER` | const | `"database"`, the seeder `run()` starts from when given no name. |
605
+ | `Seeder` | interface | A seeder. |
606
+ | `SeedContext` | interface | What a seeder's `run()` receives. |
607
+ | `SeedersOptions` | interface | Options for `Seeders`. |
608
+ | `Factory` | class | Builds and creates model instances from a definition. |
609
+ | `defineFactory` | function | `defineFactory(model, definition: (ctx: FactoryContext) => FactoryAttributes<C>): Factory<C>`. |
610
+ | `useFaker` | function | `useFaker(faker)`. Set the Faker instance factories use. |
611
+ | `getFaker` | function | `getFaker(): Promise<Faker>`. The Faker instance, loaded from the app on first use. |
612
+ | `FactoryAttributes` | type | Attributes a factory definition returns. |
613
+ | `FactoryContext` | interface | What a factory definition receives. |
614
+
615
+ ### ORM types
616
+
617
+ | Export | Kind | Description |
618
+ | --- | --- | --- |
619
+ | `ColumnType` | type | Column types, which pick the SQL type and value conversion. |
620
+ | `ColumnOptions` | interface | Options for `@Column`. |
621
+ | `ColumnMetadata` | interface | A column's metadata. |
622
+ | `ModelMetadata` | interface | A model's metadata. |
623
+ | `HasOptions` | interface | Options for `@HasMany` and `@HasOne`. |
624
+ | `BelongsToOptions` | interface | Options for `@BelongsTo`. |
625
+ | `BelongsToManyOptions` | interface | Options for `belongsToMany()`. |
626
+ | `BelongsToManyDecoratorOptions` | interface | Options for `@BelongsToMany`, including `pivotColumns`. |
627
+ | `Cast` | type | A column cast: a built-in name or a `CustomCast`. |
628
+ | `CustomCast` | interface | `{ get, set }` conversion between database and model values. |
629
+ | `Columns` | type | A model's column fields. |
630
+ | `ColumnKeys` | type | Names of a model's columns. |
631
+ | `RelationKeys` | type | Names of a model's relations. |
632
+ | `RelationPaths` | type | Relation paths for `with()`, up to three levels. |
633
+ | `BelongsToManyKeys` | type | Names of `belongsToMany` relations. |
634
+ | `HasRelationKeys` | type | Names of `hasMany` / `hasOne` relations. |
635
+ | `PivotOf` | type | Pivot columns of a `belongsToMany` relation. |
636
+ | `TimestampKeys` | type | Timestamp columns when `timestamps = true`. |
637
+ | `Row` | type | A model's row as loaded from the database. |
638
+ | `ModelClass` | interface | The static side of a model class. |
639
+ | `CreateInput` | type | `create()` input. |
640
+ | `UpdateInput` | type | `update()` / `fill()` input. |
641
+ | `PrimaryKeyValue` | type | Value type of a model's primary key. |
642
+ | `TableOf` | type | Kysely table interface for a model. |
643
+ | `DatabaseOf` | type | Kysely database interface for a set of models. |
644
+ | `ComparisonOperator` | type | Operators accepted by `where`. |
645
+ | `Counted` | type | The `<relation>_count` field `withCount()` adds. |
646
+ | `CursorPageRequest` | interface | Request for `cursorPaginate()`. |
647
+ | `CursorPaginated` | interface | Result of `cursorPaginate()`. |
648
+ | `SimplePaginated` | interface | Result of `simplePaginate()` (no total). |
649
+ | `ModelAt` | type | The model at the end of a relation path. |
650
+ | `RelationConstraint` | type | A function that narrows a related query. |
651
+ | `Scope` | type | A reusable query scope. |
652
+ | `RelatedRef` | type | A related row's key, or the related model itself. |
653
+
654
+ ## Events
655
+
656
+ Guide: [Events](/advanced/events).
657
+
658
+ | Export | Kind | Signature / description |
659
+ | --- | --- | --- |
660
+ | `MeghEvent` | abstract class | `new MyEvent(payload)`. Base class for events; sets `name` and `timestamp`. |
661
+ | `MeghEventListener` | abstract class | `handler(event: TEvent): void \| Promise<void>`. Base class for listeners. |
662
+ | `EventDispatcher` | class | `dispatch(event: MeghEvent, option?: DispatchOption): Promise<void>`. |
663
+ | `EventRegistry` | class | `EventRegistry.getInstance()`, then `register(EventClass, listener)`, `once`, `unregister`, `getListeners`, `clear`. |
664
+ | `EventQueue` | class | The in-memory queue for `queue: true` dispatches. `EventQueue.getInstance()`, `getFailedJobs()`, `clearFailed()`, `whenIdle()`. |
665
+ | `DispatchOption` | type | `{ queue?, delay?, retry?, retryDelay?, broadcast? }`. `delay` is ms or `"500ms"`, `"5s"`, `"2m"`, `"1h"`, `"1d"`. |
666
+ | `BroadcastOption` | type | `SocketBroadcastOption \| false`. |
667
+ | `SocketBroadcastOption` | type | `{ type: "socket"; channel: string; room?: string }`. |
668
+ | `MeghEventInterface` | interface | `{ name: string; timestamp: number }`. |
669
+ | `MeghEventListenerInterface` | interface | `{ handler(event): void \| Promise<void> }`. |
670
+ | `FailedEventJob` | interface | A listener that kept failing after its retries. |
671
+ | `Broadcast` | interface | `{ to: string; private?: boolean; payload: any }`. |
672
+ | `parseDelay` | function | `parseDelay(input: string \| number): number`. Parse a delay into milliseconds. |
673
+
674
+ ## Queue
675
+
676
+ Guide: [Queue](/advanced/queue).
677
+
678
+ | Export | Kind | Signature / description |
679
+ | --- | --- | --- |
680
+ | `Queue` | decorator | `@Queue(config: QueueConfig)`. Register a `MeghQueue` subclass for DI and start its worker unless `worker: false`. |
681
+ | `JobHandler` | decorator | `@JobHandler(name: string)`. Mark a method as the processor for a named job. |
682
+ | `MeghQueue` | abstract class | Produces and consumes jobs: `add`, `delay`, `dispatch`, `getJob`, `getJobs`, `clean`, `pause`, `resume`, `close`, `getQueue`, `getWorker`, `on`, `startWorker`. |
683
+ | `MeghWorker` | decorator | `@MeghWorker(config: WorkerConfig)`. Register a standalone worker class. Doesn't start it. |
684
+ | `MeghWorkerBase` | abstract class | `process(job: Job<T>): Promise<any>`. Base class for standalone workers; `start()`, `close()`, `getWorker()`. |
685
+ | `QueueConfig` | interface | `{ name, adapter?, worker?, handler?, driver? }`. |
686
+ | `WorkerConfig` | interface | `{ queue, connection?, concurrency?, options?, autoStart?, driver? }`. |
687
+ | `Job` | type | BullMQ's `Job`, re-exported. |
688
+ | `JobsOptions` | type | BullMQ's `JobsOptions`, re-exported. |
689
+ | `setQueueDriver` | function | `setQueueDriver(driver: QueueDriver \| undefined)`. Set the default driver. |
690
+ | `resolveQueueDriver` | function | `resolveQueueDriver(explicit?)`. The driver in effect: explicit, then `setQueueDriver()`, then `MEGH_QUEUE_DRIVER`, then `"bullmq"`. |
691
+ | `QueueDriver` | type | `"bullmq" \| "memory" \| "sync"`. |
692
+ | `waitForMemoryQueues` | function | Resolve when every in-memory queue is idle. For tests. |
693
+ | `resetMemoryQueues` | function | Clear every in-memory queue. For tests. |
694
+ | `MemoryJob` | class | A job in the in-memory driver. |
695
+ | `MemoryJobState` | type | `"waiting" \| "delayed" \| "active" \| "completed" \| "failed"`. |
696
+ | `getRegisteredWorkers` | function | Every `@MeghWorker` class, in declaration order. |
697
+ | `startRegisteredWorkers` | function | Resolve and start every `@MeghWorker` whose `autoStart` isn't `false`. The application calls it at boot. |
698
+ | `attachWorkerLogging` | function | `attachWorkerLogging(worker, queue)`. Log failed jobs and worker errors. |
699
+
700
+ ```ts
701
+ add(data: T, options?: JobsOptions): Promise<Job<T>>
702
+ add(name: string, data: T, options?: JobsOptions): Promise<Job<T>>
703
+ delay(data: T, delayMs: number, options?: JobsOptions): Promise<Job<T>>
704
+ delay(name: string, data: T, delayMs: number, options?: JobsOptions): Promise<Job<T>>
705
+ dispatch(name: string, data: T, delayMs?: number, options?: JobsOptions): Promise<Job<T>>
706
+ ```
707
+
708
+ ## Mail
709
+
710
+ Guide: [Mail](/advanced/mail).
711
+
712
+ | Export | Kind | Signature / description |
713
+ | --- | --- | --- |
714
+ | `Mailable` | abstract class | One kind of email. `envelope()`, `content()` (required), `attachments()`; each may be async. |
715
+ | `Mailer` | class | Injectable. `to()`, `cc()`, `bcc()`, `send()`, `queue()`, `later(delay, mail)`, `mailer(name)`. Static: `configure()`, `fake()`, `restore()`, `close()`, `reset()`. |
716
+ | `PendingMail` | class | Returned by `mailer.to()`: add recipients, then `send()`, `queue()` or `later()`. |
717
+ | `MailFake` | class | Returned by `Mailer.fake()`. `assertSent`, `assertNotSent`, `assertNothingSent`, `assertSentCount`, `assertQueued`, `assertNotQueued`, `assertNothingQueued`, `sentOf`, `queuedOf`, `sent`, `queued`, `restore`. |
718
+ | `SentMail` | class | A recorded message: `mailer`, `mailable`, `message`, `delay`, `hasTo()`, `hasCc()`, `hasBcc()`, `hasFrom()`. |
719
+ | `MailConfig` | interface | `{ default?, from?, mailers?, queue?, allowFileAccess?, allowUrlAccess?, attachmentRoot? }` for `useMail()`. URL attachments are off unless `allowUrlAccess` is `true`. |
720
+ | `MailQueueConfig` | interface | `{ name?, adapter?, driver?, worker?, jobOptions? }`. |
721
+ | `MailerConfig` | type | One mailer's settings: `{ transport: "smtp" \| "sendgrid" \| "mailgun" \| "postmark" \| "resend" \| "failover" \| "log" \| "array", ... }`, or a `MailTransport`. |
722
+ | `MailTransport` | interface | `{ send(message: MailMessage): Promise<{ messageId?, response? } \| void>; close?() }`. Implement it for your own mailer. |
723
+ | `MailMessage` | interface | A built message: `from`, `to`, `cc`, `bcc`, `replyTo`, `subject`, `html?`, `text?`, `attachments`, `headers`. |
724
+ | `MailEnvelope`, `MailContent`, `MailAttachment`, `MailAddress`, `MailAddressLike` | types | What a `Mailable` returns, and address forms. |
725
+ | `SentMessage`, `QueuedMessage` | types | What `send()` and `queue()`/`later()` resolve to. |
726
+ | `SmtpTransport`, `SendGridTransport`, `MailgunTransport`, `PostmarkTransport`, `ResendTransport`, `FailoverTransport`, `LogTransport`, `ArrayTransport` | classes | The built-in transports. |
727
+ | `MailQueue` | class | The `MeghQueue` behind `queue()` and `later()`. |
728
+ | `MailError` | class | A misconfiguration, or a mailable that cannot be built. |
729
+ | `MailTransportError` | class | A provider refused the message: `provider`, `status`, `body`. |
730
+ | `mailConfigFromEnv`, `resolveMailConfig`, `mailerProblem` | functions | Read `MEGH_MAIL_*`, merge options over it, and check a mailer's settings. |
731
+
732
+ ## Scheduler
733
+
734
+ Guide: [Scheduler](/advanced/scheduler).
735
+
736
+ | Export | Kind | Signature / description |
737
+ | --- | --- | --- |
738
+ | `ScheduledTask` | decorator | `@ScheduledTask()`. Mark a class as holding scheduled jobs and register it for DI. |
739
+ | `Cron` | decorator | `@Cron(expression: string, options?: { name?, disabled?, timezone?, runOnInit? })`. Run the method on a cron expression (node-cron). |
740
+ | `Interval` | decorator | `@Interval(ms: number, options?: { name?, disabled? })`. Run the method every `ms` milliseconds. |
741
+ | `Timeout` | decorator | `@Timeout(ms: number, options?: { name?, disabled? })`. Run the method once, `ms` milliseconds after start. |
742
+ | `MeghScheduler` | class | Runs the jobs of registered task classes: `addTaskClasses(tasks)`, `start()`, `stopAll()`. The application creates one for `useScheduler()`. |
743
+
744
+ Register task classes with `app.useScheduler([...])`.
745
+
746
+ ## Cache
747
+
748
+ Guide: [Caching](/advanced/caching).
749
+
750
+ | Export | Kind | Signature / description |
751
+ | --- | --- | --- |
752
+ | `CacheManager` | class | Key/value cache with tag invalidation, backed by memory or Redis. TTLs are in seconds. |
753
+ | `CacheManagerOptions` | type | `CacheOptions` fields plus `redis?` (an ioredis client) and `sweepIntervalMs?`. |
754
+
755
+ ```ts
756
+ CacheManager.configure(options?: CacheManagerOptions): void // defaults for new instances
757
+ CacheManager.close(): Promise<void> // static: close every instance
758
+ get<T>(key: string): Promise<T | null>
759
+ set<T>(key: string, value: T, ttl?: number, tags?: string[]): Promise<void> // ttl defaults to 3600
760
+ delete(key: string): Promise<void>
761
+ invalidateTags(tags: string | string[]): Promise<void>
762
+ sweep(): number
763
+ close(): Promise<void>
764
+ ```
765
+
766
+ Enable it with `app.useCache(options?)`.
767
+
768
+ ## Storage and uploads
769
+
770
+ Guide: [File uploads](/advanced/file-uploads).
771
+
772
+ | Export | Kind | Description |
773
+ | --- | --- | --- |
774
+ | `FileStorage` | class | Saves uploaded files under a root directory (`<cwd>/public` by default) with an upload policy. Injectable. |
775
+ | `UploadFileFromRequest` | function | `UploadFileFromRequest(req: IRequest, options?)`. Save the request's file. Options: `saveAs?`, `dest?`, `preserveFilename?`, `allowedExtensions?`. |
776
+ | `MultipartFile` | type | An uploaded file from `@fastify/multipart`. |
777
+ | `FileStorageInterface` | interface | `transform`, `save`, `saveAll`, `remove`. |
778
+ | `FileStorageOptions` | interface | `UploadPolicy` plus `baseDir?`. |
779
+ | `UploadPolicy` | interface | `{ allowedExtensions?, allowedMimeTypes?, maxFileSize? }`. `maxFileSize` defaults to 50 MB. |
780
+ | `SaveOptions` | interface | `UploadPolicy` plus `overwrite?`, `to?`, `transform?`. |
781
+ | `SaveOptionsSingle` | interface | `SaveOptions` for `save()`. |
782
+ | `SavedFileInfo` | interface | `{ filename, originalFilename, size, uploadPath, staticPath }`. |
783
+ | `TransformOptions` | interface | Image transform: `{ resize?, format?, quality? }`. |
784
+
785
+ ```ts
786
+ configure(options: FileStorageOptions): this
787
+ transform(options: TransformOptions): FileStorage
788
+ save(file: MultipartFile, options?: SaveOptionsSingle): Promise<SavedFileInfo>
789
+ saveAll(files: MultipartFile[], options?: SaveOptions): Promise<SavedFileInfo[]>
790
+ remove(filepath: string): Promise<void>
791
+ getUploadFile(filePath: string)
792
+ download(filepath: PathLike)
793
+ downloadAs(filepath: PathLike, filename: string)
794
+ ```
795
+
796
+ Upload parameters are declared with [`@UploadFile` and `@UploadFiles`](#parameters).
797
+
798
+ ## Realtime
799
+
800
+ Guide: [WebSocket](/microservices/websocket).
801
+
802
+ | Export | Kind | Signature / description |
803
+ | --- | --- | --- |
804
+ | `SocketIoServer` | const | `Token<Server>`. The Socket.IO server, registered by `useSocketIo()`. |
805
+ | `Subscribe` | decorator | `@Subscribe(event: string)`. Handle a Socket.IO event. |
806
+ | `PrivateChannel` | decorator | `@PrivateChannel(channelResolver?: (socket) => string)`. Mark a subscriber method as private. |
807
+ | `DispatchNow` | decorator | `@DispatchNow(event: string, options?: DispatchOptions)`. Emit the method's return value as `event` after it runs. |
808
+ | `SocketEventDispatcher` | class | `dispatch(event: string, data, options?: DispatchOptions)`. Emit an event over Socket.IO. |
809
+ | `SocketContextService` | class | The socket of the event being handled: `getSocket()`. |
810
+ | `DispatchOptions` | type | `{ room?, broadcast?, transports?, retry?, retryDelay? }`. |
811
+
812
+ ## OpenAPI
813
+
814
+ Guide: [OpenAPI](/microservices/openapi).
815
+
816
+ ### Decorators
817
+
818
+ | Export | Kind | Signature / description |
819
+ | --- | --- | --- |
820
+ | `OpenApi` | decorator | `@OpenApi(options: OpenApiOptions)`. Document a controller, route or property. |
821
+ | `ApiResponse` | decorator | `@ApiResponse(status: number, type?: ResponseType \| ApiResponseOptions, description?: string)`. Document a response of a route or every route of a controller. |
822
+ | `OpenApiProperty` | decorator | `@OpenApiProperty(options?)`. Document a DTO property (`ParamSchema` fields plus `isArray`, `items`, `nullable`, `readOnly`, …). |
823
+ | `OpenApiSchema` | decorator | `@OpenApiSchema()`. Add the class to `components.schemas`. |
824
+ | `OpenApiResponse` | function | Deprecated. `OpenApiResponse(code, model, description?)`. Documents a `{ code, status, data }` wrapper Megh doesn't send. Use `@ApiResponse`. |
825
+ | `OpenApiOk` | function | Deprecated. `OpenApiResponse(200, model, "Success")`. |
826
+
827
+ ### Functions
828
+
829
+ | Export | Kind | Description |
830
+ | --- | --- | --- |
831
+ | `registerSchemaProvider` | function | `registerSchemaProvider(provider: SchemaProvider)`. Describe classes the DTO reader doesn't. |
832
+ | `generateClassSchema` | function | `generateClassSchema(classType, options?: ClassSchemaOptions)`. JSON schema for a DTO class. |
833
+ | `generateSwaggerSchema` | function | `generateSwaggerSchema(classes, extraClasses?)`. `components.schemas` for `@OpenApiSchema` classes. |
834
+ | `GetSchema` | function | Alias of `generateSwaggerSchema`. |
835
+ | `inlineSchemaRefs` | function | Replace `#/components/schemas/*` refs with inline schemas. |
836
+ | `normalizeParamsToJsonSchema` | function | `normalizeParamsToJsonSchema(params, requiredKeys?)`. Turn a `ParamsSchemaMap` into an object schema. |
837
+
838
+ ### Options
839
+
840
+ | Export | Kind | Description |
841
+ | --- | --- | --- |
842
+ | `OpenApiUiOptions` | type | Options for `useOpenApi()`: `info`, `routePrefix` (default `/swagger`), `provider` (`"default"` or `"scalar"`), `auth`, `servers`, `tags`, `security`, `components`, `uiConfig`, `scalar`, `logo`, `theme`, `openapi`, `paths`. |
843
+ | `OpenApiOptions` | type | Options for `@OpenApi()` on a route: `summary`, `description`, `tags`, `params`, `query`, `headers`, `requestBody`, `response`, `exclude`, `deprecated`, `security`, … |
844
+ | `OpenApiAuth` | type | `"bearer" \| "apiKey" \| SecuritySchemeObject`. |
845
+ | `ApiResponseOptions` | interface | `{ type?, description?, contentType?, example? }`. |
846
+ | `ResponseType` | type | A DTO class, `[Class]`, `Paginated(Class)`, a JSON schema or a `$ref`. |
847
+ | `PaginatedType` | interface | What `Paginated(Class)` returns. |
848
+ | `SchemaProvider` | type | `(cls) => SchemaObject \| undefined`. |
849
+ | `ClassSchemaOptions` | type | `{ inline?, components? }` for `generateClassSchema`. |
850
+ | `SchemaClass` | type | A DTO class. |
851
+ | `ParamSchema` | type | Schema of one parameter. |
852
+ | `ParamsSchemaMap` | type | `Record<string, ParamSchema>`. |
853
+ | `RequestBodyOptions` | type | Options for `requestBody`. |
854
+ | `RequestBodyMediaTypeOptions` | type | A media type whose `schema` may be a DTO class. |
855
+ | `ResponseBodyOptions` | type | A response described as a JSON schema. |
856
+ | `ResponsesOptions` | type | Responses keyed by status code. |
857
+ | `SwaggerUiConfig` | interface | Swagger UI settings. |
858
+ | `SwaggerUiLogo` | interface | Swagger UI top-bar logo. |
859
+ | `SwaggerUiTheme` | interface | Swagger UI page title, CSS, scripts and favicon. |
860
+ | `SwaggerUiThemeFile` | interface | A theme file. |
861
+ | `SwaggerUiFavicon` | interface | A favicon file. |
862
+ | `ScalarConfig` | interface | Scalar settings. |
863
+
864
+ ### OpenAPI document types
865
+
866
+ Types for the OpenAPI 3 document: `InfoObject`, `ContactObject`,
867
+ `LicenseObject`, `ServerObject`, `ServerVariableObject`, `PathsObject`,
868
+ `PathItemObject`, `OperationObject`, `ExternalDocumentationObject`,
869
+ `ParameterObject`, `ParameterBaseObject`, `HeaderObject`, `SchemaObject`,
870
+ `ArraySchemaObject`, `NonArraySchemaObject`, `BaseSchemaObject`,
871
+ `ArraySchemaObjectType`, `NonArraySchemaObjectType`, `DiscriminatorObject`,
872
+ `XMLObject`, `ReferenceObject`, `ExampleObject`, `MediaTypeObject`,
873
+ `EncodingObject`, `RequestBodyObject`, `ResponsesObject`, `ResponseObject`,
874
+ `LinkObject`, `CallbackObject`, `SecurityRequirementObject`,
875
+ `ComponentsObject`, `SecuritySchemeObject`, `HttpSecurityScheme`,
876
+ `ApiKeySecurityScheme`, `OAuth2SecurityScheme`, `OpenIdSecurityScheme` and
877
+ `TagObject`.
878
+
879
+ ## Logging
880
+
881
+ Guide: [Logging](/advanced/logging).
882
+
883
+ | Export | Kind | Signature / description |
884
+ | --- | --- | --- |
885
+ | `LoggerService` | class | Application logger backed by one shared pino instance. Injectable. `info`, `error`, `warn`, `debug`, `fatal`, `trace` take `(message: string, obj?: any)`; `getLogger()` returns the pino logger. |
886
+ | `LoggerConfig` | interface | `{ level?, pretty?, destination? }`. |
887
+ | `buildLoggerOptions` | function | `buildLoggerOptions(config?, env?): pino.LoggerOptions`. The pino options Megh uses. |
888
+ | `getRequestId` | function | `getRequestId(): string \| undefined`. The ID of the request being handled. |
889
+ | `requestContext` | object | Per-request values: `get`, `getOrThrow`, `has`, `set`, `delete`, `user`, `getUser<T>()`, `requestId`, `active`, `run(fn, init?)`. See [Request Context](/core-concept/request-context). |
890
+ | `createContextKey` | function | `createContextKey<T>(name): ContextKey<T>`. A typed key for `requestContext`. |
891
+ | `ContextKey`, `RequestContextInit` | types | A typed key, and `{ requestId?, user?, values? }` for `requestContext.run()`. |
892
+ | `DEFAULT_REQUEST_ID_HEADER` | const | `"x-request-id"`. |
893
+ | `RequestIdOptions` | type | `false \| { header?, generate? }`, for the `requestId` application option. |
894
+
895
+ ```ts
896
+ LoggerService.getPino(): pino.Logger // the shared instance
897
+ LoggerService.configure(config?: LoggerConfig): pino.Logger // replace it
898
+ LoggerService.child(bindings: pino.Bindings): pino.Logger
899
+ ```
900
+
901
+ ## Health
902
+
903
+ Guide: [Health checks](/advanced/health).
904
+
905
+ | Export | Kind | Description |
906
+ | --- | --- | --- |
907
+ | `HealthCheck` | type | `() => unknown \| Promise<unknown>`. Passes unless it throws, rejects or returns `false`. |
908
+ | `HealthOptions` | interface | `{ path?, readyPath?, checks?, timeout? }`. Defaults: `/health`, `/ready`, 5000 ms. |
909
+ | `HealthCheckResult` | interface | `{ status: "up" \| "down"; durationMs; error? }`. |
910
+ | `ReadinessReport` | interface | `{ status: "ok" \| "error"; checks }`. |
911
+ | `HealthRegistry` | class | Runs readiness checks and serves the health routes. The application creates one. |
912
+ | `SKIP_GLOBAL_MIDDLEWARE` | const | Route config flag that makes `useMiddlewares` skip a route. |
913
+
914
+ Enable with `app.useHealth(options?)` and add checks with `app.addHealthCheck(name, check)`.
915
+
916
+ ## Plugins
917
+
918
+ Guide: [Plugins](/advanced/plugins).
919
+
920
+ | Export | Kind | Description |
921
+ | --- | --- | --- |
922
+ | `definePlugin` | function | `definePlugin(plugin: MeghPlugin): MeghPlugin`. Identity helper that type-checks a plugin. |
923
+ | `MeghPlugin` | interface | `{ name: string; dependsOn?: string[]; register(ctx: PluginContext): void }`. |
924
+ | `PluginContext` | interface | `{ app, container, http, logger, extend(name, method), onInit, onReady, onClose, addHealthCheck }`. |
925
+ | `PluginOptions` | type | `{ plugins?: MeghPlugin[]; autoloadPlugins?: boolean }`, part of `MeghApplicationOptions`. |
926
+
927
+ ## Testing
928
+
929
+ Guide: [Testing](/advanced/testing).
930
+
931
+ | Export | Kind | Description |
932
+ | --- | --- | --- |
933
+ | `MeghTest` | class | Static test helpers (below). |
934
+ | `TestApplication` | interface | Test client: `get`, `post`, `put`, `patch`, `delete`, `options` take `(url, options?: InjectOptions)`; plus `getController(controller, deps?)`. |
935
+ | `TestAppOptions` | type | `{ controllers: Constructor[] }`. |
936
+ | `TestResponse` | type | The Fastify inject response, or a promise of it. |
937
+
938
+ ```ts
939
+ MeghTest.createTestApplication(options: TestAppOptions): TestApplication
940
+ MeghTest.from(app: MeghApplication): TestApplication
941
+ MeghTest.getController<T>(controller: Constructor<T>, deps?: any[]): T
942
+ MeghTest.getProvider<T>(service: Constructor<T>, deps?: any[]): T
943
+ MeghTest.clean(): void // reset the container
944
+ ```
945
+
946
+ `getController` and `getProvider` register `deps` in place of the class's
947
+ constructor dependencies, in order. `Megh.createTestApplication(options)` is the
948
+ same as `MeghTest.createTestApplication(options)`.
949
+
950
+ ## Types
951
+
952
+ | Export | Kind | Description |
953
+ | --- | --- | --- |
954
+ | `IRequest` | interface | The request type handlers and middleware receive: Fastify's request with Megh's additions. |
955
+ | `IResponse` | interface | Fastify's reply. |
956
+ | `Constructor` | type | `new (...args: any[]) => T`. |
957
+
958
+ ## Other exports
959
+
960
+ These are exported but are mostly used by Megh itself. They may change or be
961
+ removed in a minor release, so prefer the APIs above.
962
+
963
+ ### Metadata keys
964
+
965
+ | Export | Kind |
966
+ | --- | --- |
967
+ | `ROUTE_META_KEY`, `CONTROLLER_META_KEY`, `PARAM_META_KEY`, `QUERY_META_KEY`, `REQUEST_BODY_META_KEY`, `REQUEST_BODY_FILE_KEY`, `REQUEST_BODY_FILES_KEY`, `REQUEST_USER_META_KEY`, `REQUEST_HEADER_META_KEY`, `DATASOURCE_META_KEY`, `AUTHORIZATION_META_KEY`, `API_CONTROLLER_METADATA_KEY` | const (symbols) |
968
+ | `REQUEST_METADATA_KEY`, `HTTP_CODE_META_KEY` | const (symbols) |
969
+ | `CATCH_META_KEY`, `FILTERS_META_KEY` | const (strings) |
970
+
971
+ ### Registries and internals
972
+
973
+ | Export | Kind | Description |
974
+ | --- | --- | --- |
975
+ | `registerController`, `getRegisteredControllers`, `isApiController` | function | The controller registry. |
976
+ | `registerService`, `getRegisteredServices` | function | A service registry. |
977
+ | `createControllerDecorator` | function | Factory behind `@ApiController`. |
978
+ | `getDeclaredFilters` | function | Filters declared with `@UseFilters` for a route. |
979
+ | `registerSocketSubscriber`, `getSocketSubscribers`, `isPrivate`, `getPrivateChannelResolver` | function | Socket subscriber registry. |
980
+ | `EventSubscriberRegistry` | class | Wires `@Subscribe` methods to a socket. |
981
+ | `checkHelpers`, `stringLength`, `isLength` | const / function | Helpers called by compiled validation code. |
982
+ | `ParamMetaOptions`, `ParamMetaFilesOptions`, `MethodParamMeta`, `IRoute`, `FuncRoute`, `StaticFileOptions` | type | Router metadata shapes. |
983
+
984
+ ### Utility functions
985
+
986
+ | Export | Kind | Description |
987
+ | --- | --- | --- |
988
+ | `loadPackageFromClient` | function | Load an optional dependency from the app's `node_modules`. |
989
+ | `PackageLoader` | type | Type of `loadPackageFromClient`. |
990
+ | `isConstructor` | function | Whether a value is a class. |
991
+ | `formatUrl`, `parsedPath`, `normalizePath` | function | Path helpers used by the router. |
992
+ | `sleep` | function | `sleep(ms)`: a promise that resolves after `ms`. |
993
+ | `pick`, `exclude` | function | Copy an object with only, or without, the given paths. |
994
+ | `autoCast`, `normalizeQueryDeep` | function | Convert query and parameter strings to typed values. |
995
+ | `transformObjectByInstanceToObject`, `jsonToJs`, `jsonToInstance` | function | class-transformer and JSON helpers. |
996
+ | `getDataType`, `isValidType`, `isValidJsonString` | function | Type checks used for parameters. |
997
+ | `isClassValidatorClass`, `validateObjectByInstance` | function | class-validator helpers. |
998
+ | `REQUEST_VALIDATION_OPTIONS` | const | class-validator options Megh uses for request DTOs. |
999
+ | `formatValidationMessage` | function | One-line summary of validation issues. |