@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,355 @@
1
+ ---
2
+ title: Validation
3
+ description: Validating request bodies and query strings with DTOs, using Megh's validation decorators or class-validator.
4
+ ---
5
+
6
+ # Validation
7
+
8
+ Megh validates request input with DTOs: classes whose properties carry
9
+ validation decorators. Use a DTO as the type of a `@Body()` or `@Query()`
10
+ parameter, and validation runs before your handler.
11
+
12
+ The decorators come from `@meghjs/core`. They have the same names, options and
13
+ error messages as [class-validator](https://github.com/typestack/class-validator)
14
+ and [class-transformer](https://github.com/typestack/class-transformer), and
15
+ Megh compiles each DTO's rules once into a single function, so validation is
16
+ much faster. DTOs written with class-validator keep working; see
17
+ [Switching from class-validator](#switching-from-class-validator).
18
+
19
+ ## Defining a DTO
20
+
21
+ ```ts [dtos/create-user.dto.ts]
22
+ import { IsString, IsInt, IsEmail, IsOptional, Min, Max } from '@meghjs/core';
23
+
24
+ export class CreateUserDto {
25
+ @IsString()
26
+ name: string;
27
+
28
+ @IsEmail()
29
+ email: string;
30
+
31
+ @IsInt()
32
+ @Min(18)
33
+ @Max(120)
34
+ age: number;
35
+
36
+ @IsOptional()
37
+ @IsString()
38
+ bio?: string;
39
+ }
40
+ ```
41
+
42
+ ## Validating the body
43
+
44
+ Type the `@Body()` parameter with the DTO — that is all that is needed:
45
+
46
+ ```ts [controllers/users.controller.ts]
47
+ import { ApiController, Post, Body } from '@meghjs/core';
48
+ import { CreateUserDto } from '../dtos/create-user.dto';
49
+
50
+ @ApiController('/users')
51
+ export class UsersController {
52
+ @Post()
53
+ create(@Body() body: CreateUserDto) {
54
+ // body is a validated CreateUserDto instance
55
+ return body;
56
+ }
57
+ }
58
+ ```
59
+
60
+ The handler receives the **DTO instance**, not the raw body: getters and
61
+ methods on the class work, and [`@Type` and `@Transform`](#converting-values)
62
+ have been applied.
63
+
64
+ ### Unknown properties are rejected
65
+
66
+ A property that is not declared on the DTO fails with 400, which prevents mass
67
+ assignment. Arrays and primitives sent to an object DTO are rejected too. To
68
+ accept a property without checking it, mark it with `@Allow()`.
69
+
70
+ ### Error response
71
+
72
+ When validation fails the request is rejected with **400** before the handler
73
+ runs:
74
+
75
+ ```json
76
+ {
77
+ "code": 400,
78
+ "status": "Error",
79
+ "message": "email must be an email",
80
+ "errors": [
81
+ {
82
+ "path": "email",
83
+ "constraints": { "isEmail": "email must be an email" }
84
+ }
85
+ ]
86
+ }
87
+ ```
88
+
89
+ `message` joins all messages with `; `. Nested properties use dotted paths
90
+ such as `address.city` and `items.0.name`.
91
+
92
+ Every decorator takes a `message` option, as a string or a function.
93
+ `$property`, `$value`, `$target` and `$constraint1`, `$constraint2`… are
94
+ filled in:
95
+
96
+ ```ts
97
+ @MinLength(8, { message: '$property needs at least $constraint1 characters' })
98
+ password: string;
99
+ ```
100
+
101
+ ### Without decorator metadata
102
+
103
+ tsx, esbuild and SWC do not emit decorator metadata, so Megh cannot see the
104
+ parameter type. Pass it explicitly:
105
+
106
+ ```ts
107
+ create(@Body({ type: CreateUserDto }) body: CreateUserDto) {}
108
+ ```
109
+
110
+ Without metadata, a `@Body()` or `@Query()` with no `type` stops startup with
111
+ an error that names the route and the compiler setting, rather than leaving
112
+ the DTO unvalidated. Pass `{ validate: false }` to take the raw value.
113
+
114
+ ## Validating the query string
115
+
116
+ The same applies to `@Query()`. Query values arrive as strings; Megh converts
117
+ them to the property's type (`?page=2` becomes the number `2`) before
118
+ validating:
119
+
120
+ ```ts
121
+ export class ListUsersDto {
122
+ @IsOptional()
123
+ @IsInt()
124
+ @Min(1)
125
+ page?: number;
126
+ }
127
+
128
+ @Get()
129
+ index(@Query() query: ListUsersDto) {
130
+ return { page: query.page ?? 1 };
131
+ }
132
+ ```
133
+
134
+ ## Decorators
135
+
136
+ | Kind | Decorators |
137
+ |------|------------|
138
+ | Presence | `IsOptional`, `IsDefined`, `IsNotEmpty`, `IsEmpty`, `Allow`, `ValidateIf(condition)` |
139
+ | Type | `IsString`, `IsNumber(options?)`, `IsInt`, `IsBoolean`, `IsDate`, `IsArray`, `IsObject`, `IsEnum(entity)` |
140
+ | Values | `IsIn(values)`, `IsNotIn(values)` |
141
+ | Numbers | `Min(n)`, `Max(n)`, `IsPositive`, `IsNegative` |
142
+ | Strings | `MinLength(n)`, `MaxLength(n)`, `Length(min, max?)`, `Matches(pattern, modifiers?)`, `IsEmail(options?)`, `IsUUID(version?)`, `IsUrl(options?)` |
143
+ | Arrays | `ArrayNotEmpty`, `ArrayMinSize(n)`, `ArrayMaxSize(n)` |
144
+ | Nested | `ValidateNested`, with `Type(() => Class)` |
145
+ | Conversion | `Type(() => Class)`, `Transform(fn)` |
146
+
147
+ They behave as their class-validator namesakes. Pass `{ each: true }` to check
148
+ every item of an array instead of the array itself:
149
+
150
+ ```ts
151
+ @IsString({ each: true })
152
+ @MaxLength(20, { each: true })
153
+ tags: string[];
154
+ ```
155
+
156
+ `IsOptional` skips the other rules when the value is `null` or `undefined`.
157
+ `ValidateIf((dto, value) => …)` skips them when the condition is false.
158
+
159
+ ### Email, UUID and URL
160
+
161
+ `@IsEmail()` with default options is checked by Megh itself and accepts exactly
162
+ the addresses class-validator accepts. `@IsUUID()`, `@IsUrl()` and
163
+ `@IsEmail(options)` with options use the [validator](https://github.com/validatorjs/validator.js)
164
+ package, as class-validator does; install it to use them:
165
+
166
+ ```sh
167
+ npm i validator
168
+ ```
169
+
170
+ An address containing an unpaired UTF-16 surrogate fails `@IsEmail` with the
171
+ normal 400 (class-validator throws on it, which becomes a 500).
172
+
173
+ ## Nested objects
174
+
175
+ Mark the property with `@ValidateNested()` and give its class with
176
+ `@Type()`, so the value becomes an instance of that class and is validated
177
+ with its own rules. Arrays work the same way:
178
+
179
+ ```ts
180
+ import { IsString, MinLength, ValidateNested, Type, IsArray } from '@meghjs/core';
181
+
182
+ class AddressDto {
183
+ @IsString()
184
+ @MinLength(2)
185
+ city: string;
186
+ }
187
+
188
+ class ItemDto {
189
+ @IsString()
190
+ sku: string;
191
+ }
192
+
193
+ export class CreateOrderDto {
194
+ @ValidateNested()
195
+ @Type(() => AddressDto)
196
+ address: AddressDto;
197
+
198
+ @IsArray()
199
+ @ValidateNested({ each: true })
200
+ @Type(() => ItemDto)
201
+ items: ItemDto[];
202
+ }
203
+ ```
204
+
205
+ Unknown properties are rejected inside nested objects too. Errors use dotted
206
+ paths: `address.city`, `items.1.sku`.
207
+
208
+ ## Converting values
209
+
210
+ `@Type(() => X)` converts a value before it is validated: `Number`, `String`,
211
+ `Boolean` and `Date` convert primitives (`Boolean('false')` is `true`, as in
212
+ class-transformer), and a class turns a nested object into an instance.
213
+
214
+ `@Transform` changes a value with your own function. It receives
215
+ `{ value, key, obj, type, options }` and returns the new value:
216
+
217
+ ```ts
218
+ import { IsIn, Transform } from '@meghjs/core';
219
+
220
+ export class ListUsersDto {
221
+ @Transform(({ value }) => (typeof value === 'string' ? value.toLowerCase() : value))
222
+ @IsIn(['name', 'email'])
223
+ sort: string;
224
+ }
225
+ ```
226
+
227
+ Like class-transformer, a transform only runs for properties present in the
228
+ input; defaults set on the class (`sort = 'name'`) apply when it is missing.
229
+
230
+ ## Switching from class-validator
231
+
232
+ Existing class-validator DTOs keep working as before. To switch a DTO, import
233
+ its decorators from `@meghjs/core` instead:
234
+
235
+ ```ts
236
+ import { IsString, MinLength } from 'class-validator'; // [!code --]
237
+ import { Type } from 'class-transformer'; // [!code --]
238
+ import { IsString, MinLength, Type } from '@meghjs/core'; // [!code ++]
239
+ ```
240
+
241
+ Error responses, the values your handler receives and the
242
+ [OpenAPI](/microservices/openapi) schema stay the same.
243
+
244
+ Switch every decorator of a DTO at once. A DTO that mixes `@meghjs/core`
245
+ decorators with class-validator or class-transformer ones fails when the app
246
+ starts, because each library would only check its own rules. Nested DTOs
247
+ (`@Type(() => AddressDto)`) must use Megh's decorators too.
248
+
249
+ Keep a DTO on class-validator if it needs something Megh does not have yet:
250
+
251
+ - custom validators: `@Validate`, `@ValidatorConstraint`, `registerDecorator`
252
+ - class-validator decorators not in the [table](#decorators)
253
+ - `@Expose`, `@Exclude`, and `@Type` with a `discriminator`
254
+ - Megh's `IsArrayNotEmpty` (use `ArrayNotEmpty` instead)
255
+
256
+ ### Faster class-validator DTOs (experimental)
257
+
258
+ Apps that keep class-validator DTOs can have them validated by a function
259
+ compiled from class-validator's own rules:
260
+
261
+ ```ts
262
+ const app = Megh.createApplication({
263
+ experimental: { compiledValidation: true },
264
+ });
265
+ ```
266
+
267
+ or set `MEGH_COMPILED_VALIDATION=1`. Results are the same as without it; DTOs
268
+ it cannot reproduce exactly (nested DTOs, `@Type`, `@Transform`, async
269
+ validators) are validated by class-validator as before. This option may change
270
+ in a minor release.
271
+
272
+ ## Deriving DTOs
273
+
274
+ Rather than repeating fields, derive one DTO from another:
275
+
276
+ | Helper | Result |
277
+ |--------|--------|
278
+ | `PartialType(Dto)` | Every property optional — ideal for updates |
279
+ | `PickType(Dto, ['a', 'b'])` | Only the named properties |
280
+ | `OmitType(Dto, ['a'])` | Everything except the named properties |
281
+
282
+ ```ts [dtos/update-user.dto.ts]
283
+ import { PartialType } from '@meghjs/core';
284
+ import { CreateUserDto } from './create-user.dto';
285
+
286
+ export class UpdateUserDto extends PartialType(CreateUserDto) {}
287
+ ```
288
+
289
+ The derived class keeps the validation and transformation rules of the
290
+ properties it keeps, from class-validator, class-transformer or Megh's own
291
+ decorators, along with their OpenAPI metadata and default values.
292
+ `PartialType` also marks every property `@IsOptional()`, so a missing field
293
+ passes but a present one is still checked.
294
+
295
+ The derived DTO doesn't extend the source: `instanceof CreateUserDto` is
296
+ `false` for an `UpdateUserDto`.
297
+
298
+ ## Extra validators
299
+
300
+ Megh adds validators on top of the class-validator set:
301
+
302
+ ```ts
303
+ import { IsArrayNotEmpty } from '@meghjs/core';
304
+
305
+ export class CreateOrderDto {
306
+ @IsArrayNotEmpty({ message: 'An order needs at least one item' })
307
+ items: number[];
308
+ }
309
+ ```
310
+
311
+ `IsArrayNotEmpty` is a class-validator decorator; in a DTO that uses Megh's
312
+ decorators, use `ArrayNotEmpty` instead.
313
+
314
+ ## Validating by hand
315
+
316
+ To run a DTO's validation outside a route, use `validateDto`:
317
+
318
+ ```ts
319
+ import { validateDto } from '@meghjs/core';
320
+
321
+ const { value, errors } = validateDto(CreateUserDto, input);
322
+ if (errors) {
323
+ // [{ path: 'email', constraints: { isEmail: 'email must be an email' } }]
324
+ }
325
+ ```
326
+
327
+ `value` is the DTO instance and `errors` is `null` when the input is valid,
328
+ the same shape as the 400 response's `errors`. For class-validator DTOs, use
329
+ `transformAndValidate`, which works the same but returns a promise:
330
+
331
+ ```ts
332
+ import { transformAndValidate } from '@meghjs/core';
333
+
334
+ const { value, errors } = await transformAndValidate(CreateUserDto, input);
335
+ ```
336
+
337
+ For input that does not come from a DTO, `validateOrThrow` checks a plain object
338
+ against a rule map and throws a `BadRequestException` on failure:
339
+
340
+ ```ts
341
+ import { validateOrThrow } from '@meghjs/core';
342
+
343
+ validateOrThrow(
344
+ { page: 1 },
345
+ { page: { type: 'number', min: 1, required: true } },
346
+ );
347
+ ```
348
+
349
+ Supported rule types are `string`, `number` (with `min`, `max`, `exact`) and
350
+ `boolean`, each accepting `required`, `optional` and a custom `message`.
351
+
352
+ - `number` accepts any finite number, including `0`.
353
+ - `boolean` accepts `true`, `false`, `"true"`, `"false"`, `0`, `1`, `"0"` and
354
+ `"1"`.
355
+ - A value of `undefined`, `null` or `""` counts as missing.
@@ -0,0 +1,233 @@
1
+ ---
2
+ title: Application
3
+ description: Creating the app, its options, the use* methods, what run() does, lifecycle hooks and shutdown.
4
+ ---
5
+
6
+ # Application
7
+
8
+ Every Megh app is one `MeghApplication`. You create it, turn features on with
9
+ `use*` methods, and start it with `run()`.
10
+
11
+ ```ts [app.ts]
12
+ import { Megh } from '@meghjs/core';
13
+ import { UserController } from './controllers/user.controller';
14
+
15
+ const app = Megh.createApplication();
16
+
17
+ app
18
+ .useCors({ origin: true })
19
+ .useHealth()
20
+ .useControllers([UserController]);
21
+
22
+ app.run(3000);
23
+ ```
24
+
25
+ ## Creating the app
26
+
27
+ `Megh.createApplication(options?)` returns the application. It's a singleton:
28
+ calling it again returns the same app, and the options of the later calls are
29
+ ignored. Pass every option in the first call.
30
+
31
+ | Option | Default | |
32
+ |--------|---------|---|
33
+ | `server` | | Fastify server options (`logger`, `bodyLimit`, `trustProxy`, `https`, …), passed to `Fastify()` |
34
+ | `requestId` | `{}` (on) | Request ID settings. `false` turns request IDs off. See [Logging](/advanced/logging) |
35
+ | `plugins` | `[]` | [Plugins](/advanced/plugins) to register explicitly |
36
+ | `autoloadPlugins` | `true` | Find plugins among the app's dependencies |
37
+ | `experimental.compiledValidation` | `MEGH_COMPILED_VALIDATION` env, else `false` | Compile DTO validation once per class. See [Validation](/core-concept/validation) |
38
+
39
+ ```ts
40
+ const app = Megh.createApplication({
41
+ server: {
42
+ bodyLimit: 2 * 1024 * 1024, // 2 MB
43
+ trustProxy: 1, // one load balancer in front; never `true`
44
+ },
45
+ });
46
+ ```
47
+
48
+ ### The Fastify instance
49
+
50
+ `app.app` is the underlying Fastify instance. Use it for anything Megh doesn't
51
+ wrap, such as registering a Fastify plugin:
52
+
53
+ ```ts
54
+ import etag from '@fastify/etag';
55
+
56
+ app.app.register(etag);
57
+ ```
58
+
59
+ ## Turning features on
60
+
61
+ Each `use*` method returns the app, so they chain. Call them before `run()`.
62
+
63
+ | Method | What it does | Guide |
64
+ |--------|--------------|-------|
65
+ | `useControllers([...])` or `useControllers({ auto: true, path? })` | Register controllers, or scan a folder (default: every `controllers/` folder under `src/`). Calling it again adds to the list | [Controllers](/core-concept/controller) |
66
+ | `useMiddlewares([...])` | Global middleware for every route | [Middleware](/core-concept/middleware) |
67
+ | `useAuthentication(Handler)` | Sets `request.user` on every request | [Authentication](/core-concept/authentication) |
68
+ | `useAuthorization(Handler)` | Decides access for `@Authorized` routes | [Authentication](/core-concept/authentication) |
69
+ | `useExceptionFilters(...)`, `useErrorHandler(fn)`, `useErrorLogger(...)` | Customise error responses and logging | [Error Handling](/core-concept/error-handling) |
70
+ | `useOpenApi(options)` | OpenAPI document and Swagger UI or Scalar | [OpenAPI](/microservices/openapi) |
71
+ | `useCors(options)` | CORS, through `@fastify/cors` | [Security](/production/security#restrict-cors) |
72
+ | `useSecurityHeaders(options?)` | CSP, HSTS, `nosniff` and other security headers | [Security](/production/security#add-security-headers) |
73
+ | `useRateLimit(options?)` | Requests per client per window, 429 over the limit | [Security](/production/security#add-rate-limits) |
74
+ | `useMultipart(options)` | File uploads, through `@fastify/multipart` | [File Uploads](/advanced/file-uploads) |
75
+ | `useStaticFiles(options)` | Serve files, through `@fastify/static` | [File Uploads](/advanced/file-uploads) |
76
+ | `useCompression(options?)` | gzip / brotli responses, through `@fastify/compress` | [Compression](#compression) |
77
+ | `setGlobalPrefix(prefix, { exclude? })` | Serve every route under a prefix such as `/api` | [Controllers](/core-concept/controller#global-prefix-and-versioning) |
78
+ | `useVersioning(options)` | Version routes with `@Version()`, by URI or header | [Controllers](/core-concept/controller#global-prefix-and-versioning) |
79
+ | `useEnvSchema(EnvDto)` | Validate environment variables at boot | [Configuration](/core-concept/configuration#validating-at-boot) |
80
+ | `useCache(options)` | Memory or Redis cache | [Caching](/advanced/caching) |
81
+ | `useMeghORM(options)` | Database connection for MeghORM | [MeghORM](/advanced/orm) |
82
+ | `useScheduler([...])` or `useScheduler({ path })` | Scheduled tasks | [Scheduler](/advanced/scheduler) |
83
+ | `useWorker([...])` | Queue workers | [Queue](/advanced/queue) |
84
+ | `useMail(options?)` | Send mail over SMTP or a provider's API, now or queued | [Mail](/advanced/mail) |
85
+ | `useSocketIo(options)` | Socket.IO server | [WebSocket](/microservices/websocket) |
86
+ | `useHealth(options)`, `addHealthCheck(name, fn)` | `/health` and `/ready` endpoints | [Health Checks](/advanced/health) |
87
+
88
+ Integrations are optional peer dependencies. If one isn't installed, the
89
+ `use*` call throws with the `npm install` command you need.
90
+
91
+ ### `useGlobal`
92
+
93
+ `useGlobal` sets several features in one call. Each key calls the matching
94
+ `use*` method:
95
+
96
+ ```ts
97
+ import path from 'path';
98
+
99
+ app.useGlobal({
100
+ cors: { origin: ['https://example.com'] },
101
+ openApi: { info: { title: 'My API', version: '1.0.0' } },
102
+ controllers: [UserController],
103
+ middlewares: [RequestTimer],
104
+ authorization: AppAuthorization,
105
+ multipart: { limits: { fileSize: 5 * 1024 * 1024 } },
106
+ staticFiles: { root: path.join(process.cwd(), 'public') }, // must be absolute
107
+ });
108
+ ```
109
+
110
+ | Key | Calls |
111
+ |-----|-------|
112
+ | `cors` | `useCors` |
113
+ | `openApi` | `useOpenApi` |
114
+ | `controllers` | `useControllers` |
115
+ | `middlewares` | `useMiddlewares` |
116
+ | `authorization` | `useAuthorization` |
117
+ | `multipart` | `useMultipart` |
118
+ | `staticFiles` | `useStaticFiles` |
119
+ | `scheduler` | `useScheduler` |
120
+ | `compression` | `useCompression` (`true` or options) |
121
+
122
+ ### Compression
123
+
124
+ `useCompression()` compresses responses for clients that send
125
+ `Accept-Encoding`, with `@fastify/compress`
126
+ (`npm install @fastify/compress`). Bodies under 1024 bytes are sent as they
127
+ are. Options go to the plugin:
128
+
129
+ ```ts
130
+ app.useCompression();
131
+ app.useCompression({ encodings: ['br', 'gzip'], threshold: 2048 });
132
+ ```
133
+
134
+ If a proxy or CDN in front of the app already compresses, leave it off.
135
+
136
+ ## Running the app
137
+
138
+ `run(port?, options?)` starts the app. The port defaults to the `PORT`
139
+ environment variable, else `4000`:
140
+
141
+ ```ts
142
+ app.run(); // PORT, else :4000
143
+ app.run(3000); // :3000, whatever PORT says
144
+ app.run(3000, { host: '127.0.0.1', shutdownTimeout: 20_000 });
145
+ ```
146
+
147
+ | Option | Default | |
148
+ |--------|---------|---|
149
+ | `host` | `HOST` or `0.0.0.0` | Interface to listen on |
150
+ | `onListen` | | Called once the server is listening |
151
+ | `shutdownTimeout` | `10000` | Milliseconds to wait for a clean shutdown before exiting with code 1 |
152
+
153
+ The host defaults to `0.0.0.0` so the app is reachable inside a container.
154
+ Pass `127.0.0.1` to accept local connections only. `run()` can be called once;
155
+ a second call throws `App already running`.
156
+
157
+ ### What `run()` does
158
+
159
+ In order:
160
+
161
+ 1. Validates the environment (`useEnvSchema`) and every
162
+ `@AppConfig({ schema })` class.
163
+ 1. Prepares the OpenAPI document, if `useOpenApi` was called.
164
+ 2. Runs the `onInit` hooks. MeghORM connects to the database here.
165
+ 3. Finds controllers (with `{ auto: true }`), then maps controller and inline routes.
166
+ 4. Finds and starts scheduled tasks.
167
+ 5. Installs the error handler and waits for Fastify to be ready.
168
+ 6. Starts Socket.IO, if `useSocketIo` was called.
169
+ 7. Listens for `SIGTERM` and `SIGINT`.
170
+ 8. Starts listening on the port and logs `Application running on <address>`.
171
+ 9. Runs the `onReady` hooks, then `onListen`.
172
+
173
+ A thrown error in steps 1 to 6 stops startup, and the server never listens.
174
+
175
+ ## Lifecycle hooks
176
+
177
+ Register work to run at each stage of the app's life. Call these before
178
+ `run()`; each returns the app, so they chain:
179
+
180
+ ```ts
181
+ app
182
+ .onInit(async () => {
183
+ // After the database connects, before routes are mapped and the server
184
+ // listens. A thrown error aborts startup.
185
+ await cache.warmUp();
186
+ })
187
+ .onReady(() => {
188
+ // The server is listening.
189
+ })
190
+ .onClose(async () => {
191
+ // On shutdown, after the server stops accepting requests.
192
+ await metrics.flush();
193
+ });
194
+ ```
195
+
196
+ Hooks of the same kind run in the order you register them, except `onClose`
197
+ hooks, which run in reverse so that things set up last are torn down first.
198
+ A failing `onClose` hook is logged and the others still run.
199
+
200
+ ## Shutting down
201
+
202
+ `await app.close()` shuts the app down, for example at the end of a test. In
203
+ order, it:
204
+
205
+ 1. Stops the HTTP server, waiting for in-flight requests.
206
+ 2. Stops scheduled tasks.
207
+ 3. Closes queue workers.
208
+ 4. Closes the cache, if `useCache` was called.
209
+ 5. Runs the `onClose` hooks (MeghORM closes its connection in one).
210
+
211
+ Calling `close()` twice is safe: the second call waits for the first.
212
+
213
+ On `SIGTERM` or `SIGINT`, `run()` calls `close()` and exits with code 0. If
214
+ shutdown fails, or takes longer than `shutdownTimeout`, it exits with code 1.
215
+ See [Deployment](/production/deployment) for running behind a process manager
216
+ or in a container.
217
+
218
+ ## Development and production
219
+
220
+ `app.isDevelopment()` is true only when `NODE_ENV=development`. An unset
221
+ `NODE_ENV` counts as production. In production mode, 5xx details are hidden
222
+ and logs are written as JSON. Set `NODE_ENV=development` locally to get
223
+ detailed errors, pretty logs and any docs you gate behind `isDevelopment()`:
224
+
225
+ ```ts
226
+ if (app.isDevelopment()) {
227
+ app.useOpenApi({ info: { title: 'My API', version: '1.0.0' } });
228
+ }
229
+ ```
230
+
231
+ Megh loads `.env` into `process.env` when it is first imported. Set
232
+ `MEGH_DOTENV=false` to skip that and manage the environment yourself. See
233
+ [Configuration](/core-concept/configuration).