# Megh > A TypeScript-first web framework built on Fastify. Decorator routing, dependency injection, validation, OpenAPI, MeghORM, queues, mail and a CLI, for building REST APIs in TypeScript. Source: https://meghjs.github.io --- # Introduction Source: https://meghjs.github.io/getting-started/introduction Megh is a TypeScript-first web framework for building REST APIs on Node.js. It runs on [Fastify](https://fastify.dev) and gives you decorators, dependency injection, validation, an ORM and OpenAPI docs, with less boilerplate than most structured frameworks. ```ts [controllers/user.controller.ts] import { Controller, Get, Post, Param, Body } from '@meghjs/core'; import { UserService } from '../services/user.service'; import { CreateUserDto } from '../dtos/create-user.dto'; @Controller('/users') export class UserController { constructor(private readonly users: UserService) {} @Get('/:id') findOne(@Param('id') id: number) { return this.users.find(id); } @Post('/') create(@Body() dto: CreateUserDto) { return this.users.create(dto); // dto is already validated } } ``` ```ts [app.ts] import { Megh } from '@meghjs/core'; import { UserController } from './controllers/user.controller'; const app = Megh.createApplication(); app.useControllers([UserController]); app.run(); ``` The controller gets its service through the constructor, the body is validated against `CreateUserDto` before the handler runs, and with `app.useOpenApi()` both routes appear in the generated OpenAPI document. ## Who it's for - **TypeScript developers who want structure without ceremony.** Controllers, services and DTOs, but no module files or provider arrays to keep in sync. - **Developers coming from Laravel, Rails or Django** who miss models, migrations, seeders and generators in Node. - **Teams building business APIs**, where the CLI can scaffold a working domain with auth and roles in minutes. ## What's included **HTTP** - Decorator-based [controllers](/core-concept/controller) and inline routes - [Middleware](/core-concept/middleware) with one fixed pipeline order - [Validation](/core-concept/validation) with class-validator-compatible decorators, compiled once per DTO - [Authentication](/core-concept/authentication) and deny-by-default authorization - [Error handling](/core-concept/error-handling) with exception filters - [OpenAPI](/microservices/openapi) documents with Swagger UI or Scalar **Application** - [Dependency injection](/core-concept/dependency-injection) with Megh's own container - [Configuration](/core-concept/configuration) from `.env` and typed config classes - [Lifecycle hooks](/getting-started/application#lifecycle-hooks) and graceful shutdown - [Health checks](/advanced/health), request IDs and [structured logging](/advanced/logging) **Data and background work** - [MeghORM](/advanced/orm): typed models, a query builder, migrations, seeders and factories - Optional [TypeORM and Knex](/advanced/database) integrations through `@meghjs/data` - [Events](/advanced/events), [messaging](/advanced/messaging) over Redis or RabbitMQ, [queues](/advanced/queue), [scheduled tasks](/advanced/scheduler) and [caching](/advanced/caching) - [File uploads](/advanced/file-uploads) with safe defaults - [WebSockets](/microservices/websocket) with Socket.IO **Tooling** - The [`megh` CLI](/cli/basic): new projects, generators, migrations and [scaffolding](/cli/scaffold/) - [Testing helpers](/advanced/testing), `Messaging.fake()` and in-memory queues ## How it's built - **On Fastify.** Megh adds structure on top of Fastify rather than replacing it. Any Fastify plugin works through `app.registerFastifyPlugin()`. - **Install only what you use.** Integrations such as CORS, OpenAPI, uploads, Redis and Socket.IO are optional peer dependencies. If one is missing, the `use*` call tells you what to install. - **Safe defaults.** `@Authorized` routes are denied unless an authorization handler allows them, fields a DTO doesn't declare are rejected with a 400, 5xx details are hidden in production, and uploads get random names inside a fixed folder. - **CommonJS.** `@meghjs/core` ships one CommonJS build, which ESM projects can still import. See [Installation](/getting-started/installation). ## How it compares - **Express and Fastify** give you routing and leave structure to you. Megh adds controllers, DI, validation, an ORM and OpenAPI, on Fastify. - **NestJS** is the closest in style: decorators, DI and controllers. Megh has no module system, so there's less wiring, and it ships its own ORM and scaffolding. NestJS has a much larger ecosystem and community. - **AdonisJS** shares the batteries-included idea. Megh is decorator-first and runs on Fastify. ## Project status Megh is in `0.x` and heading to 1.0. Minor releases can still contain breaking changes, each with an upgrade guide. See the [versioning policy](/reference/versioning) and [upcoming changes](/getting-started/upgrading-next). > **On 0.7.x?** See [Upgrading to 0.8](/getting-started/upgrading-0.8). > **On 0.5.x?** See [Upgrading to 0.6](/getting-started/upgrading-0.6). > **Coming from Avleon?** Avleon is now Megh. See > [Moving from Avleon to Megh](/getting-started/upgrading-megh). On 0.3 or > earlier, read [Upgrading to 0.4](/getting-started/upgrading-0.4) first. ## Next steps 1. [Install Megh](/getting-started/installation) and create a project. 2. Follow the [Quick Start](/getting-started/usage) to write your first routes. 3. Read [Application](/getting-started/application) to see how an app is put together. --- # Installation Source: https://meghjs.github.io/getting-started/installation Megh requires **Node.js 22 or newer**. ## Using the CLI If you already installed @meghjs/cli globally then run the following command: ```sh megh new myapi ``` else you can install using npx: ::: code-group ```sh [npm] npx @meghjs/cli new myapi ``` ```sh [pnpm] pnpm dlx @meghjs/cli new myapi ``` ```sh [yarn] yarn dlx @meghjs/cli new myapi ``` ::: The CLI asks which package manager to use and which features to include — OpenAPI docs, CORS and MeghORM — then scaffolds the project and installs its dependencies. ```sh cd myapi npm run start:dev ``` The app starts on `http://localhost:4000`, and with OpenAPI enabled the docs are served at `/docs`. ### What you get ``` myapi/ ├── src/ │ ├── controllers/ # Route controllers │ ├── services/ # Business logic │ ├── config/ # App configuration │ ├── app.ts # App setup │ └── serve.ts # Entry point ├── test/ ├── tsconfig.json └── package.json ``` `megh serve` compiles into `.megh/build/` and `megh build` into `dist/`. Both are generated and ignored by git. | Script | Description | |--------|-------------| | `start:dev` | Start the dev server with hot reload | | `build` | Compile TypeScript to JavaScript | | `start` | Start the production server | | `test` | Run unit tests | ## Manual setup Go to your desired project directory and run the following commands: ::: code-group ```sh [Bash] mkdir myapi && cd myapi && mkdir src ``` ```powershell [Powershell] New-Item -ItemType Directory -Name myapi Set-Location myapi New-Item -ItemType Directory -Name src ``` ::: ::: code-group ```sh [npm] npm init -y npm i @meghjs/core reflect-metadata npm i --save-dev typescript @types/node npx tsc --init ``` ```sh [pnpm] pnpm init pnpm i @meghjs/core reflect-metadata pnpm i --save-dev typescript @types/node pnpm tsc --init ``` ```sh [yarn] yarn init -y yarn add @meghjs/core reflect-metadata yarn add --dev typescript @types/node yarn tsc --init ``` ::: [Validation decorators](/core-concept/validation) come from `@meghjs/core`, so `class-validator` and `class-transformer` are not needed. They are optional peers: install them only to keep DTOs written with their decorators. Ensure `experimentalDecorators` and `emitDecoratorMetadata` are enabled in tsconfig.json — Megh's decorators do not work without them. ```json{3-4} { "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } } ``` Then add a minimal entry point: ```ts [src/app.ts] import { Megh } from '@meghjs/core'; const app = Megh.createApplication(); app.mapGet('/', () => 'Welcome to Megh.'); app.run(); ``` You can still use the CLI's generators and dev server in a manually created project by installing it locally: ```sh npm i -D @meghjs/cli npx megh serve ``` ## Optional dependencies Install these only for the features you use. Without them the package still imports, and you get a clear install hint the moment a feature needs one: | Feature | Package | |---------|---------| | CORS (`useCors`) | `@fastify/cors` | | File uploads (`useMultipart`, `@UploadFile`) | `@fastify/multipart` | | Static files (`useStaticFiles`) | `@fastify/static` | | OpenAPI with Swagger UI | `@fastify/swagger`, `@fastify/swagger-ui` | | OpenAPI with Scalar | `@fastify/swagger`, `@scalar/fastify-api-reference` | | `@IsUUID`, `@IsUrl`, `@IsEmail(options)` | `validator` | | Models and migrations (`useMeghORM`) | a driver: `pg`, `mysql2`, `better-sqlite3`, or `tedious` + `tarn` | | TypeORM (alternative to MeghORM) | `@meghjs/data`, `typeorm` + a driver (`pg`, `mysql2`, `sqlite3`, `better-sqlite3`, `mssql`) | | Knex (alternative to MeghORM) | `@meghjs/data`, `knex` + a driver | | Websockets | `socket.io`, `fastify-socket.io` | | `@react` islands in [views](/advanced/views#react) | `@swc/core` | | Image transforms | `sharp` | | Pretty dev logs | `pino-pretty` (dev dependency) | Queues, [messaging](/advanced/messaging), the Redis cache and the Redis rate limit store need nothing extra: BullMQ, the Redis client (`@redis/client`) and the RabbitMQ client (`amqplib`) are dependencies of `@meghjs/core`. ## Trying the next release `npm install` gives you the latest release. Before a new release is final, prereleases of it (versions like `0.8.0-next.0`) are published under the `next` tag: ```sh npx @meghjs/cli@next new myapi # a new project on the next release npm install @meghjs/core@next @meghjs/cli@next # move a project to it ``` The [docs for the next release](https://meghjs.github.io/next/) cover the new APIs, and its upgrade guide lists the breaking changes. A version range such as `^0.8.0` never installs a prerelease, so `npm update` keeps you on the latest release until you choose `@next`. ## Module format `@meghjs/core` ships a single CommonJS build. ESM projects can still `import { ... } from '@meghjs/core'`. Only the package root is exported: deep imports such as `@meghjs/core/dist/...` are not supported. --- # Quick Start Source: https://meghjs.github.io/getting-started/usage There are two ways to design your application: `Controller based` and `Route method based`. They can be mixed in the same app. ## Using a controller Controllers group related routes and can take dependencies through the constructor. This is the approach the CLI scaffolds. ::: code-group ```ts [app.ts] import { Megh } from '@meghjs/core'; import { WelcomeController } from './controllers/welcome.controller'; const app = Megh.createApplication(); app.useControllers([ WelcomeController ]); app.run(); ``` ```ts [controllers/welcome.controller.ts] import { Controller, Get } from '@meghjs/core'; @Controller export class WelcomeController { @Get() sayHello(){ return 'Hello world!.'; } } ``` ::: See [Controller](/core-concept/controller) for parameters, REST resources and error handling. ## Using inline routes For small apps, register handlers directly on the app with `mapGet`, `mapPost`, `mapPut`, `mapPatch` and `mapDelete`: ::: code-group ```ts [app.ts] import { Megh } from '@meghjs/core'; const app = Megh.createApplication(); app.mapGet('/', () => 'Welcome to Megh.'); app.run(); // PORT from the environment, else :4000 ``` ::: Handlers receive the request and response, and returning an object sends JSON: ```ts app.mapGet('/users/:id', (req) => ({ id: req.params.id })); app.mapPost('/users', (req) => { return { created: req.body }; }); ``` Inline routes return a chainable object for middleware, authorization and OpenAPI metadata: ```ts app.mapGet('/secret', handler) .useMiddleware([ApiKeyMiddleware]) // classes (resolved through DI) or instances .authorized() // like @Authorized(); .authorized('jwt') picks a handler .useOpenApi({ tags: ['internal'] }); ``` They run the same pipeline as controller routes: middleware, then the authentication handler (`request.user`), then `.authorized()`. Return `Results.*` to set the status code; thrown errors go through the [error handler](/core-concept/error-handling). ## Returning responses Returning an object or array sends JSON; returning a string sends it as-is. Set the status code with `@HttpCode`, or return a result that carries one: ```ts import { Post, Get, HttpCode, Results, HttpResponse } from '@meghjs/core'; @Post('/') @HttpCode(201) create(@Body() dto: CreateUserDto) { return this.users.create(dto); // 201 with the user as JSON } @Get('/:id') async findOne(@Param('id') id: number) { const user = await this.users.find(id); return user ? Results.Ok(user) // 200 { data: user } : Results.NotFound('nope'); // 404 { code, status, message } } ``` | Result | Status | Body | |--------|--------|------| | `Results.Ok(x)` | 200 | `{ data: x }` | | `Results.Created(x, location?)` | 201 | `{ data: x }`, and `Location` when given | | `Results.Accepted(x?)` | 202 | `{ data: x }`, or empty | | `Results.NoContent()` | 204 | empty | | `Results.Json(x, status?)` | 200 or `status` | `x` as it is, no `{ data }` wrapper | | `Results.Text(text, status?)` | 200 or `status` | `text/plain` | | `Results.Html(html, status?)` | 200 or `status` | `text/html` (for templates, use [`Results.View`](/advanced/views)) | | `Results.Status(code)` | `code` | empty | | `Results.File(source, options?)` | 200 | a path, Buffer or stream, shown in the browser | | `Results.Download(source, filename?)` | 200 | a path, Buffer or stream, downloaded | | `Results.OkStream(stream, { contentType, filename })` | 200 | the stream | | `Results.Redirect(url, status?)` | 302 (or 301, 303, 307, 308) | empty, `Location: url` | | `HttpResponse.Created(x)` | 201 | `{ message, data }` | | `HttpResponse.NoContent()` | 204 | empty | A returned result's status wins over `@HttpCode`. ### Returning errors Throwing an exception (`throw new NotFoundException()`) and returning an error result send the same body: `{ code, status: "Error", message }`, plus `errors` or `data` when given. Return one when the error is an expected outcome, not an exception: ```ts @Post('/') async register(@Body() dto: RegisterDto) { if (await this.users.exists(dto.email)) { return Results.Conflict('That email is already registered.'); } return Results.Created(await this.users.create(dto)); } ``` | Result | Status | |--------|--------| | `Results.BadRequest(message?, errors?)` | 400 | | `Results.Unauthorized(message?)` | 401 | | `Results.Forbidden(message?)` | 403 | | `Results.NotFound(message?)` | 404 | | `Results.Conflict(message?)` | 409 | | `Results.UnprocessableEntity(message?, errors?)` | 422 | | `Results.TooManyRequests(message?, retryAfter?)` | 429, and `Retry-After` in seconds when given | | `Results.Error(status, message, data?)` | any 4xx or 5xx | Each one has a default message, such as `Not Found`. ### Files `Results.File` shows a file in the browser and `Results.Download` downloads it. Both take a path, a Buffer or a stream. The content type comes from the file name, and a path that doesn't exist answers 404: ```ts @Get('/invoices/:id.pdf') async invoice(@Param('id') id: string) { return Results.File(`storage/invoices/${await this.invoices.fileOf(id)}`); } @Get('/export') async export() { return Results.Download(await this.reports.csv(), 'export.csv'); } @Get('/avatars/:key') async avatar(@Param('key') key: string) { const disk = Storage.disk('s3'); return Results.File(await disk.getStream(key), { filename: key }); } ``` A path is read as it is, so never build one from request input without checking it. For files on a [storage disk](/advanced/storage), pass the disk's stream as above. ### Headers on a result Every result takes `.header(name, value)` and `.withHeaders({ ... })`: ```ts return Results.Ok(report) .header('Cache-Control', 'no-store') .withHeaders({ 'X-Report-Id': report.id }); ``` ### Redirects and headers `@Redirect(url, status?)` redirects instead of sending the return value. The handler can pick another target by returning `{ url, statusCode }`: ```ts import { Get, Redirect, ResponseHeader, Results } from '@meghjs/core'; @Get('/docs') @Redirect('https://docs.example.com', 301) docs() {} @Get('/latest') @Redirect('/releases') latest() { return { url: `/releases/${this.releases.latestId()}` }; // 302 there } @Get('/me') me(@AuthUser() user?: User) { return user ?? Results.Redirect('/login'); } ``` `@ResponseHeader(name, value)` sets a header on every response from the route. Stack it for several; a header a returned `Results.*` sets wins: ```ts @Get('/report') @ResponseHeader('Cache-Control', 'no-store') report() { ... } ``` `@Header()` is the parameter decorator that reads a *request* header. To send an error status, throw an HTTP exception: ```ts import { HttpExceptions } from '@meghjs/core'; throw HttpExceptions.notFound('User not found'); ``` Error responses have the shape `{ code, status: "Error", message, data? }`. Outside development, 5xx responses hide the message and data. See [Error Handling](/core-concept/error-handling). Inline routes don't validate DTOs; use a controller when you need that. ## Running the app `run` takes an optional port. Without one it uses the `PORT` environment variable, else `4000`: ```ts app.run(); // PORT, else :4000 app.run(3000); // :3000 app.run(3000, { host: '127.0.0.1' }); ``` Set `NODE_ENV=development` locally to get detailed errors and pretty logs. An unset `NODE_ENV` counts as production. See [Application](/getting-started/application) for the app options, the `use*` methods, what `run()` does, lifecycle hooks and shutdown. ## Next steps - [Application](/getting-started/application) — options, lifecycle and shutdown - [Controller](/core-concept/controller) — routes, parameters, REST resources - [Middleware](/core-concept/middleware) — request pipeline - [MeghORM](/advanced/orm) — models, queries, relations and migrations - [OpenAPI](/microservices/openapi) — API documentation --- # Application Source: https://meghjs.github.io/getting-started/application Every Megh app is one `MeghApplication`. You create it, turn features on with `use*` methods, and start it with `run()`. ```ts [app.ts] import { Megh } from '@meghjs/core'; import { UserController } from './controllers/user.controller'; const app = Megh.createApplication(); app .useCors({ origin: true }) .useHealth() .useControllers([UserController]); app.run(3000); ``` ## Creating the app `Megh.createApplication(options?)` returns the application. It's a singleton: calling it again returns the same app, and the options of the later calls are ignored. Pass every option in the first call. | Option | Default | | |--------|---------|---| | `server` | | Fastify server options (`logger`, `bodyLimit`, `trustProxy`, `https`, …), passed to `Fastify()` | | `requestId` | `{}` (on) | Request ID settings. `false` turns request IDs off. See [Logging](/advanced/logging) | | `plugins` | `[]` | [Plugins](/advanced/plugins) to register explicitly | | `autoloadPlugins` | `true` | Find plugins among the app's dependencies | | `experimental.compiledValidation` | `MEGH_COMPILED_VALIDATION` env, else `false` | Compile DTO validation once per class. See [Validation](/core-concept/validation) | ```ts const app = Megh.createApplication({ server: { bodyLimit: 2 * 1024 * 1024, // 2 MB trustProxy: 1, // one load balancer in front; never `true` }, }); ``` ### Fastify plugins Megh runs on Fastify but does not expose the Fastify instance. For anything Megh doesn't wrap, register a Fastify plugin with `registerFastifyPlugin()`: ```ts import etag from '@fastify/etag'; app.registerFastifyPlugin(etag); app.registerFastifyPlugin(etag, { weak: true }); // with options ``` Call it before `run()` or inside an `onInit()` hook. Megh loads the plugins before it adds routes, so plugins that hook into routes, such as `@fastify/compress`, see every controller and inline route. ## Turning features on Each `use*` method returns the app, so they chain. Call them before `run()`. | Method | What it does | Guide | |--------|--------------|-------| | `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) | | `useMiddlewares([...])` | Global middleware for every route | [Middleware](/core-concept/middleware) | | `useAuthentication(Handler)` | Sets `request.user` on every request | [Authentication](/core-concept/authentication) | | `useAuthorization(Handler)` | Decides access for `@Authorized` routes | [Authentication](/core-concept/authentication) | | `useExceptionFilters(...)`, `useErrorHandler(fn)`, `useErrorLogger(...)` | Customise error responses and logging | [Error Handling](/core-concept/error-handling) | | `useOpenApi(options)` | OpenAPI document and Swagger UI or Scalar | [OpenAPI](/microservices/openapi) | | `useCors(options)` | CORS, through `@fastify/cors` | [Security](/production/security#restrict-cors) | | `useSecurityHeaders(options?)` | CSP, HSTS, `nosniff` and other security headers | [Security](/production/security#add-security-headers) | | `useRateLimit(options?)` | Requests per client per window, 429 over the limit | [Security](/production/security#add-rate-limits) | | `useMultipart(options)` | File uploads, through `@fastify/multipart` | [File Uploads](/advanced/file-uploads) | | `useStaticFiles(options)` | Serve files, through `@fastify/static` | [File Uploads](/advanced/file-uploads) | | `useCompression(options?)` | gzip / brotli responses, through `@fastify/compress` | [Compression](#compression) | | `setGlobalPrefix(prefix, { exclude? })` | Serve every route under a prefix such as `/api` | [Controllers](/core-concept/controller#global-prefix-and-versioning) | | `useVersioning(options)` | Version routes with `@Version()`, by URI or header | [Controllers](/core-concept/controller#global-prefix-and-versioning) | | `useEnvSchema(EnvDto)` | Validate environment variables at boot | [Configuration](/core-concept/configuration#validating-at-boot) | | `useCache(options)` | Memory or Redis cache | [Caching](/advanced/caching) | | `useMeghORM(options)` | Database connection for MeghORM | [MeghORM](/advanced/orm) | | `useScheduler([...])` or `useScheduler({ path })` | Scheduled tasks | [Scheduler](/advanced/scheduler) | | `useWorker([...])` | Queue workers | [Queue](/advanced/queue) | | `useMail(options?)` | Send mail over SMTP or a provider's API, now or queued | [Mail](/advanced/mail) | | `useSocketIo(options)` | Socket.IO server | [WebSocket](/microservices/websocket) | | `useHealth(options)`, `addHealthCheck(name, fn)` | `/health` and `/ready` endpoints | [Health Checks](/advanced/health) | Integrations are optional peer dependencies. If one isn't installed, the `use*` call throws with the `npm install` command you need. ### `useGlobal` `useGlobal` sets several features in one call. Each key calls the matching `use*` method: ```ts import path from 'path'; app.useGlobal({ cors: { origin: ['https://example.com'] }, openApi: { info: { title: 'My API', version: '1.0.0' } }, controllers: [UserController], middlewares: [RequestTimer], authorization: AppAuthorization, multipart: { limits: { fileSize: 5 * 1024 * 1024 } }, staticFiles: { root: path.join(process.cwd(), 'public') }, // must be absolute }); ``` | Key | Calls | |-----|-------| | `cors` | `useCors` | | `openApi` | `useOpenApi` | | `controllers` | `useControllers` | | `middlewares` | `useMiddlewares` | | `authorization` | `useAuthorization` | | `multipart` | `useMultipart` | | `staticFiles` | `useStaticFiles` | | `scheduler` | `useScheduler` | | `compression` | `useCompression` (`true` or options) | ### Compression `useCompression()` compresses responses for clients that send `Accept-Encoding`, with `@fastify/compress` (`npm install @fastify/compress`). Bodies under 1024 bytes are sent as they are. Options go to the plugin: ```ts app.useCompression(); app.useCompression({ encodings: ['br', 'gzip'], threshold: 2048 }); ``` If a proxy or CDN in front of the app already compresses, leave it off. ## Running the app `run(port?, options?)` starts the app. The port defaults to the `PORT` environment variable, else `4000`: ```ts app.run(); // PORT, else :4000 app.run(3000); // :3000, whatever PORT says app.run(3000, { host: '127.0.0.1', shutdownTimeout: 20_000 }); ``` | Option | Default | | |--------|---------|---| | `host` | `HOST` or `0.0.0.0` | Interface to listen on | | `onListen` | | Called once the server is listening | | `shutdownTimeout` | `10000` | Milliseconds to wait for a clean shutdown before exiting with code 1 | The host defaults to `0.0.0.0` so the app is reachable inside a container. Pass `127.0.0.1` to accept local connections only. `run()` can be called once; a second call throws `App already running`. ### What `run()` does In order: 1. Validates the environment (`useEnvSchema`) and every `@AppConfig({ schema })` class. 1. Prepares the OpenAPI document, if `useOpenApi` was called. 2. Runs the `onInit` hooks. MeghORM connects to the database here. 3. Finds controllers (with `{ auto: true }`), then maps controller and inline routes. 4. Finds and starts scheduled tasks. 5. Installs the error handler and waits for Fastify to be ready. 6. Starts Socket.IO, if `useSocketIo` was called. 7. Listens for `SIGTERM` and `SIGINT`. 8. Starts listening on the port and logs `Application running on
`. 9. Runs the `onReady` hooks, then `onListen`. A thrown error in steps 1 to 6 stops startup, and the server never listens. ## Lifecycle hooks Register work to run at each stage of the app's life. Call these before `run()`; each returns the app, so they chain: ```ts app .onInit(async () => { // After the database connects, before routes are mapped and the server // listens. A thrown error aborts startup. await cache.warmUp(); }) .onReady(() => { // The server is listening. }) .onClose(async () => { // On shutdown, after the server stops accepting requests. await metrics.flush(); }); ``` Hooks of the same kind run in the order you register them, except `onClose` hooks, which run in reverse so that things set up last are torn down first. A failing `onClose` hook is logged and the others still run. ## Shutting down `await app.close()` shuts the app down, for example at the end of a test. In order, it: 1. Stops the HTTP server, waiting for in-flight requests. 2. Stops scheduled tasks. 3. Closes queue workers. 4. Closes the cache, if `useCache` was called. 5. Runs the `onClose` hooks (MeghORM closes its connection in one). Calling `close()` twice is safe: the second call waits for the first. On `SIGTERM` or `SIGINT`, `run()` calls `close()` and exits with code 0. If shutdown fails, or takes longer than `shutdownTimeout`, it exits with code 1. See [Deployment](/production/deployment) for running behind a process manager or in a container. ## Development and production `app.isDevelopment()` is true only when `NODE_ENV=development`. An unset `NODE_ENV` counts as production. In production mode, 5xx details are hidden and logs are written as JSON. Set `NODE_ENV=development` locally to get detailed errors, pretty logs and any docs you gate behind `isDevelopment()`: ```ts if (app.isDevelopment()) { app.useOpenApi({ info: { title: 'My API', version: '1.0.0' } }); } ``` Megh loads `.env` into `process.env` when it is first imported. Set `MEGH_DOTENV=false` to skip that and manage the environment yourself. See [Configuration](/core-concept/configuration). --- # Controllers Source: https://meghjs.github.io/core-concept/controller A controller groups related routes. Mark the class with `@Controller` and its methods with a route decorator — `@Get`, `@Post`, `@Put`, `@Patch`, `@Delete`. ## Basic controller ```sh npx megh make:controller welcome ``` ```ts [src/controllers/welcome.controller.ts] import { Controller, Get } from '@meghjs/core'; @Controller('/welcome') export class WelcomeController { @Get() sayHello() { return 'Hello'; } } ``` Register it on the app: ```ts [app.ts] import { Megh } from '@meghjs/core'; import { WelcomeController } from './controllers/welcome.controller'; const app = Megh.createApplication(); app.useControllers([WelcomeController]); export default app; ``` `@Controller` may be used bare, in which case routes mount at the root: ```ts @Controller export class WelcomeController {} ``` ## Route parameters | Decorator | Reads from | |-----------|------------| | `@Param('id')` | Route path segment | | `@Query()` | Query string | | `@Body()` | Request body | | `@Header('x-token')` | Request header | | `@AuthUser()` | The authenticated user | ```ts @Get('/:id') findOne(@Param('id') id: number) { return { id }; } ``` ## REST controller with a built-in collection `Collection` holds items in memory — useful for prototypes and tests, with no database required. ```sh npx megh make:controller users --model user --rest ``` or shorthand ```sh npx megh m:c users -m user -r ``` ::: code-group ```ts [users.controller.ts] import { Controller, Get, Post, Put, Delete, Param, Body, Collection, HttpExceptions, } from '@meghjs/core'; import { User } from '../models/user'; @Controller('/users') export class UsersController { private readonly users = Collection.from([ { id: 1, name: 'test 1', age: 20, active: true }, { id: 2, name: 'test 2', age: 45, active: true }, { id: 3, name: 'test 3', age: 38, active: false }, ]); @Get() findAll() { return this.users.find(); } @Get('/:id') findOne(@Param('id') id: number) { const user = this.users.findOne((u) => u.id === id); if (!user) throw HttpExceptions.notFound('User not found'); return user; } @Post() create(@Body() createBody: Partial) { const lastId = this.users.max('id'); return this.users.add({ ...createBody, id: lastId + 1 }); } @Put('/:id') update(@Param('id') id: number, @Body() updateBody: Partial) { const user = this.users.findOne((u) => u.id === id); if (!user) throw HttpExceptions.notFound('User not found'); this.users.update((u) => u.id === id, updateBody); return 'Updated Successfully'; } @Delete('/:id') delete(@Param('id') id: number) { const user = this.users.findOne((u) => u.id === id); if (!user) throw HttpExceptions.notFound('User not found'); this.users.delete((u) => u.id === id); return 'Deleted Successfully'; } } ``` ```ts [models/user.ts] export class User { id: number; name: string; age: number; active: boolean; } ``` ::: `Collection` also offers `paginate({ page, perPage })`, `max`, `min`, `sum`, `avg`, `updateBy`, `deleteBy` and async variants (`findAsync`, `findOneAsync`). `paginate` returns the same `{ data, meta }` shape as the database paginators; see [Pagination](/advanced/orm/queries#pagination). ## REST controller with a MeghORM model With `--model` the generated controller delegates to a service that queries a [MeghORM](/advanced/orm) model, which keeps data access out of the controller. The model, its DTOs and the service are generated too if they don't exist yet; the model's columns are read from the migration that creates its table. ```sh npx megh make:controller users --model user --rest ``` or shorthand ```sh npx megh m:c users -m user -r ``` ::: code-group ```ts [users.controller.ts] import { Controller, ApiResponse, Body, Delete, Get, Paginated, Param, Post, Put, Query, } from '@meghjs/core'; import { User } from '../models/user.model'; import { CreateUserDto, ListUsersQuery, UpdateUserDto } from '../dtos/user.dto'; import { UserService } from '../services/user.service'; @Controller('/users') export class UsersController { constructor(private readonly userService: UserService) {} @Get() @ApiResponse(200, Paginated(User)) index(@Query() query: ListUsersQuery) { return this.userService.paginate(query); } @Get('/:id') @ApiResponse(200, User) @ApiResponse(404) show(@Param('id') id: number) { return this.userService.findOrFail(id); } @Post() @ApiResponse(200, User) create(@Body() body: CreateUserDto) { return this.userService.create(body); } @Put('/:id') @ApiResponse(200, User) @ApiResponse(404) update(@Param('id') id: number, @Body() body: UpdateUserDto) { return this.userService.update(id, body); } @Delete('/:id') @ApiResponse(200, { type: 'object', properties: { message: { type: 'string' } } }) @ApiResponse(404) async delete(@Param('id') id: number) { await this.userService.delete(id); return { message: 'User deleted.' }; } } ``` ```ts [services/user.service.ts] import { AppService, type CreateInput, type PageRequest, type UpdateInput } from '@meghjs/core'; import { User } from '../models/user.model'; @AppService export class UserService { findAll() { return User.query().orderBy('id').get(); } /** One page of users: `{ data, meta }`. */ paginate(request: PageRequest = {}) { return User.query().orderBy('id').paginate(request); } /** The user with this id; throws a 404 when there is none. */ findOrFail(id: number) { return User.findOrFail(id); } create(input: CreateInput) { return User.create(input); } /** `save()` writes only the columns that changed. */ async update(id: number, changes: UpdateInput) { const user = await User.findOrFail(id); // A DTO instance holds `undefined` for every field that was not sent. const sent = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== undefined)); return user.fill(sent).save(); } async delete(id: number) { const user = await User.findOrFail(id); await user.delete(); } } ``` ```ts [models/user.model.ts] import { Model, Table, PrimaryKey, AutoIncrement, Column, CreatedAt, UpdatedAt } from '@meghjs/core'; @Table('users') export class User extends Model { @PrimaryKey() @AutoIncrement() id?: number; @Column() name!: string; @Column({ unique: true }) email!: string; @CreatedAt() created_at?: Date; @UpdatedAt() updated_at?: Date; } ``` ::: `findOrFail` throws a 404 on its own, so the controller needs no `HttpExceptions.notFound` check. See [MeghORM](/advanced/orm) for connecting the database, and [Queries](/advanced/orm/queries) for what models can do. ## Global prefix and versioning `setGlobalPrefix` serves every controller and inline route under a prefix. Health routes and the API docs page keep their own paths; `exclude` leaves more routes alone (paths as declared, or RegExps): ```ts app.setGlobalPrefix('/api', { exclude: ['/status'] }); // @Controller('/users') @Get('/') → GET /api/users ``` `useVersioning` serves controllers under API versions. Mark a controller or a route with `@Version()` (or `@Controller({ path, version })`); a route's version overrides its controller's: ```ts import { Controller, Get, Version } from '@meghjs/core'; @Version('2') @Controller('/users') export class UsersV2Controller { @Get('/') list() { ... } @Get('/export') @Version(['1', '2']) // served for both versions export() { ... } } ``` | Option | Requests look like | |--------|--------------------| | `{ type: 'uri' }` | `GET /api/v2/users`. `prefix` changes the `v` | | `{ type: 'header' }` | `GET /api/users` with `X-API-Version: 2`. `header` changes the header name | `defaultVersion` is the version of controllers without `@Version()`. With header versioning it is also used when a request sends no version header. Without a default, unversioned controllers keep their plain path. ```ts app.useVersioning({ type: 'uri', defaultVersion: '1' }); ``` Inline routes (`app.mapGet`, ...) get the global prefix but are not versioned. ## Throwing errors `HttpExceptions` covers the common status codes — `notFound`, `badRequest`, `unauthorized`, `forbidden`, `internalError` — and each takes an optional message: ```ts throw HttpExceptions.notFound('User not found'); ``` --- # Middleware Source: https://meghjs.github.io/core-concept/middleware Middleware runs before your route handler and can inspect or modify the request, or reject it outright. ```sh npx megh make:middleware logger ``` The command generates: ```ts [src/middlewares/logger.middleware.ts] import { AppMiddleware, MeghMiddleware, IRequest, IResponse } from '@meghjs/core'; @AppMiddleware export class LoggerMiddleware extends MeghMiddleware { /** * Return the request to continue, or throw to stop the pipeline. */ async invoke(req: IRequest, res?: IResponse) { console.log('url:', req.url); return req; } } ``` A middleware extends `MeghMiddleware` and implements `invoke`. Returning the request continues the pipeline; throwing an `HttpExceptions` error stops it: ```ts import { AppMiddleware, MeghMiddleware, IRequest, HttpExceptions } from '@meghjs/core'; @AppMiddleware export class ApiKeyMiddleware extends MeghMiddleware { async invoke(req: IRequest) { if (req.headers['x-api-key'] !== process.env.API_KEY) { throw HttpExceptions.unauthorized('Invalid API key'); } return req; } } ``` ## Applying middleware Middleware can be applied at three levels. ### Global Runs for every request. Note the plural — `useMiddlewares`: ```ts [app.ts] import { Megh } from '@meghjs/core'; import { LoggerMiddleware } from './middlewares/logger.middleware'; const app = Megh.createApplication(); app.useMiddlewares([LoggerMiddleware]); export default app; ``` ### Controller scoped Runs for every route on that controller: ```ts import { Controller, Get, UseMiddleware } from '@meghjs/core'; import { LoggerMiddleware } from '../middlewares/logger.middleware'; @UseMiddleware(LoggerMiddleware) @Controller('/home') export class HomeController { @Get() sayHello() { return 'Hello'; } } ``` ### Route scoped Runs for a single route: ```ts import { Controller, Get, UseMiddleware } from '@meghjs/core'; import { LoggerMiddleware } from '../middlewares/logger.middleware'; @Controller('/home') export class HomeController { @UseMiddleware(LoggerMiddleware) @Get() sayHello() { return 'Hello'; } } ``` A class is resolved through the DI container when the route is registered, so it can use constructor injection. You can also pass an instance, for example to give it settings. `UseMiddleware` also accepts an array, and both forms can be mixed: ```ts @UseMiddleware([LoggerMiddleware, new RateLimitMiddleware(100)]) ``` ::: tip Passing a class to `@UseMiddleware` crashed `app.run()` before 0.5.2. ::: ::: info `@UseMiddleware` must sit above `@Controller` on a class, and above the route decorator on a method — decorators apply bottom-up. ::: ## Pipeline order Each request passes through these stages: 1. Global middlewares (`useMiddlewares`) 2. Class `@UseMiddleware`, then method `@UseMiddleware` 3. Authentication (sets `request.user`) 4. Class `@Authorized`, then method `@Authorized` 5. Parameter and DTO validation 6. The route handler Middleware runs before authentication, so it can reject a request early (an API key check, an IP allowlist) but cannot read `request.user`. Put checks that need the user in an authorization handler. Inline routes follow the same order. ::: warning Changed in 0.5.5 `@UseMiddleware` used to run after `@Authorized`. See [Upgrading to 0.5.5](/getting-started/upgrading-0.5#breaking-in-0-5-5). ::: See [Authentication](/core-concept/authentication) for steps 3 and 4. --- # Validation Source: https://meghjs.github.io/core-concept/validation Megh validates request input with DTOs: classes whose properties carry validation decorators. Use a DTO as the type of a `@Body()` or `@Query()` parameter, and validation runs before your handler. The decorators come from `@meghjs/core`. They have the same names, options and error messages as [class-validator](https://github.com/typestack/class-validator) and [class-transformer](https://github.com/typestack/class-transformer), and Megh compiles each DTO's rules once into a single function, so validation is much faster. You don't need to install class-validator or class-transformer. DTOs written with them keep working if they are installed; see [Switching from class-validator](#switching-from-class-validator). ## Defining a DTO ```ts [dtos/create-user.dto.ts] import { IsString, IsInt, IsEmail, IsOptional, Min, Max } from '@meghjs/core'; export class CreateUserDto { @IsString() name: string; @IsEmail() email: string; @IsInt() @Min(18) @Max(120) age: number; @IsOptional() @IsString() bio?: string; } ``` ## Validating the body Type the `@Body()` parameter with the DTO — that is all that is needed: ```ts [controllers/users.controller.ts] import { Controller, Post, Body } from '@meghjs/core'; import { CreateUserDto } from '../dtos/create-user.dto'; @Controller('/users') export class UsersController { @Post() create(@Body() body: CreateUserDto) { // body is a validated CreateUserDto instance return body; } } ``` The handler receives the **DTO instance**, not the raw body: getters and methods on the class work, and [`@Type` and `@Transform`](#converting-values) have been applied. ### Unknown properties are rejected A property that is not declared on the DTO fails with 400, which prevents mass assignment. Arrays and primitives sent to an object DTO are rejected too. To accept a property without checking it, mark it with `@Allow()`. ### Error response When validation fails the request is rejected with **400** before the handler runs: ```json { "code": 400, "status": "Error", "message": "email must be an email", "errors": [ { "path": "email", "constraints": { "isEmail": "email must be an email" } } ] } ``` `message` joins all messages with `; `. Nested properties use dotted paths such as `address.city` and `items.0.name`. Every decorator takes a `message` option, as a string or a function. `$property`, `$value`, `$target` and `$constraint1`, `$constraint2`… are filled in: ```ts @MinLength(8, { message: '$property needs at least $constraint1 characters' }) password: string; ``` ### Without decorator metadata tsx, esbuild and SWC do not emit decorator metadata, so Megh cannot see the parameter type. Pass it explicitly: ```ts create(@Body({ type: CreateUserDto }) body: CreateUserDto) {} ``` Without metadata, a `@Body()` or `@Query()` with no `type` stops startup with an error that names the route and the compiler setting, rather than leaving the DTO unvalidated. Pass `{ validate: false }` to take the raw value. ## Validating the query string The same applies to `@Query()`. Query values arrive as strings; Megh converts them to the property's type (`?page=2` becomes the number `2`) before validating: ```ts export class ListUsersDto { @IsOptional() @IsInt() @Min(1) page?: number; } @Get() index(@Query() query: ListUsersDto) { return { page: query.page ?? 1 }; } ``` ## Decorators | Kind | Decorators | |------|------------| | Presence | `IsOptional`, `IsDefined`, `IsNotEmpty`, `IsEmpty`, `Allow`, `ValidateIf(condition)` | | Type | `IsString`, `IsNumber(options?)`, `IsInt`, `IsBoolean`, `IsDate`, `IsArray`, `IsObject`, `IsEnum(entity)` | | Values | `IsIn(values)`, `IsNotIn(values)`, `Equals(value)`, `NotEquals(value)` | | Numbers | `Min(n)`, `Max(n)`, `IsPositive`, `IsNegative`, `IsDivisibleBy(n)` | | Dates | `MinDate(date)`, `MaxDate(date)` (a `Date`, or a function returning one) | | Strings | `MinLength(n)`, `MaxLength(n)`, `Length(min, max?)`, `Matches(pattern, modifiers?)`, `IsEmail(options?)`, `IsUUID(version?)`, `IsUrl(options?)`, `IsTimeZone` | | String formats | `IsNumberString`, `IsBooleanString`, `IsDateString`, `IsISO8601`, `IsAlpha`, `IsAlphanumeric`, `IsAscii`, `IsLowercase`, `IsUppercase`, `Contains(seed)`, `NotContains(seed)`, `IsJSON`, `IsJWT`, `IsHexColor`, `IsHexadecimal`, `IsMongoId`, `IsIP(version?)`, `IsBase64`, `IsCreditCard`, `IsCurrency`, `IsDecimal`, `IsFQDN`, `IsLatLong`, `IsPostalCode(locale)`, `IsSemVer`, `IsMobilePhone(locale?)`, `IsStrongPassword(options?)`, `IsPhoneNumber(region?)` | | Objects | `IsNotEmptyObject(options?)`, `IsInstance(Class)` | | Arrays | `ArrayNotEmpty`, `ArrayMinSize(n)`, `ArrayMaxSize(n)`, `ArrayUnique(identifier?)`, `ArrayContains(values)`, `ArrayNotContains(values)` | | Nested | `ValidateNested`, with `Type(() => Class)` | | Conversion | `Type(() => Class, options?)`, `Transform(fn)`, `Expose(options?)`, `Exclude(options?)` | | Custom | `Validate(Constraint)`, `ValidatorConstraint(options?)`, `registerDecorator(options)`, `ValidateBy(options)` | They behave as their class-validator namesakes. Pass `{ each: true }` to check every item of an array instead of the array itself: ```ts @IsString({ each: true }) @MaxLength(20, { each: true }) tags: string[]; ``` `IsOptional` skips the other rules when the value is `null` or `undefined`. `ValidateIf((dto, value) => …)` skips them when the condition is false. ### Checks that need a package `@IsEmail()` with default options and `@IsUUID()` are checked by Megh itself and accept exactly the values class-validator accepts. `@IsUrl()`, `@IsEmail(options)` with options and the checks in the **String formats** row (except `IsPhoneNumber`) use the [validator](https://github.com/validatorjs/validator.js) package, as class-validator does; install it to use them: ```sh npm i validator ``` `@IsPhoneNumber()` uses [libphonenumber-js](https://github.com/catamphetamine/libphonenumber-js), as class-validator does: ```sh npm i libphonenumber-js ``` A DTO that uses one of these without the package installed fails when the app starts, with the `npm i` command to run. An address containing an unpaired UTF-16 surrogate fails `@IsEmail` with the normal 400 (class-validator throws on it, which becomes a 500). ## Nested objects Mark the property with `@ValidateNested()` and give its class with `@Type()`, so the value becomes an instance of that class and is validated with its own rules. Arrays work the same way: ```ts import { IsString, MinLength, ValidateNested, Type, IsArray } from '@meghjs/core'; class AddressDto { @IsString() @MinLength(2) city: string; } class ItemDto { @IsString() sku: string; } export class CreateOrderDto { @ValidateNested() @Type(() => AddressDto) address: AddressDto; @IsArray() @ValidateNested({ each: true }) @Type(() => ItemDto) items: ItemDto[]; } ``` Unknown properties are rejected inside nested objects too. Errors use dotted paths: `address.city`, `items.1.sku`. ## Converting values `@Type(() => X)` converts a value before it is validated: `Number`, `String`, `Boolean` and `Date` convert primitives (`Boolean('false')` is `true`, as in class-transformer), and a class turns a nested object into an instance. `@Transform` changes a value with your own function. It receives `{ value, key, obj, type, options }` and returns the new value: ```ts import { IsIn, Transform } from '@meghjs/core'; export class ListUsersDto { @Transform(({ value }) => (typeof value === 'string' ? value.toLowerCase() : value)) @IsIn(['name', 'email']) sort: string; } ``` Like class-transformer, a transform only runs for properties present in the input; defaults set on the class (`sort = 'name'`) apply when it is missing. ### Different key names `@Expose({ name })` reads a property from another key of the body, and writes it back under that key in [responses](#shaping-responses): ```ts export class CreateUserDto { @Expose({ name: 'first_name' }) @IsString() firstName: string; } ``` A body `{ "first_name": "Ada" }` gives `dto.firstName === 'Ada'`. ### Choosing a class from the input When a property can hold several shapes, `@Type` with a `discriminator` picks the class from a property of the value. Arrays work the same way, item by item: ```ts class CatDto { @IsString() name: string; } class DogDto { @IsString() name: string; @IsBoolean() goodBoy: boolean; } export class CreatePetDto { @ValidateNested() @Type(() => Object, { discriminator: { property: 'kind', subTypes: [ { name: 'cat', value: CatDto }, { name: 'dog', value: DogDto }, ], }, }) pet: CatDto | DogDto; } ``` The `kind` property is removed from the value before it is validated. Pass `keepDiscriminatorProperty: true` to keep it (then declare it on each class, for example with `@IsIn(['cat'])`). ## Custom validators Write a class with a `validate` method and mark it with `@ValidatorConstraint`, then use it with `@Validate`: ```ts import { Validate, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from '@meghjs/core'; @ValidatorConstraint({ name: 'isSlug' }) class IsSlugConstraint implements ValidatorConstraintInterface { validate(value: unknown) { return typeof value === 'string' && /^[a-z0-9-]+$/.test(value); } defaultMessage(args: ValidationArguments) { return `${args.property} must be a slug`; } } export class CreatePostDto { @Validate(IsSlugConstraint) slug: string; } ``` The constraint key in errors is the `name` (`{ isSlug: 'slug must be a slug' }`), or the class name when no name is given. Constraints passed as `@Validate(Class, [a, b])` reach the validator as `args.constraints`. To make a reusable decorator, use `registerDecorator`: ```ts import { registerDecorator, ValidationOptions } from '@meghjs/core'; export function IsSlug(options?: ValidationOptions) { return (object: object, propertyName: string) => registerDecorator({ name: 'isSlug', target: object.constructor, propertyName, options, validator: { validate: (value) => typeof value === 'string' && /^[a-z0-9-]+$/.test(value), defaultMessage: (args) => `${args!.property} must be a slug`, }, }); } ``` ### Async validators A validator may return a promise, for example to check the database: ```ts @ValidatorConstraint({ name: 'isEmailFree', async: true }) class IsEmailFree implements ValidatorConstraintInterface { async validate(email: string) { return !(await User.findBy('email', email)); } defaultMessage() { return 'email is already registered'; } } ``` Request validation waits for async validators. DTOs without them are still validated synchronously. To validate one by hand, use `validateDtoAsync` (`validateDto` throws for a DTO with an async validator). The validator class is created once, with no constructor arguments, and reused. ## Shaping responses `HttpResponse.Ok(data, Class)` and `HttpResponse.Created(data, Class)` return `data` shaped by `Class`: only properties marked with `@Expose()` are kept, converted to their declared types, and nested classes are shaped by their own decorators: ```ts import { Exclude, Expose, HttpResponse, Type } from '@meghjs/core'; class AuthorView { @Expose() name: string; } export class PostView { @Expose() id: number; @Expose({ name: 'post_title' }) title: string; @Expose() @Type(() => AuthorView) author: AuthorView; } // In a controller: return HttpResponse.Ok(post, PostView); // { message: 'success', data: { id: 1, post_title: '…', author: { name: '…' } } } ``` `@Exclude()` drops a property (`@Exclude({ toPlainOnly: true })` drops it from responses only), and `@Exclude()` on a class drops every property that isn't `@Expose`d. `@Transform(fn, { toPlainOnly: true })` changes a value in responses only. The same conversions are available directly as `plainToInstance(Class, plain, options?)` and `instanceToPlain(object, options?)`, with class-transformer's names. They support the `excludeExtraneousValues`, `enableImplicitConversion` and `exposeUnsetFields` options. `groups` and versions (`since`, `until`) are not supported: an `@Expose` with `groups` is never applied. ## Switching from class-validator Existing class-validator DTOs keep working as long as class-validator and class-transformer are installed. They are optional peers of `@meghjs/core`: an app whose DTOs all use Megh's decorators doesn't need them. To switch a DTO, import its decorators from `@meghjs/core` instead: ```ts import { IsString, MinLength } from 'class-validator'; // [!code --] import { Type } from 'class-transformer'; // [!code --] import { IsString, MinLength, Type } from '@meghjs/core'; // [!code ++] ``` Error responses, the values your handler receives and the [OpenAPI](/microservices/openapi) schema stay the same. Switch every decorator of a DTO at once. A DTO that mixes `@meghjs/core` decorators with class-validator or class-transformer ones fails when the app starts, because each library would only check its own rules. Nested DTOs (`@Type(() => AddressDto)`) must use Megh's decorators too. Custom validators move the same way: import `ValidatorConstraint`, `Validate` and `registerDecorator` from `@meghjs/core`. Once no DTO imports from them, uninstall the two packages: ```sh npm uninstall class-validator class-transformer ``` What Megh does not support: - validation groups (`groups`, `always`) and `@Expose` groups and versions - class-validator's `useContainer`: a custom validator class is created with no constructor arguments - class-validator decorators not in the [table](#decorators) (such as `IsLatitude`, `IsISBN`, `IsEthereumAddress`). Write them with [`registerDecorator`](#custom-validators) or keep that DTO on class-validator. ### Faster class-validator DTOs (experimental) Apps that keep class-validator DTOs can have them validated by a function compiled from class-validator's own rules: ```ts const app = Megh.createApplication({ experimental: { compiledValidation: true }, }); ``` or set `MEGH_COMPILED_VALIDATION=1`. Results are the same as without it; DTOs it cannot reproduce exactly (nested DTOs, `@Type`, `@Transform`, async validators) are validated by class-validator as before. This option may change in a minor release. ## Deriving DTOs Rather than repeating fields, derive one DTO from another: | Helper | Result | |--------|--------| | `PartialType(Dto)` | Every property optional — ideal for updates | | `PickType(Dto, ['a', 'b'])` | Only the named properties | | `OmitType(Dto, ['a'])` | Everything except the named properties | ```ts [dtos/update-user.dto.ts] import { PartialType } from '@meghjs/core'; import { CreateUserDto } from './create-user.dto'; export class UpdateUserDto extends PartialType(CreateUserDto) {} ``` The derived class keeps the validation and transformation rules of the properties it keeps, from class-validator, class-transformer or Megh's own decorators, along with their OpenAPI metadata and default values. `PartialType` also marks every property `@IsOptional()`, so a missing field passes but a present one is still checked. The derived DTO doesn't extend the source: `instanceof CreateUserDto` is `false` for an `UpdateUserDto`. ## Validating by hand To run a DTO's validation outside a route, use `validateDto`: ```ts import { validateDto } from '@meghjs/core'; const { value, errors } = validateDto(CreateUserDto, input); if (errors) { // [{ path: 'email', constraints: { isEmail: 'email must be an email' } }] } ``` `value` is the DTO instance and `errors` is `null` when the input is valid, the same shape as the 400 response's `errors`. For DTOs with [async validators](#async-validators), use `validateDtoAsync`. For class-validator DTOs, use `transformAndValidate`, which works the same for either kind of DTO but returns a promise: ```ts import { transformAndValidate } from '@meghjs/core'; const { value, errors } = await transformAndValidate(CreateUserDto, input); ``` For input that does not come from a DTO, `validateOrThrow` checks a plain object against a rule map and throws a `BadRequestException` on failure: ```ts import { validateOrThrow } from '@meghjs/core'; validateOrThrow( { page: 1 }, { page: { type: 'number', min: 1, required: true } }, ); ``` Supported rule types are `string`, `number` (with `min`, `max`, `exact`) and `boolean`, each accepting `required`, `optional` and a custom `message`. - `number` accepts any finite number, including `0`. - `boolean` accepts `true`, `false`, `"true"`, `"false"`, `0`, `1`, `"0"` and `"1"`. - A value of `undefined`, `null` or `""` counts as missing. --- # Error Handling Source: https://meghjs.github.io/core-concept/error-handling Throw an exception anywhere in a request (a controller, a service, a middleware or an authorizer) and Megh turns it into a JSON response. ```ts import { Controller, Get, Param, NotFoundException } from '@meghjs/core'; @Controller('/users') export class UsersController { @Get('/:id') async findOne(@Param('id') id: number) { const user = await this.users.findByPk(id); if (!user) throw new NotFoundException('User not found'); return user; } } ``` ```json { "code": 404, "status": "Error", "message": "User not found", "data": { "message": "User not found" } } ``` ## HTTP exceptions | Class | Status | Factory | | ------------------------------- | ------ | ------------------------------------- | | `BadRequestException` | 400 | `HttpExceptions.badRequest()` | | `ValidationErrorException` | 400 | `HttpExceptions.validationError()` | | `UnauthorizedException` | 401 | `HttpExceptions.unauthorized()` | | `ForbiddenException` | 403 | `HttpExceptions.forbidden()` | | `NotFoundException` | 404 | `HttpExceptions.notFound()` | | `MethodNotAllowedException` | 405 | `HttpExceptions.methodNotAllowed()` | | `NotAcceptableException` | 406 | | | `RequestTimeoutException` | 408 | | | `ConflictException` | 409 | `HttpExceptions.conflict()` | | `GoneException` | 410 | `HttpExceptions.gone()` | | `PayloadTooLargeException` | 413 | `HttpExceptions.payloadTooLarge()` | | `UnsupportedMediaTypeException` | 415 | `HttpExceptions.unsupportedMediaType()` | | `UnprocessableEntityException` | 422 | `HttpExceptions.unprocessableEntity()` | | `TooManyRequestsException` | 429 | `HttpExceptions.tooManyRequests()` | | `InternalErrorException` | 500 | `HttpExceptions.internalError()` | | `NotImplementedException` | 501 | `HttpExceptions.notImplemented()` | | `BadGatewayException` | 502 | | | `ServiceUnavailableException` | 503 | `HttpExceptions.serviceUnavailable()` | | `GatewayTimeoutException` | 504 | | | `HttpException` | any | `HttpExceptions.status(code, msg)` | The message can be a string or an object; an object is sent as `data`. The second argument sets response headers and keeps the original error as `cause` for logs: ```ts throw new TooManyRequestsException('Slow down', { headers: { 'Retry-After': 30 } }); throw new ServiceUnavailableException('Payments are down', { cause: err }); throw new HttpException(402, 'Payment required'); ``` ## The default response Without filters, Megh answers like this: - **HTTP exceptions** keep their status. For 4xx the message and `data` are sent. For 5xx they are sent only when `NODE_ENV=development`; otherwise the message is `Internal Server Error`. - **Validation failures**, from DTOs or the route schema, are a 400 with the individual issues in `errors`. - **Framework errors** keep their status: malformed JSON (400), body too large (413), unsupported content type (415), rate limited (429) and so on. - **Unknown routes** are a 404: `Route GET /nope not found`. - **Anything else** is a 500. In development the body adds `error` and the first lines of `stack`. Errors answered this way are logged: 4xx as warnings, the rest as errors with the stack. Replace the logger, or turn it off, with `useErrorLogger`: ```ts app.useErrorLogger((error, request, response) => { if (response.statusCode >= 500) Sentry.captureException(error); }); app.useErrorLogger(false); ``` ## Custom error handler For a quick change, register a function. It sees every error, and `response` holds what Megh would send by default: ```ts app.useErrorHandler((error, { response }) => ({ success: false, message: response.body.message, })); ``` What the handler does decides what happens next: | The handler… | Result | | -------------------------------------------- | ----------------------------------------------- | | returns a value | sent as the body, with `response.statusCode` | | calls `reply.code(...)` and returns a value | sent with that status | | sends the reply itself (`reply.send(...)`) | nothing else runs | | returns an `Error` | replaces the error; the next filter handles it | | returns nothing | the next filter, then the default response | | throws | logged; the default response is sent | ## Exception filters A filter is a class with a `catch(error, ctx)` method, following the same rules. `@Catch(...)` limits it to some error classes (subclasses included), and its constructor can take services from the container. ```ts [src/filters/out-of-stock.filter.ts] import { Catch, ConflictException, ExceptionFilter } from '@meghjs/core'; import { OutOfStockError } from '../errors/out-of-stock.error'; // Map a domain error to a 409, then let later filters format it. @Catch(OutOfStockError) export class OutOfStockFilter implements ExceptionFilter { catch(error: OutOfStockError) { return new ConflictException(error.message); } } ``` ```ts [src/filters/problem-json.filter.ts] import { Catch, ErrorContext, ExceptionFilter } from '@meghjs/core'; // Answer every error as RFC 9457 problem details. @Catch() export class ProblemJsonFilter implements ExceptionFilter { catch(error: unknown, { reply, request, response }: ErrorContext) { reply.type('application/problem+json'); return { type: 'about:blank', status: response.statusCode, title: response.body.message, instance: request.url, }; } } ``` ```ts [src/app.ts] app.useExceptionFilters([OutOfStockFilter, ProblemJsonFilter]); ``` Global filters run in registration order. `ctx.response` is already redacted in production, so building on it does not leak 5xx details. ### Per controller or route `@UseFilters` applies filters to one controller or one route. They run before the global ones: route filters first, then controller filters. ```ts import { Controller, Post, UseFilters } from '@meghjs/core'; @UseFilters(PaymentErrorFilter) @Controller('/payments') export class PaymentsController { @UseFilters((error, { reply }) => { reply.code(409); return { message: 'Refund already issued' }; }) @Post('/:id/refund') refund() { // ... } } ``` `useExceptionFilters`, `useErrorHandler` and `@UseFilters` take filter classes, filter instances or functions. Register global filters before `app.run()`. ## Testing `MeghTest` uses the same error handling as `run()`, filters included, so tests see the responses production sends, with one difference: 5xx responses include the error's message and stack, as in development, though `NODE_ENV` is `test`. Pass `errorDetails: false` to `MeghTest.from()` to get the production response. See [Testing](/advanced/testing#error-details). --- # Configuration and Environment Source: https://meghjs.github.io/core-concept/configuration Megh reads settings from environment variables and a `.env` file. Read them directly with `Environment`, or group them into typed config classes. ## The `.env` file Megh loads `.env` from the current working directory (`process.cwd()`) into `process.env` when `@meghjs/core` is first imported. Module-level code can read `process.env` straight away. ```sh [.env] PORT=4000 MAIL_HOST=smtp.example.com MAIL_PORT=587 ``` - Only `.env` is read. There is no `.env.local` or `.env.production`. - A missing `.env` is fine. Nothing is loaded and no error is raised. - Real environment variables win. A variable already set in the shell, in Docker or by your host is never overwritten by `.env`. - Run the app from the project root, or the file won't be found. ### `MEGH_DOTENV` Set `MEGH_DOTENV=false` to stop Megh loading `.env` into `process.env`, for example when your platform injects the environment itself: ```sh MEGH_DOTENV=false node dist/serve.js ``` It is checked before `.env` is read, so set it in the real environment, not in `.env`. With `MEGH_DOTENV=false`, `Environment` doesn't read `.env` either: `get()`, `getOrThrow()` and `getAll()` only see `process.env`. It is checked on every read. ## `Environment` `Environment` is an injectable service for reading variables: ```ts [src/services/mailer.service.ts] import { AppService, Environment, inject } from '@meghjs/core'; @AppService export class MailerService { private readonly env = inject(Environment); host() { return this.env.get('MAIL_HOST') ?? 'localhost'; } } ``` | Method | Returns | |--------|---------| | `get(key)` | The value, or `undefined` when it isn't set | | `getOrThrow(key)` | The value. Throws `EnvironmentVariableNotFound` (`" not found in environment variables."`, with the name in `error.key`) when it isn't set | | `getAll()` | Every variable, `.env` merged with `process.env` | | `Environment.reload()` | Static. Forget the cached `.env` so the next read loads it again | Values from `process.env` take precedence over the `.env` file in all three methods. ::: tip Values are strings The type parameter is only a cast. `env.get('PORT')` still returns the string `"4000"`. Convert it yourself: `Number(env.get('PORT'))`. ::: `getOrThrow` treats an empty value (`KEY=`) as set and returns `""`. ### Caching `Environment` parses `.env` once and keeps the result. `process.env` is read on every call, so changes to it at runtime show up straight away. Edits to the `.env` file do not, until you call `Environment.reload()` or restart. If `.env` exists but can't be read, the error is logged and `Environment` returns only the `process.env` values until `Environment.reload()`. ### Outside classes `inject()` works anywhere, for example in the startup script: ```ts [src/serve.ts] import { Environment, inject } from '@meghjs/core'; import app from './app'; async function serve() { const env = inject(Environment); if (env.get('MAINTENANCE') === 'true') return; await app.run(); } serve(); ``` ## Config classes A config class turns variables into one typed settings object. Extend `MeghConfig`, implement `config(env)`, and mark the class with `@AppConfig`: ```ts [src/config/mail.config.ts] import { AppConfig, Environment, MeghConfig } from '@meghjs/core'; export type MailSettings = { host: string; port: number; secure: boolean; from: string; }; @AppConfig export class MailConfig extends MeghConfig { config(env: Environment): MailSettings { return { host: env.get('MAIL_HOST') ?? 'localhost', port: Number(env.get('MAIL_PORT')) || 1025, secure: env.get('MAIL_SECURE') === 'true', from: env.getOrThrow('MAIL_FROM'), }; } } ``` `npx megh make:config mail` generates this file for you. `@AppConfig` registers the class with [dependency injection](/core-concept/dependency-injection). It takes no arguments, so write `@AppConfig`, not `@AppConfig()`. ### Reading a config with `GetConfig` `GetConfig(ConfigClass)` returns the object built by `config()`, typed from the class: ```ts [src/services/mailer.service.ts] import { AppService, GetConfig } from '@meghjs/core'; import { MailConfig } from '../config/mail.config'; @AppService export class MailerService { private readonly mail = GetConfig(MailConfig); // MailSettings connect() { return createTransport({ host: this.mail.host, port: this.mail.port }); } } ``` `config()` runs on the first `GetConfig` call and the result is cached, so later calls return the same object. `Environment.reload()` clears the cache, and the next `GetConfig` call runs `config()` again. If the class isn't registered, `GetConfig` throws `Config class "MailConfig" is not registered. Did you forget to apply the @AppConfig decorator?`. An error thrown inside `config()`, for example `EnvironmentVariableNotFound` from `getOrThrow`, reaches you as it is. ### Validating at boot Describe the environment as a DTO class, with the same validation decorators as request DTOs, and let the app check it when it starts: ```ts [src/config/env.ts] import { IsIn, IsInt, IsString, Min } from '@meghjs/core'; export class Env { @IsInt() @Min(1) PORT: number; @IsString() DATABASE_URL: string; @IsIn(['development', 'production', 'test']) NODE_ENV: string; } ``` ```ts [src/app.ts] app.useEnvSchema(Env); ``` `run()` then fails before anything starts, listing every problem: ```txt ConfigValidationError: [Megh] Invalid environment: PORT: PORT must not be less than 1 DATABASE_URL: DATABASE_URL must be a string ``` Only the variables the DTO declares are checked. Properties typed `number` or `boolean` are converted first (`"4000"` → `4000`, `"true"`/`"1"` → `true`). `validateEnv(Env)` does the same anywhere and returns the converted values. A config class can declare the shape of what `config()` returns: ```ts @AppConfig({ schema: MailSettingsDto }) export class MailConfig extends MeghConfig { ... } ``` The result is checked on the first `GetConfig(MailConfig)` and, for every class with a schema, when the app starts. Properties the schema doesn't declare are not checked. Both throw `ConfigValidationError`, whose `issues` list each failing property. ### Reading a token `GetConfig` also accepts a token or string name and returns whatever is registered for it in the container: ```ts import { GetConfig, MeghContainer } from '@meghjs/core'; MeghContainer.set('FEATURE_FLAGS', { newCheckout: true }); const flags = GetConfig<{ newCheckout: boolean }>('FEATURE_FLAGS'); ``` It throws `Config token "FEATURE_FLAGS" is not registered in the container.` when nothing is set. ### Passing a config class to the app Some `use*` methods take a config class in place of options and call `config()` for you: ```ts [src/app.ts] import { Megh } from '@meghjs/core'; import { OpenApiConfig } from './config/openapi.config'; import { DatabaseConfig } from './config/database.config'; const app = Megh.createApplication(); app.useMeghORM(DatabaseConfig); // MeghConfig app.useOpenApi(OpenApiConfig); // MeghConfig ``` `useMeghORM` only recognises a class that extends `MeghConfig`, so always extend it. The config is read once, when the method is called. ## Summary | API | Use | |-----|-----| | `Environment` | Injectable service: `get`, `getOrThrow`, `getAll`, `Environment.reload()` | | `EnvironmentVariableNotFound` | Error thrown by `getOrThrow()`; check it with `instanceof` | | `MeghConfig` | Base class for config classes. Implement `config(env): T` | | `@AppConfig` | Registers a config class for injection | | `GetConfig(ConfigClass)` | Builds and returns the typed settings | | `GetConfig(token)` | Returns the value registered for a token or string | | `MEGH_DOTENV=false` | Don't read `.env` at all: only `process.env` is used | See also [Application](/getting-started/application) for `NODE_ENV`, `HOST` and other variables the app reads, and [Deployment](/production/deployment) for setting the environment in production. --- # Dependency Injection Source: https://meghjs.github.io/core-concept/dependency-injection Megh builds your controllers, services and middleware for you, and gives each one the services it needs. Every service is created once and shared. ## Registering a service Mark a class with `@AppService` (or `@Injectable()`). Controllers, middleware, config classes and queue workers are registered by their own decorators. ```ts [src/services/mailer.service.ts] import { AppService } from '@meghjs/core'; @AppService export class MailerService { send(to: string, body: string) { // ... } } ``` ## Injecting with `inject()` Call `inject()` in a field initializer: ```ts [src/services/user.service.ts] import { AppService, inject } from '@meghjs/core'; import { MailerService } from './mailer.service'; import { UserRepository } from './user.repository'; @AppService export class UserService { private readonly users = inject(UserRepository); private readonly mailer = inject(MailerService); async register(email: string) { const user = await this.users.create({ email }); this.mailer.send(email, 'Welcome!'); return user; } } ``` Unlike [constructor injection](#injecting-through-the-constructor), `inject()` doesn't rely on `emitDecoratorMetadata`, so it also works with test runners and bundlers that can't emit it, such as esbuild. It works outside classes too, for example in a startup script: ```ts [serve.ts] import { Environment, inject } from '@meghjs/core'; import app from './app'; async function serve() { const env = inject(Environment); await app.run(Number(env.get('PORT')) || 4000); } serve(); ``` ### Optional dependencies Pass `{ optional: true }` to get `undefined` instead of an error when nothing is registered: ```ts private readonly analytics = inject(AnalyticsService, { optional: true }); // AnalyticsService | undefined ``` This only covers the service not being registered. If it's registered but fails to build (one of its own dependencies is missing, or its constructor throws), `inject()` still throws. ## Injecting through the constructor Constructor parameters are injected from their types: ```ts @AppService export class UserService { constructor( private readonly users: UserRepository, private readonly mailer: MailerService, ) {} } ``` This needs `experimentalDecorators` and `emitDecoratorMetadata` in `tsconfig.json`, which `megh new` projects have. Parameters typed as interfaces, unions or primitives (`string`, `number`) have no runtime type to resolve: TypeScript emits `Object` or `String` for them. Building such a class fails with a `ContainerError` that names the parameter. Inject a [token](#tokens) with `@Inject`, or mark the parameter `@Optional()` to get `undefined`: ```ts import { AppService, Inject, Optional } from '@meghjs/core'; import { PAYMENTS, type PaymentGateway } from './tokens'; @AppService export class OrderService { constructor( @Inject(PAYMENTS) private readonly gateway: PaymentGateway, @Optional() private readonly audit?: AuditLog, // undefined unless registered ) {} } ``` `@Inject(id, { optional: true })` injects `undefined` when nothing is registered for `id`. `@Optional()` on a class-typed parameter injects the instance when the class is registered, and `undefined` when it isn't. Both styles resolve the same shared instances, and you can mix them in a class. ## Tokens Use a `Token` for values that aren't classes, such as a client from another library or a setting: ```ts [src/tokens.ts] import { Token } from '@meghjs/core'; import type Stripe from 'stripe'; export const STRIPE = new Token('STRIPE'); ``` ```ts [src/app.ts] import { MeghContainer } from '@meghjs/core'; import Stripe from 'stripe'; import { STRIPE } from './tokens'; MeghContainer.set(STRIPE, new Stripe(process.env.STRIPE_SECRET_KEY!)); ``` ```ts @AppService export class BillingService { private readonly stripe = inject(STRIPE); // typed as Stripe } ``` ## `MeghContainer` | Method | Use | |--------|-----| | `MeghContainer.get(id)` | Resolve a class, token or name. Same as `inject(id)` | | `MeghContainer.set(id, value)` | Register a value, or replace a class with another implementation | | `MeghContainer.has(id)` | Whether anything is registered for `id` | | `MeghContainer.reset()` | Drop created class instances so they're built again. Token values are kept. For tests | | `MeghContainer.reset({ all: true })` | Also remove every value set for a token or string. For tests | ## Testing Replace a dependency before the class that uses it is built, and reset after each test: ```ts import { MeghContainer } from '@meghjs/core'; afterEach(() => MeghContainer.reset()); it('sends a welcome email', async () => { const sent: string[] = []; MeghContainer.set(MailerService, { send: (to: string) => sent.push(to) }); await MeghContainer.get(UserService).register('a@b.c'); expect(sent).toEqual(['a@b.c']); }); ``` `MeghContainer.set(MailerService, fake)` works for both `inject()` and constructor injection. `reset()` rebuilds a class key such as `MailerService` on the next `get`, so the fake above is gone after it. A value set on a token or string is kept, though. To remove those too, use `MeghContainer.reset({ all: true })` (or `MeghTest.clean({ all: true })`): ```ts afterEach(() => MeghContainer.reset({ all: true })); it('uses the fake gateway', async () => { MeghContainer.set(PAYMENT_GATEWAY, fakeGateway); // ... }); ``` ## Errors Errors are `ContainerError`s and name the chain of classes being built: ``` Cannot construct UserService -> MailerService: SmtpClient is not registered. Mark it with @Injectable() (or @AppService), or register an instance with MeghContainer.set(SmtpClient, value). ``` A parameter with no type to resolve fails when the class is first built, instead of injecting `undefined`: ``` Cannot resolve parameter 0 of OrderService: its type is an interface, union or primitive (emitted as Object). Use @Inject(TOKEN) on the parameter or inject(TOKEN) in a field, type it as a class, or mark it @Optional(). ``` A class-typed parameter can also show up as `Object` when two files import each other: the class isn't loaded yet when TypeScript emits the type. Two services that need each other while being built are reported instead of overflowing the stack: ``` Circular dependency: OrderService -> UserService -> OrderService. ``` To break a cycle, have one side call `inject()` inside the method that needs it, not in a field initializer or constructor. --- # Request Context Source: https://meghjs.github.io/core-concept/request-context Services are singletons, so a service deep in the call chain can't see the request it's working for. `requestContext` holds values for the request being handled and makes them readable anywhere in its async call chain, such as services, repositories and event listeners, without passing `req` through every call. Each request gets its own values. ```ts import { createContextKey, requestContext } from '@meghjs/core'; export const TENANT = createContextKey('tenant'); ``` Set a value early in the request, for example in middleware or an authenticator: ```ts @AppMiddleware export class TenantMiddleware extends MeghMiddleware { invoke(req: IRequest) { requestContext.set(TENANT, String(req.headers['x-tenant'])); return req; } } ``` Read it wherever you need it: ```ts @AppService export class InvoiceService { list() { const tenant = requestContext.get(TENANT); // string | undefined // ... } } ``` ## The current user After `useAuthentication()` resolves a user, it is on `requestContext.user` as well as `req.user`. Use `getUser()` for a typed value: ```ts const user = requestContext.getUser(); // User | undefined ``` It is `undefined` for anonymous requests, before authentication runs (in middleware), and outside a request. ## API | | | |---|---| | `createContextKey(name)` | A typed key. Two keys with the same name are still different keys, so libraries can't clash. Plain strings work too, typed as you pass them. | | `get(key)` | The value, or `undefined`. | | `getOrThrow(key)` | The value; throws when it isn't set or outside a request. | | `has(key)`, `delete(key)` | Check for or remove a value. | | `set(key, value)` | Set a value for the rest of this request. Throws outside a request. | | `user`, `getUser()` | The authenticated user. | | `requestId` | Same as `getRequestId()`. `undefined` when request IDs are off. | | `active` | `true` inside a request or `run()`. | | `run(fn, init?)` | Run `fn` in a fresh context, with optional `{ requestId, user, values }`. | ## What keeps the context The context follows the request's async chain: - awaited calls, promises and timers started in the request; - event listeners, including `dispatch(event, { queue: true })` and delayed dispatches on the in-memory queue. Each queued event runs in the context it was dispatched in. It does **not** cross process boundaries. Queue jobs on Redis or RabbitMQ, and distributed events, are handled in another process, so put what the job needs (a tenant ID, a user ID) in the job data, and use `run()` in the worker if the code you call reads the context: ```ts @MeghWorker({ queue: 'invoices' }) export class InvoiceWorker extends MeghWorkerBase<{ tenant: string }> { private readonly invoices = inject(InvoiceService); process(job: Job<{ tenant: string }>) { return requestContext.run(() => this.invoices.generate(), { values: [[TENANT, job.data.tenant]], }); } } ``` Socket.IO handlers aren't requests either. They have their own context (see [WebSocket](/microservices/websocket)). ## Tests and scripts Code that reads the context works outside a request too: `get` returns `undefined`. To give it values, wrap the call in `run()`: ```ts const invoices = await requestContext.run(() => service.list(), { values: [[TENANT, 'acme']], user: { id: 1 }, }); ``` --- # Authentication Source: https://meghjs.github.io/core-concept/authentication Megh splits access control into two steps: - **Authentication** works out *who* the caller is and sets `request.user`. - **Authorization** decides whether that caller may use a route marked `@Authorized`. ## Authentication Extend `MeghAuthentication` and return the user, or `null` for an anonymous request. Whatever you return becomes `request.user`: ```ts [auth/jwt.authentication.ts] import { MeghAuthentication, AppService, IRequest } from '@meghjs/core'; @AppService export class JwtAuthentication extends MeghAuthentication { async authenticate(request: IRequest) { const header = request.headers.authorization; if (!header?.startsWith('Bearer ')) return null; return verifyToken(header.slice(7)); } } ``` Register it once: ```ts [app.ts] app.useAuthentication(JwtAuthentication); ``` Read the user in a handler with `@AuthUser()`: ```ts @Controller('/me') export class MeController { @Get() whoami(@AuthUser() user: User) { return user; } } ``` Authentication never rejects a request by itself. Use authorization for that. ## Authorization Authorization is **deny-by-default**. Write a class with an `authorize` method and mark it `@CanAuthorize`: ```ts [auth/jwt.authorization.ts] import { CanAuthorize, IRequest, HttpExceptions } from '@meghjs/core'; @CanAuthorize export class JwtAuthorization { async authorize(req: IRequest, options?: { roles?: string[] }) { if (!req.user) throw HttpExceptions.unauthorized('Login required'); // 401 if (options?.roles && !options.roles.includes(req.user.role)) { return false; // 403 } } } ``` | `authorize` result | Response | |--------------------|----------| | returns `false` | 403 | | throws an `HttpExceptions` error | that error's status | | returns anything else (including nothing) | request continues | Register it: ```ts [app.ts] app.useAuthorization(JwtAuthorization); ``` ### Protecting routes ```ts // every route in the controller @Authorized() @Controller('/admin') export class AdminController { @Get() dashboard(@AuthUser() user: User) { return user; } } // one route, with options passed to authorize() @Controller('/reports') export class ReportsController { @Authorized({ roles: ['admin'] }) @Get('/stats') stats() {} } ``` ::: warning If no authorizer is registered, Megh logs a warning at boot and every `@Authorized` route answers **403**. ::: ### Multiple strategies Register several authorizers by name and choose one per route: ```ts app.useAuthorization({ jwt: JwtAuthorization, apiKey: ApiKeyAuthorization }); @Authorized('apiKey') // by name @Authorized({ name: 'jwt', roles: ['admin'] }) // by name, with options ``` `@Authorized()` with no name uses the first registered handler. Naming a handler that is not registered makes `app.run()` fail at boot. ### Deny by default A route without `@Authorized` is public, so forgetting it on one handler leaves that endpoint open. To flip this, set a default with `useAuthorization`, and mark the routes that stay open with `@Public()`: ```ts app.useAuthentication(JwtAuthentication); app.useAuthorization(JwtAuthorization, { default: 'authenticated' }); @Public() @Controller('/auth') export class AuthController { @Post('/login') login() {} } app.mapGet('/status', () => ({ ok: true })).public(); ``` | `default` | Every route without `@Authorized` or `@Public` needs | |---|---| | `'authenticated'` | A user from `useAuthentication()`, else **401** | | `true` | The default authorizer, like a bare `@Authorized()` | | `'jwt'`, `{ name: 'jwt', roles: ['user'] }` | That authorizer and options, like `@Authorized('jwt')` | - An explicit `@Authorized` on a route or its controller always wins over the default, and over `@Public`. A route marked with both logs a warning at boot. - `@Public()` works on a controller or a route. Inline routes use `.public()`. - Health probes (`useHealth()`), the OpenAPI UI and static files aren't routes Megh authorizes, so they stay public. - The default is off unless you set it. `megh route:list` shows each route as `authorized`, `public` or `default` (protected only when a default is set). ## Order of checks Middleware runs first (global, then `@UseMiddleware`), then authentication, then the class and method `@Authorized` checks, then validation. See [Middleware](/core-concept/middleware#pipeline-order). ## Server-rendered apps For an app with views, keep the logged-in user in a [session](/advanced/sessions#logging-in). With `loginPath`, browsers are redirected to the login page instead of getting a 401, and [gates](/advanced/sessions#gates) add permission checks you can use in views with `@can`. --- # Sessions Source: https://meghjs.github.io/advanced/sessions :::: v-pre Sessions keep per-visitor state between requests, such as who is logged in, a cart, or a message to show after a redirect. Use them with [views](/advanced/views). An API with token authentication doesn't need them. The browser gets one cookie holding a random session ID, signed with HMAC-SHA256. The data stays on the server. ## Setup ```ts [app.ts] app.useSession({ secret: process.env.SESSION_SECRET }); ``` The secret must be at least 32 characters. Leave `secret` out and Megh reads `SESSION_SECRET`. To generate one: ```sh node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))" ``` | Option | Default | Meaning | | ------------ | ---------------- | -------------------------------------------------------------------------------------- | | `secret` | `SESSION_SECRET` | Signs the cookie. An array rotates keys: the first signs, all of them verify | | `cookieName` | `megh_session` | Cookie name | | `maxAge` | `'2h'` | Lifetime after the last change: milliseconds or `'30m'`, `'7 days'` | | `rolling` | `false` | Save on every request, so the session expires after inactivity instead | | `cookie` | see below | `path` (`/`), `domain`, `httpOnly` (`true`), `sameSite` (`'lax'`), `secure` (`'auto'`) | | `store` | memory | A `SessionStore`, see [Stores](#stores) | | `redis` | | Shortcut for `store: new RedisSessionStore(redis)` | | `loginPath` | | Send browsers that need to log in here instead of a 401, see [Protecting pages](#protecting-pages) | With `secure: 'auto'` the cookie is `Secure` when the request came over HTTPS. Behind a proxy that ends TLS, set `server.trustProxy` so Megh can tell. A visitor gets a cookie only once something is stored in their session. ## Using the session Inject it with `@Session()`: ```ts [controllers/cart.controller.ts] import { Controller, MeghSession, Param, Post, Results, Session, } from "@meghjs/core"; @Controller("/cart") export class CartController { @Post("/add/:id") add(@Param("id") id: number, @Session() session: MeghSession) { const items = session.get("cart") ?? []; session.set("cart", [...items, id]); session.flash("status", "Added to your cart."); return Results.Redirect("/cart"); } } ``` | Method | Does | | ------------------------- | ---------------------------------------------------------------------------- | | `get(key)` / `has(key)` | Read a value, or one flashed by the previous request | | `set(key, value)` | Store a value. It must survive `JSON.stringify` | | `pull(key)` | Read and remove | | `delete(key)` / `clear()` | Remove one value / all of them | | `all()` | Every value | | `flash(key, value)` | Store a value for the **next** request only, e.g. a message after a redirect | | `reflash()` | Keep this request's flashed values for one more request | | `regenerate()` | Move to a new session ID, keeping the data. Call it on login | | `destroy()` | Delete the session and clear the cookie. Call it on logout | | `intended(fallback)` | The page a guest asked for before being sent to log in, else `fallback` | | `id` / `isNew` | The session ID; `true` if the visitor had no session before this request | Changes are saved when the response is sent. Outside a controller, `currentSession()` returns the current request's session. Keys starting with `__` are reserved for Megh. ## Logging in Store the user's ID in the session, and read it back in an [authentication handler](/core-concept/authentication). Then `@AuthUser()`, `@Authorized()` and the `@auth` directive all work as usual: ```ts [auth/session.authentication.ts] import { AppService, IRequest, MeghAuthentication, currentSession, } from "@meghjs/core"; @AppService export class SessionAuthentication extends MeghAuthentication { constructor(private readonly users: UserRepository) { super(); } async authenticate(_request: IRequest) { const id = currentSession()?.get("userId"); return id ? this.users.find(id) : null; } } ``` ```ts [app.ts] app.useSession(); app.useAuthentication(SessionAuthentication); ``` ```ts [controllers/auth.controller.ts] @Post("/login") async login(@Body() form: LoginForm, @Session() session: MeghSession) { const user = await this.users.verify(form.email, form.password); if (!user) { session.flash("error", "Wrong email or password."); return Results.Redirect("/login"); } session.regenerate().set("userId", user.id); return Results.Redirect(session.intended("/")); } @Post("/logout") logout(@Session() session: MeghSession) { session.destroy(); return Results.Redirect("/"); } ``` Always call `regenerate()` on login. Without it, someone who planted a session ID in the victim's browser before login (session fixation) would share the logged-in session. ## Protecting pages Route protection is the usual [authorization](/core-concept/authentication): `useAuthorization()` with `default: "authenticated"` protects every route, `@Public()` opens the login page, and `@Authorized({ roles: ["admin"] })` runs your handler. For a browser, a 401 JSON body is no use, so set `loginPath`: ```ts [app.ts] app.useSession({ loginPath: "/login" }); app.useAuthentication(SessionAuthentication); app.useAuthorization(RoleAuthorization, { default: "authenticated" }); ``` When a route answers 401 and the request accepts HTML, the browser is redirected to `/login` instead: - A GET remembers its URL, and `session.intended("/")` returns it after login. It is always a path on your site, so it can't send users elsewhere. - A form POST gets a 303 and isn't remembered, because it can't be replayed. - JSON requests (`Accept: application/json`), XHR (`X-Requested-With: XMLHttpRequest`) and clients that don't ask for HTML keep the 401. - A 403 stays a 403: the user is logged in, just not allowed. Your own exception filters run first, so one that handles 401 itself wins. ## Gates A gate is a named permission check, defined once and used in views and code: ```ts [app.ts] app.defineGate("edit-post", (user: User, post: Post) => user.role === "admin" || user.id === post.authorId, ); ``` ```ts [controllers/posts.controller.ts] import { gate } from "@meghjs/core"; @Post("/:id") async update(@Param("id") id: number, @Body() form: PostForm) { const post = await this.posts.find(id); gate.authorize("edit-post", post); // 401 for a guest, 403 when denied // ... } ``` | Method | Does | | -------------------------------------- | ------------------------------------------------------------ | | `gate.allows(name, ...args)` | `true` when the current user passes. Guests never do | | `gate.denies(name, ...args)` | The opposite | | `gate.authorize(name, ...args)` | Throws `UnauthorizedException` / `ForbiddenException` | | `gate.forUser(user).allows(name, ...)` | Check another user, e.g. in a job | The check gets the user from `useAuthentication()`, then your arguments. Guests are denied without calling it. It must return `true` or `false` synchronously, because views render synchronously: load the post before checking, and pass it in. `Gate` can also be injected. ## In views Views get the session as `session`. Values you pass to `Results.View` take precedence. ```html [views/layouts/app.megh.html] @session('status')

{{ value }}

@endsession

{{ session.get('cart')?.length ?? 0 }} items

@can('edit-post', post) Edit @else Read only @endcan ``` - `@auth` … `@endauth` renders when the request has an authenticated user, meaning whatever `useAuthentication()` resolved. `@else` works inside it. It checks the request, not the view data, so a `user` you pass to a profile page doesn't count. - `@guest` … `@endguest` is the opposite. - `@session('key')` … `@endsession` renders only when the session has the key, flashed values included, with the value as `value`. - `@can('gate', ...args)` … `@endcan` renders when the user passes the [gate](#gates); `@cannot` … `@endcannot` when they don't. Both take `@else`. ## Stores The default `MemorySessionStore` keeps sessions in the process. Sessions are lost on restart and not shared between replicas. In production, use Redis: ```ts import Redis from "ioredis"; app.useSession({ redis: new Redis(process.env.REDIS_URL!) }); ``` Keys are `megh:session:`, each with a TTL of `maxAge`. For another database, implement `SessionStore`: ```ts import type { SessionData, SessionStore } from "@meghjs/core"; class PgSessionStore implements SessionStore { async get(id: string): Promise { /* ... */ } async set(id: string, data: SessionData, ttlMs: number) { /* ... */ } async destroy(id: string) { /* ... */ } } app.useSession({ store: new PgSessionStore() }); ``` A store Megh created is closed when the app shuts down. One you pass in is yours to close. :::: --- # Hashing Source: https://meghjs.github.io/core-concept/hashing `Hash` hashes passwords and other secrets one way, and checks a value against a hash. It has three drivers: | Driver | Package | Notes | |---|---|---| | `scrypt` (default) | none, built into Node.js | N = 2^17, r = 8, p = 1 (OWASP) | | `bcrypt` | `bcrypt` (native) or `bcryptjs` | 12 rounds. Values over 72 bytes are refused | | `argon2` | `argon2` | argon2id, 19 MiB, 2 iterations, 1 lane (OWASP) | scrypt needs no install, so it's the default. For the others, install the package; without it, `Hash` throws `[Megh] argon2 is not installed. Run: npm install argon2`. ```sh npm i argon2 # argon2 npm i bcrypt # bcrypt, native npm i bcryptjs # bcrypt, pure JavaScript ``` With both `bcrypt` and `bcryptjs` installed, Megh uses `bcrypt`. ## Hashing and checking Inject `Hash` like any service: ```ts import { AppService, Hash } from '@meghjs/core'; @AppService export class AccountService { constructor(private readonly hash: Hash) {} async register(email: string, password: string) { return User.create({ email, password: await this.hash.make(password) }); } async signIn(email: string, password: string) { const user = await User.findBy('email', email); if (!user || !(await this.hash.check(password, user.password))) { throw new UnauthorizedException('Invalid email or password.'); } return user; } } ``` Outside a class, call the same methods on `Hash` itself, or on the `hash` helper: ```ts import { Hash, hash } from '@meghjs/core'; const hashed = await Hash.make('secret'); await hash.check('secret', hashed); // true ``` - `make(value, options?)` hashes `value` with the default driver and a new random salt, so the same value gives a different hash each time. - `check(value, hashed)` returns `true` when they match. It reads the algorithm from the hash, so it checks scrypt, bcrypt and argon2 hashes whatever the default driver is. A wrong value, an empty or malformed hash, or one Megh doesn't know returns `false`. It only throws when the hash needs a package that isn't installed. - `needsRehash(hashed, options?)` returns `true` when `hashed` was made by another driver or with other settings than the current ones. - `driver(name)` gives one driver with its configured settings: `hash.driver('bcrypt').make(value)`. Comparisons run in constant time. Megh never logs the values it hashes. ## Settings Pick the driver and its settings with `app.useHashing()`: ```ts [src/app.ts] app.useHashing({ driver: 'argon2', argon2: { memoryCost: 19456, timeCost: 2, parallelism: 1 }, }); ``` Or with an `@AppConfig` class, the same way as other `use*` settings: ```ts [src/config/hashing.config.ts] import { AppConfig, MeghConfig, type HashingConfig } from '@meghjs/core'; @AppConfig export class HashingSettings extends MeghConfig { config(): HashingConfig { return { driver: 'bcrypt', bcrypt: { rounds: 12 } }; } } ``` ```ts [src/app.ts] app.useHashing(HashingSettings); ``` | Setting | Default | | |---|---|---| | `driver` | `scrypt` | `scrypt`, `bcrypt` or `argon2` | | `scrypt.cost` | `131072` | N, a power of two | | `scrypt.blockSize` | `8` | r | | `scrypt.parallelization` | `1` | p | | `scrypt.saltLength` | `16` | Bytes, at least 16 | | `scrypt.keyLength` | `64` | Bytes | | `bcrypt.rounds` | `12` | 4 to 31; each step doubles the time | | `argon2.memoryCost` | `19456` | KiB | | `argon2.timeCost` | `2` | Iterations | | `argon2.parallelism` | `1` | Lanes | An unknown driver or an invalid setting throws when `useHashing()` runs. Without `useHashing()`, `Hash` uses scrypt with the defaults. scrypt hashes look like `scrypt$$$

$$` (base64). bcrypt and argon2 hashes use their usual formats (`$2b$12$...`, `$argon2id$v=19$...`). ### bcrypt and long passwords bcrypt only reads the first 72 bytes of a value. Instead of hashing a cut-off value, `make()` throws a `HashingError` for anything longer (and for values containing a NUL character). Bytes, not characters: `é` is two bytes. Limit password length in your DTO, or use argon2 or scrypt. ## Upgrading old hashes When you change the driver or raise the cost, existing hashes keep working, because `check()` reads the algorithm from each hash. Rehash a user's password the next time they sign in: ```ts if (await this.hash.check(password, user.password)) { if (this.hash.needsRehash(user.password)) { user.password = await this.hash.make(password); await user.save(); } } ``` `megh scaffold:auth` writes this into `AuthService.login()`. Hashes from earlier versions of `scaffold:auth` (`scrypt$$`) still check, and `needsRehash()` returns `true` for them. ## Tests Hashing is slow on purpose. In tests, make it cheap: ```ts import { Hash } from '@meghjs/core'; beforeAll(() => Hash.configure({ scrypt: { cost: 1024 }, bcrypt: { rounds: 4 }, argon2: { memoryCost: 1024, timeCost: 1 }, }), ); afterAll(() => Hash.reset()); ``` `Hash.configure()` takes the same options as `useHashing()`, and `Hash.reset()` goes back to scrypt with the defaults. Don't use these settings outside tests. ## From the command line `megh make:hash` prints a hash, for example for a seeder, or checks a value against one: ```sh megh make:hash < password.txt megh make:hash --bcrypt --rounds 10 < password.txt megh make:hash --verify '$2b$12$...' < password.txt # prints match or no match ``` See [CLI: Hashing a value](/cli/basic#hashing-a-value). --- # Security Hardening Source: https://meghjs.github.io/production/security Megh ships with safe defaults for the parts it owns. The rest, such as CORS, security headers and rate limits, depends on your app, so you turn it on yourself. The checklist below shows how. ## What Megh does by default ### `@Authorized` fails closed A route marked `@Authorized` (or `.authorized()` on an inline route) is never served without an authorization handler. If you forget `app.useAuthorization(...)`, every request gets **403**, and startup logs a warning: ```text GET /admin uses @Authorized but no authorization handler is registered; every request will be denied (403). Call app.useAuthorization(YourAuthorization). ``` An `authorize` method that returns `false` also answers 403. See [Authentication](/core-concept/authentication). ### DTOs reject unknown properties `@Body()` and `@Query()` DTOs are validated with `whitelist` and `forbidNonWhitelisted`. A property the DTO doesn't declare fails with 400, so a client can't slip `isAdmin: true` into a model. See [Validation](/core-concept/validation). ### 5xx details stay on the server Unless `NODE_ENV=development`, a 5xx response is only: ```json { "code": 500, "status": "Error", "message": "Internal Server Error" } ``` The real message, payload and stack are logged, not sent. 4xx messages are sent as written, so don't put internal details in them. `/ready` likewise hides why a health check failed outside development. ### Uploads stay in their folder `FileStorage` treats uploads as untrusted. By default it: - saves files under a random UUID name that keeps the extension; - rejects filenames containing `/`, `\`, `..` or null bytes; - keeps every path, including `to`, inside `baseDir`. When saving or reading it checks this again after following symlinks; - accepts only an allowlist of extensions (images, PDF, office files, text/CSV, zip, audio and video). HTML, SVG and JS are rejected; - never overwrites an existing file. The MIME type is not checked unless you set `allowedMimeTypes`. See [File Uploads](/advanced/file-uploads). ### Download headers are escaped `Results.OkStream(stream, { filename })` builds `Content-Disposition` so a filename can't inject headers: the plain `filename` keeps only safe ASCII and the real name goes in the RFC 5987 `filename*` parameter. ### Logs leave out credentials - Error logs record the method, URL, status and error. Request headers and bodies are not logged. - Database passwords are replaced by `***` in connection log lines and connection errors. - A client's `x-request-id` is only reused if it matches `^[\w.:-]{1,128}$`; anything else is replaced by a generated ID, so it can't forge log lines. The URL includes the query string, so keep tokens out of query parameters. ## Checklist ### Restrict CORS `useCors` passes its options to `@fastify/cors`. The scaffold uses `origin: '*'`; list your front-ends instead: ```ts app.useCors({ origin: ['https://app.example.com', /\.example\.com$/], credentials: true, }); ``` Browsers refuse credentialed requests when the allowed origin is `*`. ### Add security headers `app.useSecurityHeaders()` sends these headers on every response, including errors and 404s: | Header | Default | | --- | --- | | `Content-Security-Policy` | `default-src 'self'`, no plugins, no inline script, no framing by other sites | | `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | | `X-Frame-Options` | `SAMEORIGIN` | | `Referrer-Policy` | `no-referrer` | | `Cross-Origin-Opener-Policy` | `same-origin` | | `Cross-Origin-Resource-Policy` | `same-origin` | | `X-Content-Type-Options` | `nosniff` | | `Origin-Agent-Cluster`, `X-DNS-Prefetch-Control`, `X-Download-Options`, `X-Permitted-Cross-Domain-Policies` | `?1`, `off`, `noopen`, `none` | | `X-XSS-Protection` | `0`, which turns off the old XSS filter (it caused more holes than it closed) | ```ts [src/app.ts] app.useSecurityHeaders(); ``` Pass `false` to leave a header out, or change it: ```ts app.useSecurityHeaders({ contentSecurityPolicy: { directives: { imgSrc: ["'self'", 'https://cdn.example.com'], // camelCase or 'img-src' upgradeInsecureRequests: false, // drop a default }, }, strictTransportSecurity: { maxAge: 63072000, preload: true }, frameOptions: 'DENY', crossOriginResourcePolicy: 'cross-origin', // a public asset API headers: { 'Permissions-Policy': 'camera=(), microphone=()' }, }); ``` - `contentSecurityPolicy: { reportOnly: true }` sends `Content-Security-Policy-Report-Only`, so you can try a policy before enforcing it. `useDefaults: false` starts from an empty policy. - `crossOriginEmbedderPolicy` is off unless you set it, since it blocks cross-origin images and scripts. - `headers` adds any other header, or removes a default with `false`. - A header a route sets itself wins over the default. - The API docs page from `useOpenApi()` keeps its own CSP. Swagger UI sends a policy that fits it, and Scalar needs inline script, so both still load. Megh checks the options at startup and throws on a value that could break or inject a header, such as a newline or a `;` in a CSP source. ### Add rate limits `app.useRateLimit()` limits each client to 100 requests a minute, counted per IP in memory. Over the limit, the client gets **429** in Megh's error shape, with `Retry-After`: ```ts [src/app.ts] app.useRateLimit(); // 100 a minute app.useRateLimit({ max: 300, window: '5m' }); // window: ms, '30s', '15m', '1 hour' ``` Every limited response carries `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` (seconds left in the window). Pass `headers: false` to hide them. Give a sensitive route a tighter limit with `@RateLimit()`, on a method or a whole controller. It gets its own counter, so login attempts don't use up the app-wide allowance. `@RateLimit(false)` takes a route out: ```ts [src/controllers/auth.controller.ts] import { Controller, Get, Post, RateLimit } from '@meghjs/core'; @Controller('/auth') export class AuthController { @Post('/login') @RateLimit({ max: 5, window: '15m' }) login() {} @Get('/status') @RateLimit(false) status() {} } ``` Inline routes take `.rateLimit({ ... })`. `@RateLimit()` works without `useRateLimit()`: then only the routes that declare a limit are limited, as with `useRateLimit({ global: false })`. More options: ```ts app.useRateLimit({ key: (req) => String(req.headers['x-api-key'] ?? req.ip), // count per API key skip: (req) => req.ip === '10.0.0.5', // internal callers message: 'Slow down', }); ``` Things to know: - **Behind a proxy**, `request.ip` is the proxy's address unless you set `trustProxy` (next section). Without it, every client shares one counter. Set it to a hop count or the proxy's address, never `true`: with `true`, clients can send their own `X-Forwarded-For` and get a fresh counter on every request. Megh warns at boot when rate limiting runs with `trustProxy: true`. - **Several replicas** each count on their own with the memory store. Give Redis connection options so they share one count: ```ts app.useRateLimit({ redis: { url: process.env.REDIS_URL } }); ``` Megh opens the connection on the first request and closes it on shutdown. `new RedisRateLimitStore({ url }, { prefix })` builds the store yourself; the prefix defaults to `megh:rate-limit:`, and `close()` closes it. For another backend, implement `RateLimitStore` (`hit(key, windowMs)` returns `{ count, resetAt }`) and pass it as `store`. - A route's own limit (`@RateLimit`) is one counter per handler. With URI versioning, `/v1/login` and `/v2/login` share it, so `@Version(['1', '2'])` doesn't double the attempts a client gets. - **IPv6 clients** are counted per `/64` network, because one host usually owns a whole `/64` and could rotate addresses inside it to dodge the limit. Change it with `ipv6Subnet` (`128` counts each address). IPv4 is counted per address. - **The memory store holds at most 100,000 clients.** Past that it drops the oldest windows first and logs a warning once, so a flood of new addresses can't exhaust memory. Dropped clients start a fresh count. Raise the cap with `store: new MemoryRateLimitStore({ maxKeys: 500_000 })`, or use Redis. - **If the store fails** (Redis is down), requests get 500. Set `failOpen: true` to let them through instead; the error is still logged. - `/health` and `/ready` from `useHealth()` are never limited, so probes keep answering. Unknown URLs are limited, so scanning for paths counts. - Limits use a fixed window: a client can send up to `max` at the end of one window and `max` more at the start of the next. ### Terminate HTTPS at a proxy Serve HTTPS from a load balancer, ingress or reverse proxy, and keep the app on plain HTTP inside the network. Tell Fastify to trust the proxy so `request.ip`, `request.protocol` and `request.hostname` come from the `X-Forwarded-*` headers: ```ts const app = Megh.createApplication({ server: { trustProxy: 1 }, // one proxy in front; or its address, e.g. '10.0.0.0/8' }); ``` Don't use `trustProxy: true`. Common proxies, such as nginx with `$proxy_add_x_forwarded_for` and AWS ALB, **append** the client's address to `X-Forwarded-For` instead of replacing it. With `true`, Fastify takes the leftmost entry, which the client wrote, so clients can spoof their IP and dodge rate limits. A hop count (the number of proxies you run) or the proxies' addresses make Fastify read the entry your own proxy added. Bind to `127.0.0.1` (`HOST=127.0.0.1`) when the proxy runs on the same machine. To terminate TLS in Node instead, pass `server.https`. ### Limit body sizes Fastify rejects JSON bodies over 1 MiB with 413. Lower it if your API takes small payloads: ```ts Megh.createApplication({ server: { bodyLimit: 100 * 1024 } }); // 100 KB ``` `useMultipart()` limits each file to 10 MB by default. Set `limits` to change it, and cap the number of files and fields too: ```ts app.useMultipart({ limits: { fileSize: 5 * 1024 * 1024, files: 1, fields: 10 } }); ``` ### Keep secrets in the environment - Read secrets from environment variables or your platform's secret store. The scaffold's `.gitignore` already leaves out `.env` and `.env.local`. - Don't bake `.env` into images. Add it to `.dockerignore`. - Fail fast when a secret is missing: `env.getOrThrow('JWT_SECRET')`. See [Configuration](/core-concept/configuration). ### Keep the OpenAPI docs in development `useOpenApi()` serves the docs whenever you call it. Gate it, as the scaffold does: ```ts if (app.isDevelopment()) { app.useOpenApi(OpenApiConfig); } ``` If you need public docs, put them behind authentication at the proxy. ### Set `NODE_ENV=production` Everything above that depends on production mode (hidden 5xx details, hidden health errors, docs off) needs `NODE_ENV` to be anything but `development`. See [Deployment](/production/deployment#environment). ### Audit dependencies ```bash npm audit --omit=dev npx megh doctor ``` `npm audit` reports known vulnerabilities. `megh doctor` checks that Node, `@meghjs/core` and the CLI versions line up. Keep Megh, Fastify and the `@fastify/*` plugins current, and run the audit in CI. --- # MeghORM Source: https://meghjs.github.io/advanced/orm `@meghjs/core` includes its own ORM. You describe tables with decorators, and column names, value types and loaded relations are checked by TypeScript. Use it through models, or as a query builder when you need SQL-level control. ```ts const users = await User.where('email', 'like', '%@acme.io') .with('posts.comments') .orderBy('name') .get(); users[0].posts[0].comments[0].body; // typed User.where('emial', 'x'); // compile error: '"emial"' is not assignable to '"id" | "email" | "name"' ``` These pages cover everything the ORM does, so you don't need another library's docs. ## Installation The ORM ships with `@meghjs/core`. Install only the driver for your database: ::: code-group ```sh [PostgreSQL] npm i pg ``` ```sh [MySQL] npm i mysql2 ``` ```sh [SQLite] npm i better-sqlite3 ``` ```sh [SQL Server] npm i tedious tarn ``` ::: ## Connecting Call `useMeghORM()` with the connection settings. Megh creates the connection and its pool, checks it when the app starts, and closes it on shutdown: ```ts [app.ts] import { Megh } from '@meghjs/core'; const app = Megh.createApplication(); app.useMeghORM({ dialect: 'postgres', url: process.env.DATABASE_URL }); ``` With no arguments, the settings come from the environment (and `.env`), which is also where the [migration commands](/advanced/orm/migrations) read them: ```sh [.env] DATABASE_URL=postgres://app:secret@localhost:5432/app ``` ```ts app.useMeghORM(); // reads DATABASE_URL ``` The URL scheme picks the database, so `dialect` is optional with a URL: | Database | URL | |---|---| | PostgreSQL | `postgres://user:pass@host:5432/db` | | MySQL / MariaDB | `mysql://user:pass@host:3306/db` | | SQL Server | `mssql://user:pass@host:1433/db` (or `sqlserver://`). Add `?encrypt=false` or `?trustServerCertificate=true` for local servers | | SQLite | `sqlite:./database.sqlite`, or `sqlite::memory:` | Instead of a URL, give the parts: ```ts app.useMeghORM({ dialect: 'mysql', host: 'localhost', port: 3306, user: 'app', password: process.env.DB_PASSWORD, database: 'app', pool: { max: 20 }, }); ``` | Option | Environment variable | | |---|---|---| | `dialect` | `DB_DIALECT` | `postgres`, `mysql`, `sqlite` or `mssql` | | `url` | `DATABASE_URL` | Connection URL | | `host`, `port` | `DB_HOST`, `DB_PORT` | | | `user`, `password` | `DB_USER`, `DB_PASSWORD` | | | `database` | `DB_NAME` | Database name; for SQLite, the file path | | `pool.min`, `pool.max` | `DB_POOL_MIN`, `DB_POOL_MAX` | Pool size. `max` defaults to 10 | | `ssl` | | `true` or driver TLS options (Postgres, MySQL). SQL Server encrypts unless `false` | | `trustServerCertificate` | | SQL Server: accept a self-signed certificate | | `naming` | | `"preserve"` (default) or `"snake_case"`. See [Column names](/advanced/orm/models#column-names) | Settings passed to `useMeghORM()` override the environment. To build them in an `@AppConfig` class ([example](/advanced/database#using-a-config-class)), pass the class: ```ts @AppConfig class DatabaseConfig extends MeghConfig { config(env: Environment): DatabaseOptions { return { url: env.get('DATABASE_URL'), pool: { max: Number(env.get('POOL')) || 10 } }; } } app.useMeghORM(DatabaseConfig); ``` If the database can't be reached, `app.run()` fails with the reason and where it tried to connect (without the password). A missing driver is reported with the `npm install` command to run. Outside an app, in scripts and tests, connect with `Model.useConnection(createDatabase(resolveDatabaseOptions({ url })))`. ::: details Upgrading from `useDatabase(kysely)` `app.useDatabase(db)` still works, with a deprecation warning, for apps that create their own Kysely instance. Replace it with `useMeghORM()` and delete `src/database/connection.ts`: the migration commands now connect from `DATABASE_URL` too. ::: ## Guides | Page | What it covers | |---|---| | [Models](/advanced/orm/models) | Decorators, keys, column names, timestamps, soft deletes, casts | | [Queries](/advanced/orm/queries) | Where clauses, aggregates, scopes, pagination, writes, transactions | | [Relations](/advanced/orm/relations) | hasMany, hasOne, belongsTo, belongsToMany, eager loading | | [Query Builder](/advanced/orm/query-builder) | `DB.table()` queries and raw SQL | | [Migrations](/advanced/orm/migrations) | The schema builder and the migration runner | | [Seeding and Factories](/advanced/orm/seeding) | Seeders, model factories and Faker | To use TypeORM or Knex instead, see [TypeORM and Knex](/advanced/database). ## Testing The ORM is tested against SQLite. The MySQL path for reading back inserted rows, which has no `RETURNING`, is implemented but not yet covered by tests. --- # Models Source: https://meghjs.github.io/advanced/orm/models A model is a class that describes one table. Its decorators give the columns, keys and value conversions, and TypeScript checks every query against them. ## Defining models Extend `Model` and describe the table with decorators: ```ts [src/models/user.model.ts] import { Model, Table, PrimaryKey, AutoIncrement, Column, CreatedAt, UpdatedAt, HasMany, } from '@meghjs/core'; import { Post } from './post.model'; @Table('users') export class User extends Model { @PrimaryKey() @AutoIncrement() id?: number; @Column({ unique: true }) email!: string; @Column({ nullable: true }) name!: string | null; @Column() active!: boolean; @CreatedAt() created_at?: Date; @UpdatedAt() updated_at?: Date; @HasMany(() => Post) posts?: Post[]; get displayName() { return this.name ?? this.email; } greet() { return `Hi ${this.displayName}`; } } ``` Query results are instances of the model, so methods and getters work on them. **Optional fields.** Declare columns the database fills in with `?`: the auto-increment `id`, timestamps, columns with a default. They're optional in `create()`, and present on every row you load, so `user.id` is a `number` on query results. **Fields that aren't columns.** Only decorated fields are saved. For TypeScript to leave a field out of `where()` and `create()` too, make it `private`, `readonly` or a getter. ### Decorators | Decorator | | |---|---| | `@Table(name?)` | The table. Without a name, the plural snake_case class name: `BlogPost` → `blog_posts` | | `@Column(options?)` | A column. Also `@Column('text')` or `@Column('text', options)` | | `@PrimaryKey(options?)` | The primary key. Defaults to `id` when no field has it | | `@AutoIncrement()` | A column the database numbers: `SERIAL`/`IDENTITY` on PostgreSQL, `AUTO_INCREMENT` on MySQL, `IDENTITY(1,1)` on SQL Server, `AUTOINCREMENT` on SQLite. Left out of inserts | | `@Identity()` | Same as `@AutoIncrement()` | | `@CreatedAt()` | Set when the row is inserted. See [Timestamps](#timestamps) | | `@UpdatedAt()` | Set on every insert and update | | `@DeletedAt()` | Turns on [soft deletes](#soft-deletes) | | `@HasMany`, `@HasOne`, `@BelongsTo`, `@BelongsToMany` | [Relations](/advanced/orm/relations) | Column options: | Option | | |---|---| | `name` | The column's name, when it differs from the property. See [Column names](#column-names) | | `type` | `string`, `text`, `integer`, `bigint`, `float`, `double`, `decimal`, `boolean`, `date`, `datetime`, `timestamp`, `time`, `json`, `uuid`, `binary`. `boolean` and `Date` fields are detected from the TypeScript type | | `nullable` | Allows `NULL` | | `unique` | | | `default` | Default value | | `length` | For `string` | | `precision`, `scale` | For `decimal` | | `cast` | How stored values convert. Defaults from `type`; see [Casts](#casts) | Decorated columns are inherited, so shared columns can live in a base class: ```ts export abstract class BaseModel extends Model { @PrimaryKey() @AutoIncrement() id?: number; @CreatedAt() created_at?: Date; @UpdatedAt() updated_at?: Date; } @Table() export class Tag extends BaseModel { @Column() name!: string; } ``` ### Column names By default a property is stored in the column with the same name. To use camelCase properties with snake_case columns, set the naming strategy once: ```ts app.useMeghORM({ naming: 'snake_case' }); @Table() class Post extends Model { @PrimaryKey() @AutoIncrement() id?: number; @Column() authorId!: number; // author_id @Column() publishedAt!: Date | null; // published_at @CreatedAt() createdAt?: Date; // created_at } ``` Or name a column explicitly, which works with either strategy: ```ts @Table('legacy_customers') class Customer extends Model { @PrimaryKey({ name: 'customer_no' }) @AutoIncrement() id?: number; @Column({ name: 'e_mail' }) email!: string; @CreatedAt({ name: 'created_on' }) createdAt?: Date; } ``` Model code then uses property names everywhere: `create()`, `where()`, `orderBy()`, `select()`, `withCount()`, `cursorPaginate({ column })`, aggregates, query results and JSON. Relation keys may be given as either the property or the column, so the defaults (`author_id`) work with an `authorId` property. Code that writes SQL itself uses column names: the [query builder](/advanced/orm/query-builder), [raw queries](/advanced/orm/query-builder#raw-queries), `where((eb) => …)` expressions and migrations. In scripts and tests without an app, call `setNamingStrategy('snake_case')` before querying. ::: details Models without decorators Models written before decorators keep working: every field is a column except relations (declared with `hasMany()` and the others), methods and getters, and settings are static fields (`static readonly table = 'users'`, `primaryKey`, `generated`, `timestamps`, `softDeletes`, `casts`). Decorators set the same settings, so the two styles can be mixed while you migrate. ::: ## Timestamps ```ts @Table() class Post extends Model { @PrimaryKey() @AutoIncrement() id?: number; @Column() title!: string; @CreatedAt() created_at?: Date; @UpdatedAt() updated_at?: Date; } ``` The `@CreatedAt` column is set on insert, and the `@UpdatedAt` column on every insert and update: `create()`, `save()`, query `update()`, and soft deletes and restores. Both are read back as `Date`. Use either one on its own, and name the fields after your columns. ## Soft deletes ```ts @Table() class Post extends Model { @PrimaryKey() @AutoIncrement() id?: number; @DeletedAt() deleted_at?: Date | null; } ``` With a `@DeletedAt` column, `delete()` sets it instead of removing the row, and every query, eager load included, leaves those rows out: ```ts await post.delete(); post.isTrashed(); // true await Post.find(post.id); // undefined await Post.withTrashed().find(post.id); // still there await Post.onlyTrashed().get(); // only deleted rows await post.restore(); await Post.onlyTrashed().where('user_id', 1).restore(); await post.forceDelete(); // really delete await Post.onlyTrashed().forceDelete(); ``` ## Casts Casts convert between what the database stores and what the model holds. A column's `type` picks its cast (`boolean`, `json`, `date`, `datetime` and `timestamp` have one), and `cast` sets it explicitly: ```ts @Table() class Member extends Model { @PrimaryKey() @AutoIncrement() id?: number; @Column() is_admin!: boolean; // boolean, from the TypeScript type @Column({ type: 'json', nullable: true }) settings!: { theme: string } | null; @Column({ type: 'date', nullable: true }) born_on!: Date | null; @Column({ type: 'decimal', cast: 'number' }) balance!: number; } ``` `boolean` and `Date` fields get their cast from the TypeScript type. A nullable field (`boolean | null`) has no single type at runtime, so give it `type`. | Cast | Read as | Written as | |---|---|---| | `'boolean'` | `true` / `false` (from `1`/`0`, `'true'`, …) | the boolean (`1`/`0` on SQLite) | | `'number'` | a number, e.g. from Postgres `numeric` / `bigint` strings | the number | | `'string'` | a string | the value | | `'json'` | the parsed value | JSON text | | `'date'` | a `Date` | `YYYY-MM-DD`, from the date's UTC parts | | `'datetime'` | a `Date` | the `Date` (ISO text on SQLite) | | `{ get, set }` | `get(stored)` | `set(value)` | ```ts const csv: CustomCast = { get: (stored) => (stored === '' ? [] : stored.split(',')), set: (tags) => tags.join(','), }; ``` Timestamp and soft-delete columns are cast as `'datetime'` automatically. `save()` notices changes made in place, such as `member.settings.theme = 'dark'`. SQLite drivers can only bind numbers, strings and buffers, so on SQLite `Date` values become ISO text and booleans become `1`/`0`, in `where()` too. ## Hiding columns from JSON `toJSON()`, and so every API response, includes a model's columns, loaded relations and counts. Keep secrets out with `hidden`: ```ts class User extends Model { static readonly table = 'users'; static readonly hidden = ['password', 'remember_token']; static readonly appends = ['full_name']; id: number; first_name: string; last_name: string; password: string; get full_name() { return `${this.first_name} ${this.last_name}`; } } JSON.stringify(user); // no password; full_name included user.password; // still readable in code ``` - `hidden` leaves properties out, in loaded relations too (`Post.with('user')` never sends the user's password). OpenAPI schemas from `modelSchema()` leave them out as well. - `visible`, when set, is the only list of columns to include. Loaded relations, counts and `appends` are still included. - `appends` adds getters. - `user.makeVisible('password')` and `user.makeHidden('email')` change one instance. ## Events Run code when an instance is created, updated, deleted or restored: ```ts User.on('creating', (user) => { user.email = user.email.toLowerCase(); }); User.on('deleted', async (user) => { await audit.log('user deleted', user.id); }); const off = Post.on('saved', (post) => cache.forget(`post:${post.id}`)); off(); // remove the handler ``` | Event | When | |---|---| | `saving` / `saved` | Every `save()` and `create()` (`saved` also when nothing changed) | | `creating` / `created` | An insert | | `updating` / `updated` | An update that changes columns | | `deleting` / `deleted` | `delete()`, soft or not, and `forceDelete()` | | `restoring` / `restored` | `restore()` | Handlers run in order and are awaited. `-ing` handlers run before the write: they can change the model, or throw to stop the write. Handlers on a base class run for its subclasses too. Query-level writes (`User.where(…).update()`, `.delete()`, `upsert()`, `insert()`, `increment()`) change many rows at once and fire no events. ## Instance helpers ```ts await user.refresh(); // reload the columns from the database const copy = await user.fresh(); // a new instance read from the database, or undefined await post.touch(); // set updated_at to now and save await post.increment('views'); // views = views + 1 in the database, and on post const draft = post.replicate(['slug']); // unsaved copy, without id, timestamps and slug await draft.fill({ slug: 'copy' }).save(); ``` ::: tip Reserved names Instance methods such as `save`, `fill`, `delete`, `refresh`, `fresh`, `touch`, `replicate`, `increment`, `decrement`, `related`, `makeVisible` and `toJSON` can't be used as column or method names on a model. Map such a column to another property with `@Column({ name })`. ::: ## Generating models `npx megh make:model user --orm` writes `src/models/user.model.ts`, with its columns read from the migrations that create and change the `users` table. (Without `--orm`, `make:model` writes a plain class.) See [CLI: Model](/cli/generators#model). --- # Queries Source: https://meghjs.github.io/advanced/orm/queries Models read and write rows through typed queries. Column names and values are checked against the model, and results are model instances. ## Querying ```ts await User.all(); await User.find(1); // User | undefined await User.findOrFail(1); // throws a 404 NotFoundException if missing await User.findBy('email', 'ann@acme.io'); // first match, or undefined await User.findBy({ email: 'ann@acme.io', active: true }); await User.findByOrFail('email', 'ann@acme.io'); // or a 404 await User.where('email', 'ann@acme.io').first(); await User.where('id', '>', 10).orderBy('name', 'desc').limit(10).offset(20).get(); await User.where('name', null).get(); // IS NULL await User.query().whereIn('id', [1, 2, 3]).get(); await User.query().whereNotNull('name').count(); await User.where('email', 'ann@acme.io').exists(); ``` `User.where()`, `User.with()`, `User.whereHas()`, `User.withCount()` and `User.scope()` start a query; `User.query()` starts an empty one. Nothing runs until `get()`, `first()`, `firstOrFail()`, `count()`, `exists()`, an aggregate, a paginate method, `update()` or `delete()` is called. ### Conditions | | | |---|---| | `where('role', 'admin')`, `where('age', '>=', 18)` | `null` becomes `IS NULL` | | `orWhere(...)` | Same forms, joined with `or` | | `whereIn`, `whereNotIn`, `orWhereIn` | A list, or a subquery ([below](#subqueries)) | | `whereNull`, `whereNotNull`, `orWhereNull`, `orWhereNotNull` | | | `whereBetween('age', [18, 65])`, `whereNotBetween` | Both ends included | | `whereColumn('updated_at', '>', 'created_at')` | Compare two columns | | `whereRaw('lower(email) = ?', [email])`, `orWhereRaw` | SQL with `?` placeholders | | `whereExists(query)`, `whereNotExists(query)` | | | `whereHas`, `orWhereHas`, `whereDoesntHave` | By relation, see [Relations](/advanced/orm/relations#querying-by-relation) | As in SQL, `and` binds tighter than `or`: `.where(a).orWhere(b).where(c)` means `a or (b and c)`. A query's own conditions are kept in one group, so an `orWhere()` never widens the soft-delete scope, a [global scope](#global-scopes) or a relation query's link to its parent: ```ts await User.where('role', 'admin').orWhere('role', 'owner').get(); // where (role = ? or role = ?) and deleted_at is null ``` Pass a callback for anything else Kysely can express: ```ts await User.where((eb) => eb.or([eb('role', '=', 'admin'), eb('id', '=', 1)])).get(); ``` `when()` applies a part of the query only when a value is set, such as an optional filter from a request: ```ts await Post.query() .when(search, (q, term) => q.where('title', 'like', `%${term}%`)) .when(authorId, (q, id) => q.where('user_id', id)) .get(); ``` ### Subqueries `whereIn()` and `whereExists()` take a model query or a [`DB.table()`](/advanced/orm/query-builder) query: ```ts const authors = DB.table('posts').select('user_id').where('views', '>', 1000); await User.query().whereIn('id', authors).get(); await User.query() .whereExists(DB.table('bans').whereColumn('bans.user_id', '=', 'users.id')) .count(); ``` ### Ordering ```ts await Post.query().orderBy('published_on', 'desc').get(); await Post.query().orderBy('published_on', 'desc', 'last').get(); // NULLs last await Post.query().latest().get(); // created_at desc await Post.query().oldest('id').get(); ``` The third argument puts NULLs `'first'` or `'last'` on every database. It is written as `case when … is null`, because MySQL and SQL Server have no `NULLS FIRST` / `NULLS LAST`. ### Selecting, grouping and joining `select()` fetches only some columns, and the result type narrows to them: ```ts const rows = await User.query().select('id', 'email').get(); rows[0].email; // string rows[0].name; // compile error ``` `selectRaw()` adds an expression, named with `as`. Type it with a generic. It appears on each result and in JSON, but `save()` never writes it: ```ts const lines = await OrderLine.query() .selectRaw<{ total: number }>('price * quantity as total') .get(); lines[0].total; // number ``` ```ts // one column, cast, of every row or of the first const emails = await User.query().orderBy('id').pluck('email'); // string[] const name = await User.where('id', 1).value('name'); // string | null | undefined // grouping: results are models holding the selected columns const totals = await Post.query() .select('user_id') .selectRaw<{ views: number }>('sum(views) as views') .groupBy('user_id') .having('user_id', '<', 100) .get(); await Post.query().select('user_id').distinct().count(); // counts the distinct rows await Post.query().distinctOn('user_id').orderBy('user_id').get(); // PostgreSQL only // rows of two queries on the same model await User.where('role', 'admin').union(User.where('score', '>', 90)).orderBy('name').get(); ``` `join()`, `leftJoin()` and `rightJoin()` filter or sort by another table. Results are still this model's rows, with only its columns. Name other tables' columns in full: ```ts await Post.query() .join('users', 'users.id', 'posts.user_id') .where('users.active', true) .orderBy('users.name') .get(); ``` A query with joins can't `update()` or `delete()`. Filter those with `whereHas()` or `whereIn()` instead. `toSQL()` returns the SQL and parameters `get()` would run. ### Aggregates ```ts await Post.count(); await Post.sum('views'); // 0 when no rows match await Post.where('user_id', 1).avg('views'); // null when no rows match await Post.min('published_on'); // casts apply: a Date here await Post.max('views'); ``` Aggregates respect filters and soft deletes, like every other query. ### Scopes A scope is a reusable piece of a query, typed for its model: ```ts import type { Scope } from '@meghjs/core'; const published: Scope = (q) => q.whereNotNull('published_on'); const byAuthor: Scope = (q, userId) => q.where('user_id', userId); await Post.scope(published).scope(byAuthor, 1).orderBy('id').get(); ``` ### Global scopes A global scope filters every query on its model: `find()`, counts, updates, and relation queries such as `with()`, `whereHas()` and `withCount()`. Declare them by name: ```ts import { Model, type ModelQuery } from '@meghjs/core'; class Post extends Model { static readonly table = 'posts'; static readonly globalScopes = { published: (q: ModelQuery) => q.whereNotNull('published_on'), tenant: (q: ModelQuery) => q.where('tenant_id', currentTenant()), }; // … } await Post.count(); // published, this tenant await Post.withoutGlobalScope('published').count(); // drafts too await Post.withoutGlobalScopes().count(); // every row await Post.query().withoutGlobalScopes(['tenant']).get(); ``` Only a scope's `where` conditions apply. They run each time a query is built, so `currentTenant()` above can read the current request. ### Pagination `paginate()` returns the same `{ data, meta }` shape as the rest of Megh: ```ts const page = await Post.query().orderBy('id').paginate({ page: 2, perPage: 20 }); // page.meta → { total, page, perPage, lastPage, next, prev } await Post.paginate({ page: 1 }); // every row ``` `simplePaginate()` skips the `count(*)` query, which is costly on large tables. It fetches one extra row to tell whether another page follows: ```ts const page = await Post.query().simplePaginate({ page: 2, perPage: 20 }); // page.meta → { page, perPage, hasMore, next, prev } ``` `cursorPaginate()` pages by key instead of by offset. Pages stay stable when rows are inserted, and deep pages are as fast as the first. Pass the returned `nextCursor` back to get the next page: ```ts const first = await Post.where('published', true).cursorPaginate({ perPage: 20 }); const next = await Post.where('published', true).cursorPaginate({ perPage: 20, cursor: first.meta.nextCursor, // null on the last page }); // meta → { perPage, hasMore, nextCursor } ``` It orders by the primary key by default; pass `column` (it must be unique) and `direction: 'desc'` to change that. An invalid cursor throws a 400 `BadRequestException`. ### Large results `get()` loads every matching row into memory. For big tables, read them a part at a time: ```ts // 500 at a time, by primary key; return false to stop await User.where('active', true).chunk(500, async (users, page) => { for (const user of users) await mailer.send(user); }); // one at a time, fetched 1000 at a time, relations included for await (const user of User.with('posts').lazy()) { // … } // rows as the database sends them for await (const user of User.query().stream()) { // … } ``` `chunk()` and `lazy()` page by primary key (`where id > last`), so they stay correct when the callback updates or deletes the rows it reads. They don't take an `orderBy()`; use `cursorPaginate()` to page in another order. `stream()` holds a connection while it runs and can't eager-load relations (use `lazy()` for that). ### Cancelling queries `abortSignal()` stops a query when its signal aborts, for example after a timeout or when the client disconnects. Eager loads under it stop too: ```ts await Report.query().abortSignal(AbortSignal.timeout(5_000)).get(); const controller = new AbortController(); await Report.query().abortSignal(controller.signal, 'cancel query').get(); ``` By default (`'ignore query'`) the query stops being waited for, but the database finishes it. `'cancel query'` also cancels it on the database (PostgreSQL, MySQL and SQL Server). ### Locking rows Inside a transaction, `lockForUpdate()` locks the selected rows until the transaction ends, so no one else can change them in between: ```ts await Model.transaction(async () => { const account = await Account.where('id', id).lockForUpdate().firstOrFail(); account.balance -= amount; await account.save(); }); // a job queue: take the next free job, skipping those other workers hold const job = await Job.where('status', 'pending') .orderBy('id') .lockForUpdate() .skipLocked() .first(); ``` `sharedLock()` (`FOR SHARE`) lets others read the rows but not change them. `noWait()` fails at once instead of waiting for a locked row. `skipLocked()` and `noWait()` need PostgreSQL or MySQL 8. On SQLite, which locks the whole database for a write, locks do nothing. SQL Server isn't supported and throws. ### Paging on SQL Server SQL Server has no `LIMIT`, so on SQL Server `limit()` becomes `select top(n)` and `offset()` becomes `offset … rows fetch next … rows only`. SQL Server only allows an offset after an `ORDER BY`, so a query with an offset but no `orderBy()` gets `order by (select null)`, and its row order is not guaranteed. Add an `orderBy()` when paging so pages stay stable. ## Creating, updating and deleting ```ts // insert and return the stored row (generated columns included) const user = await User.create({ email: 'ann@acme.io' }); // id generated, name nullable → optional // or build an instance and save it const bob = new User().fill({ email: 'bob@acme.io', name: 'Bob' }); await bob.save(); // save() updates only the columns that changed, and does nothing if none did bob.name = 'Robert'; await bob.save(); // UPDATE users SET name = ? WHERE id = ? await bob.delete(); // many rows at once; both return the number of rows affected await Post.where('user_id', 1).update({ published: true }); await Post.where('published', false).delete(); ``` `create()`'s argument is typed from the model: required columns must be present, and generated, nullable and timestamp columns may be left out. ### Finding or creating ```ts // the first match, or a new unsaved instance const user = await User.firstOrNew({ email }, { name: 'Ann' }); // the first match, or a new saved row const tag = await Tag.firstOrCreate({ slug: 'orm' }, { name: 'ORM' }); // update the first match, or create one (in a transaction) await Setting.updateOrCreate({ key: 'theme' }, { value: 'dark' }); ``` ### Many rows ```ts // one create() per row, in a transaction: events fire, rows come back const posts = await Post.createMany([{ title: 'A' }, { title: 'B' }]); // as few statements as possible: casts and timestamps, no events, no rows back await Post.insert(rows); // insert, or update the rows whose sku already exists await Price.upsert( [{ sku: 'A1', amount: 10 }, { sku: 'B2', amount: 20 }], 'sku', // unique column(s) to match by ['amount'], // columns to update; default: every given column but the keys ); ``` `upsert()` runs as `ON CONFLICT … DO UPDATE` on PostgreSQL and SQLite, `ON DUPLICATE KEY UPDATE` on MySQL and `MERGE` on SQL Server. The match columns need a unique index, except on SQL Server. MySQL matches on any of the table's unique indexes, whatever `uniqueBy` says. `created_at` is set on insert and kept on update. It returns the database's count of affected rows, in which MySQL counts an update as 2. ### Increments `increment()` and `decrement()` change a number in one statement (`set views = views + 1`), so concurrent requests don't overwrite each other: ```ts await Post.where('id', 1).increment('views'); await Product.where('sku', 'A1').decrement('stock', 3, { restocked: false }); await post.increment('views'); // the row and the instance ``` ## Transactions ```ts await Model.transaction(async () => { const user = await User.create({ email: 'ann@acme.io' }); await Profile.create({ user_id: user.id, bio: '' }); }); ``` Every model query inside the callback uses the transaction, even in functions it calls. The transaction commits when the callback resolves and rolls back if it throws. A nested `Model.transaction()` runs in a savepoint. If it throws, only its own work is rolled back, and the error still reaches the caller: ```ts await Model.transaction(async () => { await Order.create({ total: 10 }); try { await Model.transaction(async () => { await Invoice.create({ order_id: 1 }); throw new Error('mailer down'); }); } catch { // the invoice is gone, the order is kept } }); ``` If the outer transaction rolls back, so does everything nested inside it. --- # Relations Source: https://meghjs.github.io/advanced/orm/relations Relations connect models. Declare them with decorators, then load them with `with()`, filter by them with `whereHas()` and count them with `withCount()`. ```ts @Table() class User extends Model { @PrimaryKey() @AutoIncrement() id?: number; @HasMany(() => Post) posts?: Post[]; // posts.user_id → users.id @HasOne(() => Profile) profile?: Profile | null; // profiles.user_id → users.id } @Table() class Post extends Model { @PrimaryKey() @AutoIncrement() id?: number; @Column() user_id!: number; @BelongsTo(() => User, { foreignKey: 'user_id' }) author?: User | null; } ``` Type a relation field with the model it loads: `Post[]` for `@HasMany`, `Profile | null` for `@HasOne` and `@BelongsTo`. The field is `undefined` until the relation is loaded, so declare it with `?`. A field typed with a model, or an array of models, is a relation rather than a column: `create()` and `where()` leave it out, and `with('posts')` type-checks and returns `Post[]`. The related class is passed as a function, so models can refer to each other in any order, even from files that import each other. ::: warning Circular imports in ES module builds Keep the `| null` on `@HasOne` and `@BelongsTo` fields, or use the `HasOne` / `BelongsTo` types. A field typed with the bare model (`author?: User`) makes TypeScript's decorator metadata read `User` while its file is still loading. When two models import each other, an app compiled to ES modules then fails on startup with `ReferenceError: Cannot access 'User' before initialization`. CommonJS builds are not affected, and `Post[]` fields are always fine. ::: Each decorator also has a field type of the same name (`posts?: HasMany`, `author?: BelongsTo`), which works the same way. Many-to-many keeps its `BelongsToMany` type, because a plain `Role[]` can't carry the pivot columns or `attach()` / `detach()` ([below](#many-to-many)). Key defaults: | Relation | Foreign key default | Options | |---|---|---| | `@HasMany(() => Post)` | `_id` on the related table, e.g. `user_id` | `foreignKey`, `localKey` | | `@HasOne(() => Profile)` | same as `HasMany` | `foreignKey`, `localKey` | | `@BelongsTo(() => User)` | `_id` on this table, e.g. `author_id` | `foreignKey`, `ownerKey` | ## Eager loading Load relations with `with()`. Use dots for nested relations: ```ts const users = await User.with('posts.comments', 'profile').get(); users[0].posts; // Post[] users[0].profile; // Profile | null users[0].posts[0].author; // compile error: not loaded ``` Each relation level is one query, however many rows there are: ```sql select * from users select * from posts where user_id in (?, ?) select * from comments where post_id in (?, ?, ?) select * from profiles where user_id in (?, ?) ``` ### Constraining eager loads Pass a callback to shape a relation's query. It gets the related model's query, so `select()`, `where()`, `orderBy()`, `limit()`, `withTrashed()`, `whereHas()`, `withCount()` and nested `with()` all work: ```ts const todos = await Todo.with('user', (q) => q.select('name', 'role')).paginate(); todos.data[0].title; // every todo column todos.data[0].user?.name; // string todos.data[0].user?.password; // compile error: not selected ``` ```sql select * from todos limit ? offset ? select name, role, id from users where id in (?, ?) ``` `select()` adds the keys the loader matches rows by, here `users.id`. A `hasMany` relation keeps its foreign key the same way. `limit()` and `offset()` apply to each parent's rows, not to the total. This loads the three latest published posts of every user: ```ts await User.with('posts', (q) => q.where('published', true).orderBy('created_at', 'desc').limit(3), ).get(); ``` It runs as one query, numbering each user's posts with `row_number() over (partition by user_id order by created_at desc)`. That needs window functions: SQLite 3.25+, MySQL 8+, PostgreSQL or SQL Server. A dotted path constrains its last relation. The relations before it load in full: ```ts // Every post, each with only its approved comments. await User.with('posts.comments', (q) => q.where('approved', true)).get(); ``` To constrain several relations, pass an object: ```ts await User.with({ posts: (q) => q.select('id', 'title').orderBy('id', 'desc'), profile: (q) => q.select('avatar'), }).get(); ``` ## Querying by relation `whereHas()` keeps rows that have a related row; `whereDoesntHave()` keeps those that don't. Narrow the related rows with a callback, and follow nested relations with dots: ```ts await User.whereHas('posts').get(); await User.whereHas('posts', (q) => q.where('published', true)).get(); await User.whereHas('posts.comments', (q) => q.where('body', 'like', '%megh%')).get(); await User.whereDoesntHave('roles').delete(); await User.whereHas('posts').orWhereHas('comments').get(); // either one ``` Each one runs as an `EXISTS` subquery, so it works with `count()`, `paginate()`, `update()` and `delete()` too. Soft-deleted related rows don't count. ## Counting related rows `withCount()` adds a `_count` number to each result, without loading the rows: ```ts const users = await User.withCount('posts', 'roles').get(); users[0].posts_count; // number await User.query().withCount('posts', (q) => q.where('published', true)).get(); ``` Sums, averages, minimums, maximums and existence work the same way. Each takes a constraint as its last argument: ```ts const users = await User.query() .withSum('orders', 'total') // orders_sum_total: number | null .withAvg('orders', 'total') // orders_avg_total .withMin('orders', 'placed_at') // orders_min_placed_at, typed like the column .withMax('orders', 'placed_at') .withExists('subscription') // subscription_exists: boolean .get(); await User.query().withSum('orders', 'total', (q) => q.where('status', 'paid')).get(); ``` A sum, average, minimum or maximum is `null` when there are no related rows. Counts and aggregates appear in JSON but are never written back by `save()`. ## Creating related rows `related()` on a `hasMany`, `hasOne`, `morphMany` or `morphOne` relation creates rows with the foreign key (and type) already set. On a `belongsTo` it throws, since this row holds the key: ```ts const post = await user.related('posts').create({ title: 'Hello' }); // user_id set await user.related('posts').createMany([{ title: 'A' }, { title: 'B' }]); await user.related('posts').save(existingPost); // moves it to this user await user.related('posts').query().where('published', true).get(); const profile = await user.related('profile').get(); // Profile | null ``` `related('posts').query()` keeps its link to the user apart from your conditions, so an `orWhere()` there can't reach other users' posts. ## Has many through A relation through an intermediate model. A country has many posts through its users: ```ts class Country extends Model { static readonly table = 'countries'; id: number; // countries.id → users.country_id, users.id → posts.user_id posts = hasManyThrough(() => Post, () => User); latestPost = hasOneThrough(() => Post, () => User); } const countries = await Country.with('posts', (q) => q.orderBy('id', 'desc').limit(5)).get(); await Country.whereHas('posts', (q) => q.where('published', true)).get(); await Country.query().withCount('posts').get(); ``` The keys default to `_id` on the intermediate table and `_id` on the related one. Override them with `{ firstKey, secondKey, localKey, secondLocalKey }`. Soft-deleted intermediate rows don't link anything. With decorators, use `@HasManyThrough(() => Post, () => User)` and `@HasOneThrough`. ## Polymorphic relations One table can belong to several others. Comments on both posts and videos hold the owner's key and its type: ```ts class Post extends Model { static readonly table = 'posts'; id: number; comments = morphMany(() => Comment, 'commentable'); } class Video extends Model { static readonly table = 'videos'; static readonly morphType = 'video'; // stored type; defaults to the table name id: number; comments = morphMany(() => Comment, 'commentable'); thumbnail = morphOne(() => Image, 'imageable'); } class Comment extends Model { static readonly table = 'comments'; id: number; commentable_id: number; commentable_type: string; // 'posts' or 'video' body: string; commentable = morphTo(() => [Post, Video]); // Post | Video | null } ``` ```ts await Post.with('comments').withCount('comments').get(); await Post.whereHas('comments', (q) => q.where('body', 'like', '%megh%')).get(); await post.related('comments').create({ body: 'Nice' }); // id and type set const comments = await Comment.with('commentable').get(); // one query per type if (comments[0].commentable instanceof Video) { // … } ``` The columns are `_id` and `_type`. `morphTo` loads each owner type in one query. A type that none of its targets has throws. `whereHas()` and the aggregates don't support `morphTo`. Filter on `_type` and `_id` instead. With decorators, use `@MorphMany(() => Comment, 'commentable')`, `@MorphOne` and `@MorphTo(() => [Post, Video])`. ## Many-to-many ```ts @Table() class User extends Model { @PrimaryKey() @AutoIncrement() id?: number; @BelongsToMany(() => Role, { pivotColumns: ['granted_by'] }) roles?: BelongsToMany; } ``` Type many-to-many fields with `BelongsToMany`, not `Role[]`: the second argument types each loaded role's `pivot`, and the type tells `related('roles')` to offer `attach()`, `detach()` and `sync()`. The pivot table defaults to both snake_case class names, sorted and joined: `role_user`, with the columns `user_id` and `role_id`. Override any of these with options: ```ts @BelongsToMany(() => Role, { table: 'user_roles', foreignPivotKey: 'member_id', relatedPivotKey: 'role_id', }) roles!: BelongsToMany; ``` Loaded models carry their pivot row in `pivot`, which also appears in JSON: ```ts const user = await User.with('roles').firstOrFail(); user.roles[0].pivot.granted_by; // string | null ``` Change the links through `related()`: ```ts await user.related('roles').attach([adminRole, 3], { granted_by: 'root' }); // models or keys await user.related('roles').detach(adminRole); // or detach() for all await user.related('roles').sync([1, 2]); // → { attached, detached }, in one transaction const roles = await user.related('roles').get(); ``` --- # Query Builder Source: https://meghjs.github.io/advanced/orm/query-builder For queries that don't fit a model, such as reports, bulk updates, or tables without a model, use `DB.table()`: ```ts import { DB } from '@meghjs/core'; const top = await DB.table('orders') .select('customer_id') .selectRaw('sum(total) as revenue') .where('status', 'paid') .whereBetween('created_at', [from, to]) .groupBy('customer_id') .orderBy('revenue', 'desc') .limit(10) .get(); ``` Rows are plain objects. Type them with `DB.table<{ id: number; email: string }>('users')`. Values are always sent as parameters, never written into the SQL. **Conditions** | | | |---|---| | `where('status', 'paid')`, `where('total', '>', 100)` | Operators: `=`, `!=`, `<>`, `<`, `<=`, `>`, `>=`, `like`, `not like`, `ilike`, `in`, `not in`, `is`, `is not` | | `where({ status: 'paid', currency: 'EUR' })` | Every column equal | | `where((q) => q.where('a', 1).orWhere('b', 2))` | A group in parentheses | | `orWhere(...)` | Same forms, joined with `or` | | `whereIn`, `whereNotIn`, `orWhereIn` | A list, or a subquery: `whereIn('id', DB.table('bans').select('user_id'))`. An empty list matches nothing (`whereIn`) or everything (`whereNotIn`) | | `whereExists(query)`, `whereNotExists(query)` | `whereExists(DB.table('bans').whereColumn('bans.user_id', '=', 'users.id'))` | | `whereNull`, `whereNotNull`, `orWhereNull`, `orWhereNotNull` | | | `whereBetween`, `whereNotBetween` | `whereBetween('age', [18, 65])` | | `whereColumn('updated_at', '>', 'created_at')` | Compare two columns | | `whereRaw('lower(email) = ?', [email])`, `orWhereRaw` | SQL with `?` placeholders | | `when(value, (q, value) => …, otherwise?)` | Apply a part of the query only when `value` is set | `where('x', null)` becomes `x is null`. As in SQL, `and` binds tighter than `or`: `.where(a).orWhere(b).where(c)` means `a or (b and c)`. **Shaping the result** | | | |---|---| | `select('id', 'users.email as contact', 'orders.*')`, `selectRaw(sql, bindings?)`, `distinct()`, `distinctOn(...columns)` | Columns. All columns by default. `distinctOn` is PostgreSQL only | | `join(table, left, right)`, `join(table, left, op, right)`, `leftJoin`, `rightJoin` | `join('users', 'users.id', 'orders.user_id')` | | `orderBy(column, 'asc' \| 'desc', nulls?)`, `orderByDesc`, `orderByRaw`, `latest(column = 'created_at')`, `oldest` | `nulls`: `'first'` or `'last'`, on every database | | `union(query)`, `unionAll(query)` | Add another query's rows | | `withExpression(name, query)`, `withRecursiveExpression(name, anchor, recursive)` | Common table expressions, see **Trees and CTEs** below | | `lockForUpdate()`, `sharedLock()`, `skipLocked()`, `noWait()` | Row locks, as on [model queries](/advanced/orm/queries#locking-rows) | | `abortSignal(signal, strategy?)` | Stop when `signal` aborts, as on [model queries](/advanced/orm/queries#cancelling-queries) | | `groupBy(...columns)`, `having(column, op, value)`, `havingRaw` | | | `limit` / `take`, `offset` / `skip`, `forPage(page, perPage)` | | **Reading** | | | |---|---| | `get()` | Every row | | `first()`, `firstOrFail()` | The first row, `undefined` or a 404 `NotFoundException` | | `value(column)`, `pluck(column)` | One column of the first row, or of every row | | `exists()`, `doesntExist()` | | | `count(column?)`, `sum`, `avg`, `min`, `max` | Grouped and distinct queries count their rows | | `paginate({ page, perPage })` | `{ data, meta: { total, page, perPage, lastPage, next, prev } }` | | `chunkById(size, fn, column = 'id')` | `size` rows at a time, paged by a unique column; `fn` returns `false` to stop | | `stream(chunkSize?)` | `for await (const row of query.stream())`: rows as the database sends them | **Writing** ```ts await DB.table('tags').insert([{ name: 'ts' }, { name: 'node' }]); const id = await DB.table('tags').insertGetId({ name: 'orm' }); const updated = await DB.table('orders').where('status', 'new').update({ status: 'paid' }); // rows changed await DB.table('posts').where('id', 1).increment('views'); await DB.table('carts').where('updated_at', '<', cutoff).delete(); ``` Objects are stored as JSON. A column a row leaves out gets its database default, even in a multi-row insert. `upsert(rows, uniqueBy, update?)` inserts rows, or updates those whose `uniqueBy` columns match an existing row. It runs as `ON CONFLICT`, `ON DUPLICATE KEY UPDATE` or `MERGE`, depending on the database. See [Many rows](/advanced/orm/queries#many-rows). ```ts await DB.table('stock').upsert([{ sku: 'A1', qty: 5 }], 'sku', ['qty']); ``` **Trees and CTEs** `withRecursiveExpression()` walks trees and graphs in one query. The anchor query picks the starting rows, and the recursive one joins the expression's own name to find the next level: ```ts const subtree = await DB.table('tree') .withRecursiveExpression( 'tree', DB.table('categories').where('id', rootId), DB.table('categories') .select('categories.*') .join('tree', 'tree.id', 'categories.parent_id'), ) .get(); // as a subquery for models const ids = DB.table('tree').withRecursiveExpression('tree', anchor, recursive).select('id'); const categories = await Category.query().whereIn('id', ids).get(); ``` `withExpression(name, query)` adds a plain `with name as (…)`. On SQL Server, whose expressions recurse without the keyword, `WITH RECURSIVE` is written as `WITH`. **Raw SQL and transactions** ```ts const rows = await DB.select('select * from users where email = ?', [email]); const changed = await DB.statement('update users set active = ? where last_seen < ?', [false, cutoff]); await DB.transaction(async () => { await DB.table('accounts').where('id', from).decrement('balance', amount); await DB.table('accounts').where('id', to).increment('balance', amount); }); ``` `DB.transaction()` is the same transaction as `Model.transaction()`: model queries and `DB` queries inside it share it, and nested calls run in a savepoint. `toSQL()` on a query returns the SQL and parameters it would run, and `clone()` copies a query so you can build on it. ## Raw queries For full control, `Model.db()` returns the Kysely instance underneath (the transaction, inside `Model.transaction()`). Type it from your models with `DatabaseOf`: ```ts import { Model, type DatabaseOf } from '@meghjs/core'; type DB = DatabaseOf; const rows = await Model.db() .selectFrom('posts') .innerJoin('users', 'users.id', 'posts.user_id') .select(['posts.title', 'users.email']) .execute(); // { title: string; email: string }[] ``` The connection is also registered in the container under `ORM_CONNECTION`: ```ts import { MeghContainer, ORM_CONNECTION } from '@meghjs/core'; const db = MeghContainer.get(ORM_CONNECTION); // Kysely ``` --- # Migrations Source: https://meghjs.github.io/advanced/orm/migrations A migration is a file in `src/database/migrations` whose default export is `defineMigration({ up, down })`. Both functions receive the schema builder. `down` undoes `up`, so the migration can be rolled back. Migrations run in file-name order, so names start with a timestamp. Create one with the CLI: ```sh npx megh make:migration create_users_table ``` ```ts [src/database/migrations/20261101093000_create_users_table.ts] import { defineMigration } from '@meghjs/core'; export default defineMigration({ async up(schema) { await schema.create('users', (table) => { table.id(); table.string('email').unique(); table.string('name').nullable(); table.boolean('active').default(true); table.foreignId('team_id').constrained().cascadeOnDelete(); table.timestamps(); }); }, async down(schema) { await schema.drop('users'); }, }); ``` The same migration runs on PostgreSQL, MySQL, SQLite and SQL Server. Each column type becomes the right SQL type for the database, and statements are issued the way each one needs them. The name picks the template: - `create__table` gives a create-table migration. - `add__to_
_table` (also `remove`/`drop`/`alter`/`change`/`update`, with `to`/`from`/`in`/`on`) gives an alter-table one. - Anything else gives an empty migration. `--create
` and `--table
` choose the template explicitly. ## Tables | | | |---|---| | `schema.create(name, (table) => …)` | Create a table | | `schema.table(name, (table) => …)` | Change a table | | `schema.drop(name)` / `schema.dropIfExists(name)` | Drop a table | | `schema.rename(from, to)` | Rename a table | | `schema.hasTable(name)` / `schema.hasColumn(table, column)` | Check what exists | | `schema.raw(sql)` | Run SQL as written, for anything else | ## Columns Columns are `NOT NULL` unless marked `nullable()`. | Method | PostgreSQL | MySQL | SQLite | SQL Server | |---|---|---|---|---| | `id(name = 'id')`, `increments(name)` | `integer` identity | `int auto_increment` | `integer autoincrement` | `int identity` | | `bigIncrements(name)` | `bigint` identity | `bigint auto_increment` | `integer autoincrement` | `bigint identity` | | `string(name, length = 255)` | `varchar` | `varchar` | `varchar` | `nvarchar` | | `text(name)` | `text` | `text` | `text` | `nvarchar(max)` | | `integer(name)` | `integer` | `int` | `integer` | `int` | | `bigInteger(name)` | `bigint` | `bigint` | `integer` | `bigint` | | `float(name)` | `real` | `float` | `real` | `real` | | `double(name)` | `double precision` | `double` | `real` | `float` | | `decimal(name, precision = 8, scale = 2)` | `numeric` | `decimal` | `numeric` | `decimal` | | `boolean(name)` | `boolean` | `boolean` | `integer` | `bit` | | `date(name)` | `date` | `date` | `date` | `date` | | `datetime(name)` | `timestamp` | `datetime` | `datetime` | `datetime2` | | `timestamp(name)` | `timestamptz` | `datetime` | `datetime` | `datetimeoffset` | | `time(name)` | `time` | `time` | `time` | `time` | | `json(name)` | `jsonb` | `json` | `text` | `nvarchar(max)` | | `uuid(name)` | `uuid` | `char(36)` | `varchar(36)` | `uniqueidentifier` | | `binary(name)` | `bytea` | `blob` | `blob` | `varbinary(max)` | | `foreignId(name)` | `integer` | `int` | `integer` | `int` | | `timestamps()` | nullable `created_at` and `updated_at`, for `@CreatedAt` / `@UpdatedAt` | | | | | `softDeletes(name = 'deleted_at')` | nullable timestamp, for `@DeletedAt` | | | | `id()` is a 32-bit integer, so drivers return it as a number. `bigIncrements()` holds more rows, but PostgreSQL and MySQL drivers return 64-bit integers as strings. Modifiers, chained after a column: | | | |---|---| | `.nullable()` | Allow `NULL` | | `.unique()` | Unique index | | `.primary()` | Primary key | | `.default(value)` | Default value. Booleans, dates and objects are converted for the database | | `.useCurrent()` | Default to the current time | | `.autoIncrement()` | Numbered by the database | | `.constrained(table?, column = 'id')` | Foreign key. The table comes from the column name: `team_id` → `teams` | | `.references('teams.id')` | Foreign key to a given table and column | | `.onDelete(action)`, `.onUpdate(action)` | `'cascade'`, `'set null'`, `'restrict'`, `'no action'`, `'set default'` | | `.cascadeOnDelete()`, `.nullOnDelete()` | Shorthands. `nullOnDelete()` also makes the column nullable | ## Indexes and keys ```ts await schema.create('posts', (table) => { table.id(); table.integer('author_id'); table.string('slug'); table.unique(['author_id', 'slug']); // posts_author_id_slug_unique table.index('slug'); // posts_slug_index table.foreign('author_id').references('users.id').cascadeOnDelete(); }); ``` Indexes and keys are named `
__`, so you can drop them by their columns: `table.dropIndex(['slug'])`, `table.dropUnique([...])`, `table.dropForeign(['author_id'])`. `table.primary(['a', 'b'])` declares a primary key over several columns. ## Changing tables ```ts await schema.table('users', (table) => { table.string('phone').nullable(); table.foreignId('company_id').nullable().constrained(); table.renameColumn('name', 'full_name'); table.dropColumn('legacy'); }); ``` A column added to an existing table must be `nullable()` or have a `default()`, because rows already in the table need a value. SQLite can't add a foreign key or primary key to an existing column, or drop one. Declare them in `schema.create()`, or add the foreign key together with its new column (`foreignId(...).constrained()`), which SQLite supports. Doing otherwise throws a `SchemaError` that explains this. ::: details Migrations written against Kysely Migration files that export `up(db)` / `down(db)` functions taking the Kysely instance still run, in order with the others. New migrations use the schema builder. ::: Then run them: | Command | | |---|---| | `megh migrate` | Run pending migrations | | `megh migrate:status` | Show which have run (`--json` for JSON) | | `megh migrate:rollback` | Undo the last migration; `--step ` for more | | `megh migrate:reset` | Undo every migration | | `megh migrate:refresh` | Undo every migration, then run them all again | The commands compile `src/` with SWC, load `.env`, and connect the way `app.useMeghORM()` does: from `DATABASE_URL` or the `DB_*` variables. Settings that aren't secret can go in `package.json`, as can a different migrations folder: ```json [package.json] { "megh": { "database": { "dialect": "postgres", "pool": { "max": 2 } }, "migrations": "migrations" } } ``` A project that still has `src/database/connection.ts` exporting a Kysely instance keeps using it, as does `"database": "path/to/module.ts"`. A failing migration stops the run, and the error names it. What happens to the migrations before it depends on the database: - **PostgreSQL and SQL Server** support transactional DDL, so the whole run is one transaction: a failure rolls back every migration in that run. - **MySQL and SQLite** don't, so migrations that ran before the failure stay applied. The error lists them. Executed migrations are recorded in Kysely's `kysely_migration` table, so projects already using Kysely migrations keep their history. ## Running migrations from code `Migrations` runs the same operations from code, for example in test setup or at deploy time: ```ts import { Migrations, Model } from '@meghjs/core'; // After app.useMeghORM() (or Model.useConnection()): const migrations = new Migrations(Model.db(), { folder: `${__dirname}/database/migrations` }); await migrations.latest(); // names that ran await migrations.rollback(2); await migrations.status(); // [{ name, executedAt }] ``` Pass `migrations: { name: defineMigration({ up, down }) }` instead of `folder` to define them inline, and `table` / `lockTable` to change the bookkeeping table names. A failed run throws a `MigrationError` with `migration` (the one that failed) and `completed` (those that ran before it; on PostgreSQL and SQL Server they were rolled back with it). --- # Seeding and Factories Source: https://meghjs.github.io/advanced/orm/seeding Seeders put rows in the database; factories make rows with fake values. A seeder often uses factories, and tests use factories on their own. ## Seeding Seeders fill the database with rows for development, tests and demos. Each file in `src/database/seeders/` exports `defineSeeder({ run })`, and is named after its file without `.seeder.ts`: ```ts [src/database/seeders/users.seeder.ts] import { DB, defineSeeder } from '@meghjs/core'; import { Role } from '../../models/role.model'; import { User } from '../../models/user.model'; export default defineSeeder({ async run() { const admin = await Role.findByOrFail('name', 'Admin'); await User.create({ name: 'Ann', email: 'ann@example.com', role_id: admin.id! }); await DB.table('settings').insert([{ key: 'theme', value: 'dark' }]); }, }); ``` The `database` seeder is the entry point. `call()` runs other seeders by name, in order: ```ts [src/database/seeders/database.seeder.ts] export default defineSeeder({ async run({ call }) { await call('roles', 'users'); }, }); ``` Run them with `npx megh db:seed` (see [CLI: Seeders](/cli/database#seeders)). Without a `database` seeder, every seeder runs in file-name order. A run is one transaction, which models, `DB.table()` and the `db` passed to `run()` all use, so a failing seeder saves nothing. A seeder that calls itself, directly or through others, is reported as a loop. ### Seeding from code `Seeders` runs them from code, for example in test setup: ```ts import { Model, Seeders } from '@meghjs/core'; const seeders = new Seeders(Model.db(), { folder: `${__dirname}/database/seeders` }); await seeders.run(); // the database seeder, else all; returns the names that ran await seeders.run('roles'); // one seeder ``` Pass `seeders: { roles: defineSeeder({ run }) }` instead of `folder` to define them inline, and `transaction: false` to commit each statement as it runs. A failure throws a `SeedError` whose `seeder` names the seeder that failed. ## Factories A factory builds rows of a model with fake values from [Faker](https://fakerjs.dev), for seeders and tests. Install Faker in the app (`npm install -D @faker-js/faker`), then define the factory, or generate one with [`megh make:factory user`](/cli/database#factories): ```ts [src/database/factories/user.factory.ts] import { defineFactory } from '@meghjs/core'; import { User } from '../../models/user.model'; import { RoleFactory } from './role.factory'; export const UserFactory = defineFactory(User, ({ faker, sequence }) => ({ name: faker.person.fullName(), email: `user${sequence}@${faker.internet.domainName()}`, is_active: true, role_id: RoleFactory, })); ``` The definition gets `faker` and `sequence` (1 for the first row this factory builds, then 2, 3, …). Its values are typed from the model, like `create()`'s. ```ts await UserFactory.create(); // one saved row await UserFactory.createMany(10); // ten, each with its own values await UserFactory.create({ name: 'Ann' }); // override some values const user = await UserFactory.make(); // an unsaved instance; user.save() inserts it const body = await UserFactory.raw(); // just the values, e.g. for a POST in a test ``` `state()` returns a new factory with more values applied. Keep the ones you reuse as constants: ```ts export const InactiveUser = UserFactory.state({ is_active: false }); export const Admin = UserFactory.state(({ sequence }) => ({ name: `Admin ${sequence}` })); await InactiveUser.createMany(3); ``` A value that is another factory creates a related row and uses its primary key: `role_id: RoleFactory` gives each user its own role. To share one, pass the key: `UserFactory.createMany(5, { role_id: admin.id })`. Inside a seeder, factories run in its transaction like every other query, so a failing seed saves nothing: ```ts [src/database/seeders/users.seeder.ts] export default defineSeeder({ async run() { const admin = await RoleFactory.create({ name: 'Admin' }); await UserFactory.createMany(20, { role_id: admin.id }); }, }); ``` `useFaker()` changes the Faker instance factories use, for a locale or for repeatable values: ```ts import { fakerDE } from '@faker-js/faker'; import { useFaker } from '@meghjs/core'; useFaker(fakerDE); fakerDE.seed(42); // the same values on every run ``` --- # TypeORM and Knex Source: https://meghjs.github.io/advanced/database ::: tip Built-in models `@meghjs/core` also has its own type-safe models and migrations, built on Kysely, with no extra Megh package. See [MeghORM](/advanced/orm). ::: The `@meghjs/data` package adds two database integrations: **TypeORM** for an entity/repository model, and **Knex** for a query builder. Install it with the library you use and its driver. It needs `@meghjs/core` 0.4 or later. ::: code-group ```sh [TypeORM] npm i @meghjs/data typeorm pg ``` ```sh [Knex] npm i @meghjs/data knex pg ``` ::: `@meghjs/data` is a [plugin](/advanced/plugins): once it is installed, `app.useTypeORM()` and `app.useKnex()` are available, with no import needed. Projects created with `megh new` load its types through the generated `megh-env.d.ts`. In other projects, add that file yourself and include it in `tsconfig.json`: ```ts [megh-env.d.ts] /// ``` ```json [tsconfig.json] { "include": ["megh-env.d.ts", "src/**/*"] } ``` Both methods connect before they resolve, so await them before `app.run()`. The connection is closed when the app shuts down. ## TypeORM Register the datasource on the app with `useTypeORM`. It is asynchronous, so await it before the app runs. ```ts [app.ts] import { Megh } from '@meghjs/core'; import { User } from './models/user'; import { UsersController } from './controllers/users.controller'; const app = Megh.createApplication(); export async function setup() { await app.useTypeORM({ type: 'postgres', host: 'localhost', port: 5432, username: 'postgres', password: 'postgres', database: 'myapi', entities: [User], synchronize: true, // development only }); app.useControllers([UsersController]); return app; } export default app; ``` ```ts [serve.ts] import { Environment, inject } from '@meghjs/core'; import app, { setup } from './app'; async function serve() { await setup(); const env = inject(Environment); await app.run(Number(env.get('PORT')) || 4000); } serve(); ``` ::: info The project generated by `megh new` compiles to CommonJS, where top-level `await` is not available. Wrap async setup in a function and await it from your entry point, as above. ::: ### Defining an entity ```ts [models/user.ts] import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm'; @Entity({ name: 'user' }) export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @CreateDateColumn() createdAt: Date; } ``` Generate one with the CLI: ```sh npx megh make:model user --typeorm ``` ### Injecting a repository Use `@InjectRepository` to receive a TypeORM `Repository` in any service or controller. It also has a `paginate()` method, so type it as `PaginatedRepository`: ```ts [services/user.service.ts] import { AppService } from '@meghjs/core'; import { InjectRepository, PaginatedRepository } from '@meghjs/data'; import { User } from '../models/user'; @AppService export class UserService { constructor( @InjectRepository(User) private readonly userRepository: PaginatedRepository, ) {} findAll() { return this.userRepository.find(); } page(page: number) { return this.userRepository.paginate({ page, perPage: 20 }); } findByPk(id: number) { return this.userRepository.findOneBy({ id }); } create(body: Partial) { const user = this.userRepository.create(body); return this.userRepository.save(user); } } ``` ### Using a config class Instead of an inline object, `useTypeORM` also accepts an `@AppConfig` class. This keeps credentials in one place and gives access to the environment: ::: code-group ```ts [config/database.config.ts] import { AppConfig, MeghConfig, Environment } from '@meghjs/core'; import { DataSourceOptions } from 'typeorm'; import { User } from '../models/user'; @AppConfig export class DatabaseConfig extends MeghConfig { config(env: Environment): DataSourceOptions { return { type: 'postgres', url: env.get('DATABASE_URL'), entities: [User], }; } } ``` ```ts [app.ts] import { Megh } from '@meghjs/core'; import { DatabaseConfig } from './config/database.config'; const app = Megh.createApplication(); export async function setup() { await app.useTypeORM(DatabaseConfig); return app; } export default app; ``` ::: ### Custom repositories Extend `MeghRepository` to keep queries in one class, with pagination and transactions built in. Query operators (`Like`, `ILike`, `In`, `Not`, `Between`, `LessThan`, `MoreThan`, `IsNull`, `Any`, `Raw`, `Equal`, `ArrayContains`) are exported from `@meghjs/data`. ```ts [repositories/user.repository.ts] import { MeghRepository, Repository, Like } from '@meghjs/data'; import { User } from '../models/user'; import { AuditService } from '../services/audit.service'; @Repository(User) export class UserRepository extends MeghRepository { constructor(private readonly audit: AuditService) { super(); } search(term: string, page = 1) { return this.paginate( { where: { name: Like(`%${term}%`) } }, // TypeORM find options { page, perPage: 20 }, ); } rename(id: number, name: string) { return this.transaction(async (tx) => { await tx.update({ id }, { name }); await this.audit.log('rename', id); }); } } ``` ::: warning In 0.3.0, a `@Repository` class must declare a constructor that calls `super()`, even with no dependencies. Without one, resolving it through dependency injection fails on the first query. ::: - `transaction(work)` joins a transaction that is already active instead of opening a nested one. The `tx` repository keeps your injected dependencies. - `withManager(manager)` returns a copy bound to another `EntityManager`. ## Knex Register the connection with `useKnex`, which takes a Knex config or an `@AppConfig` class just like `useTypeORM`: ```ts [app.ts] import { Megh } from '@meghjs/core'; const app = Megh.createApplication(); export async function setup() { await app.useKnex({ client: 'pg', connection: process.env.DATABASE_URL, }); return app; } export default app; ``` Call `setup()` from `serve.ts` before `app.run()`, as in the TypeORM example. Inject `KnexDB` to reach the query builder through its `client` property: ```ts [services/report.service.ts] import { AppService } from '@meghjs/core'; import { KnexDB } from '@meghjs/data'; @AppService export class ReportService { constructor(private readonly db: KnexDB) {} activeUsers() { return this.db.client('user').where({ active: true }).select('*'); } page(page: number) { return this.db.paginate(this.db.client('user').orderBy('id'), { page, perPage: 20 }); } } ``` `KnexDB` throws if it is resolved before `useKnex` has run, so always register the connection during app setup. `paginateKnex(query, { page, perPage })` does the same as `db.paginate` without injecting `KnexDB`. ## Pagination Every paginator takes `{ page, perPage }` and returns the same shape: | Source | Call | |--------|------| | `@InjectRepository` | `repo.paginate({ page, perPage })` | | `MeghRepository` | `this.paginate(findOptions, { page, perPage })` | | `KnexDB` | `db.paginate(query, { page, perPage })` | | `Collection` | `collection.paginate({ page, perPage })` | ```json { "data": [ ... ], "meta": { "total": 57, "page": 2, "perPage": 20, "lastPage": 3, "next": 3, "prev": 1 } } ``` `page` defaults to 1 and `perPage` to 10. `next` and `prev` are page numbers. They are `null` at either end. The `Paginated` and `PageRequest` types are exported. ## Without a database For prototypes and tests, `Collection` gives the same shape of API over an in-memory array — see [Controller](/core-concept/controller) for an example. ## Troubleshooting | Symptom | Fix | |---------|-----| | TypeScript: `Property 'useKnex' does not exist` (or `useTypeORM`) | Add `megh-env.d.ts` and include it in `tsconfig.json`, as shown above. Importing anything from `@meghjs/data` in your code has the same effect. | | Runtime: `app.useKnex is not a function` | List `@meghjs/data` in `package.json` dependencies, use `@meghjs/core` 0.4 or later, and start the app from the project root: plugins are found from the `package.json` in the current directory. A bundled app has no `package.json` at runtime; pass the plugin explicitly (below). | | `pg is required but not installed` | Install the driver named in `client` (or `type` for TypeORM). | | `Knex is not initialized. Call useKnex first.` | A service using `KnexDB` was created before `useKnex` finished. Await `setup()` before `app.run()`. | To register the plugin yourself, for a bundled app or to turn off discovery: ```ts import { Megh } from '@meghjs/core'; import { dataPlugin } from '@meghjs/data'; const app = Megh.createApplication({ plugins: [dataPlugin] }); ``` --- # Views Source: https://meghjs.github.io/advanced/views :::: v-pre Megh ships a template engine modelled on Laravel Blade: `{{ }}` echoes, `@if` / `@foreach` directives, layouts, includes, stacks and `` tags. Templates compile to JavaScript once and are cached, so a render is a function call. It has no dependencies. ## Setup Point the app at your views folder. It defaults to `/views`: ```ts [app.ts] import path from "path"; app.useViews({ root: path.join(process.cwd(), "views") }); app.getViews().share("appName", "My App"); // available in every view ``` | Option | Default | Meaning | | ----------- | -------------------------------------- | ----------------------------------------------------------------------------- | | `root` | `/views` | Folder holding the views | | `extension` | `.megh.html` | Template file extension | | `cache` | `false` only in `NODE_ENV=development` | `false` recompiles a file when it changes, so edits show up without a restart | | `maxDepth` | `100` | Guard against a view including itself forever | View names use dots: `layouts.app` is `views/layouts/app.megh.html`. Names that would leave the views folder (`../secret`) are rejected. `megh new myapp --mvc` sets all of this up with a layout and a home page, and `megh make:view pages.about` adds a page. See [CLI](/cli/basic#application). For completion, highlighting and validation in `.megh.html` files, see [Editor setup](#editor-setup). ## Returning a view Return `Results.View` (or the `view` shorthand) from a controller or a `mapGet` handler. It is sent as `text/html; charset=utf-8`: ```ts [controllers/home.controller.ts] import { Controller, Get, Results, view } from "@meghjs/core"; @Controller("/") export class HomeController { @Get("/") index() { return Results.View("home", { user: { name: "Ana" }, todos }); } @Get("/gone") gone() { return view("errors.404", {}, 404).header("cache-control", "no-store"); } } app.mapGet("/about", () => view("about")); ``` If a template throws, nothing has been sent yet, so the error goes through the normal error handler and the client gets a 500. ::: warning Per-request data `share()` data is global to the engine, which every request uses. Pass the current user, CSRF token and similar values to `Results.View` instead. ::: You can also render to a string anywhere, for example for an email: ```ts import { getViewEngine } from "@meghjs/core"; const html = getViewEngine().render("emails.welcome", { user }); const inline = getViewEngine().renderString("Hi {{ name }}", { name: "Ana" }); ``` ## Syntax | Syntax | Meaning | | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | `{{ expr }}` | Echo, HTML-escaped. `expr` is any JS expression | | `{!! expr !!}` | Echo raw (unescaped). Only use it on trusted HTML | | `{{-- comment --}}` | Removed at compile time, tags inside it included | | `@{{ x }}` / `@@if` | Literal `{{ x }}` / `@if` (for Vue/Alpine) | | `@if(c)` `@elseif(c)` `@else` `@endif` | Conditionals | | `@unless(c)` … `@endunless` | `if (!c)` | | `@isset(a.b.c)` … `@endisset` | True if the path exists and isn't null. Never throws. Takes `@else` / `@elseif` | | `@foreach(items as item)` / `@foreach(obj as key => value)` | Arrays, Maps, Sets, iterables and plain objects | | `loop.index` `.iteration` `.first` `.last` `.count` `.remaining` `.even` `.odd` `.depth` `.parent` | Like Blade's `$loop` | | `@for(let i = 0; i < 3; i++)` … `@endfor`, `@while(c)` … `@endwhile` | Plain JS loops | | `@break` `@continue` / `@break(cond)` | Loop control | | `@js(const x = 1)` / `@js … @endjs` | Raw JS (Blade's `@php`) | | `@json(value)` | JSON that's safe inside ` @endpush ``` ```html [views/components/alert.megh.html]
@isset(title){{ title }}@endisset {{ slot }}
``` The child renders first and fills its sections, then the layout renders and `@yield`s them. Anything the child prints outside a section is dropped, as in Blade. ## React An `@react` block holds a React component written in JSX (or TSX). Megh compiles it once, on the server, and the page gets an empty element plus a ` ``` Edits to components (Vue, React with Fast Refresh, Svelte) and CSS show up in the page without a reload, and component state is kept. Server code in `src/` still restarts the app as usual. For `.tsx` and `.jsx` entries, `@vite` also installs React Fast Refresh before the entry runs. - The dev server uses port 5173 and fails to start if it's taken, so the URL in the hot file is always right. Set `server.port` in `vite.config.mts` to use another. - The page is served by Megh, and modules come from the dev server. Vite allows cross-origin requests from `localhost` and `127.0.0.1` by default. If you open the app under another host name, set `server.cors`. - With [Inertia](/advanced/inertia), the asset version is `"hot"` while the dev server runs, so updates never force a full reload. - Pass `--no-hmr` to build with `vite build --watch` instead: the page then loads the built files, and you reload to see changes. A `vite.config` without the `megh()` plugin always works this way. `--no-vite` doesn't run Vite at all. - In production (`NODE_ENV=production`, which `megh start` sets) the hot file is ignored, so a stale one can't point pages at a dev server. ## Builds `npm run build` runs `vite build && megh build`, so a deployment ships a current `public/build`, and `@vite` loads the hashed files from the manifest. ## Options ```ts app.useVite({ buildDir: "public/build", base: "/build/" }); ``` | Option | Default | Meaning | | --- | --- | --- | | `buildDir` | `"public/build"` | Vite's `build.outDir` | | `base` | `"/build/"` | URL the build is served at: Vite's `base` | | `entry` | none | Entry used by `@vite` with no arguments | | `serve` | `true` | Serve `buildDir` at `base`. Set `false` when a CDN or proxy serves it | Keep `buildDir` and `base` in step with the `megh()` plugin options in `vite.config.mts`. ## Asset version `useVite()` hashes the manifest, so the version changes with each build. `useInertia()` uses it as the Inertia asset version unless you pass one. :::: --- # Inertia.js Source: https://meghjs.github.io/advanced/inertia :::: v-pre [Inertia.js](https://inertiajs.com) lets you build a single-page app with server-side routing. Controllers return a page component name and its props instead of JSON for an API. The official Inertia client (Vue, React or Svelte) renders the page and turns links and forms into requests that return JSON, so the browser does not reload. Megh implements the server side of the [Inertia v3 protocol](https://inertiajs.com/docs/v3/core-concepts/the-protocol). `@meghjs/core` does not depend on any frontend package. Your app installs the Inertia client and a bundler, as in any Inertia app. ## Quick start Inertia support ships in 0.8.0. Until that is released, use the `@next` CLI. It creates a working Inertia app with Vite and your choice of framework: ```sh npx @meghjs/cli@next new myapp --inertia # Vue (default) npx @meghjs/cli@next new myapp --inertia react # or svelte cd myapp npm run start:dev # also runs Vite, with hot module replacement npx megh make:page Users/Show # frontend/pages/Users/Show.vue ``` For an existing project, `npx megh add inertia [vue|react|svelte]` makes the same changes. See [`megh add`](/cli/basic#add-to-a-project). The rest of this page explains the parts. ## Project layout ``` src/ server code: controllers, services, app.ts views/app.megh.html the HTML document for first visits (a server template) frontend/ browser code, built by Vite ├── app.ts createInertiaApp() (app.tsx for React) ├── css/ └── pages/ page components: Results.Inertia('Users/Show') → pages/Users/Show.vue public/build/ Vite's output (generated, not committed) ``` `views/` holds only `.megh.html` templates and `frontend/` only browser code. The [Vite](/advanced/vite) page covers `frontend/` and the build. ## Setup ```ts [app.ts] app.useSession(); // validation errors and flash messages; SESSION_SECRET in .env app.useViews(); // views/app.megh.html app.useVite(); // serves public/build and provides @vite app.useInertia(); app.shareInertia("appName", "My App"); ``` | Option | Default | Meaning | | ---------- | ------- | --------------------------------------------------------------------------------- | | `rootView` | `"app"` | View holding the HTML document for first visits | | `rootId` | `"app"` | `id` of the element the client mounts on. Must match `id` in `createInertiaApp()` | | `version` | the Vite build's version with `useVite()`, else `""` | Asset version, a string or a function returning one. `""` turns version checks off | The configuration belongs to the application. It is not global, so two apps in one process can use different settings. ## The root view The root view is a normal Megh view. `@vite` loads the built JavaScript and CSS, and `@inertia` prints the page data and the mount element: ```html [views/app.megh.html] @vite('frontend/app.ts') @inertia ``` `@inertia` renders: ```html
``` The JSON is escaped so that `<`, `>` and `&` cannot appear raw. A prop containing `` therefore cannot end the element early. The view also receives the page object as `page`, and `session` when sessions are on. ## Returning a page ```ts import { Results, inertia } from "@meghjs/core"; @Get("/users/:id") show(@Param("id") id: number) { return Results.Inertia("Users/Show", { user: this.users.find(id) }); } app.mapGet("/", () => inertia("Home")); // the same, shorter ``` A first visit (a normal browser request) gets the root view as HTML. A request from the Inertia client (`X-Inertia: true`) gets the same page object as JSON, with `X-Inertia: true`. Both are built from one resolved object, so the two cannot differ: ```json { "component": "Users/Show", "props": { "appName": "My App", "user": { "id": 42 }, "errors": {} }, "url": "/users/42?tab=profile", "version": "3f9a1c2e" } ``` `url` is the path and query string as the server received them. ## Props Props are merged in this order. When two have the same name, the later one wins: 1. `errors`: validation errors flashed by the previous request, `{}` if none 2. shared props from `app.shareInertia()` 3. the route's props A function prop is called only when the prop is sent: ```ts return Results.Inertia("Users/Index", { users: () => this.users.all(), stats: () => this.users.stats(), // skipped unless sent }); ``` Shared props use the same rule. A shared function is called per request with `{ method, url, headers, session }`, so it can read the current user's data: ```ts app.shareInertia("flash", ({ session }) => ({ success: session?.get("success") ?? null, })); ``` A plain shared value is the same object for every request. Do not put per-request data in one. ### Partial reloads `router.reload({ only: ["stats"] })` on the client sends `X-Inertia-Partial-Component`, `X-Inertia-Partial-Data` and/or `X-Inertia-Partial-Except`. When the component matches the current page, Megh sends only the props the client asked for, plus `errors`. The other props' functions are not called, so their database queries do not run. Names are matched against top-level prop names only (see the [support matrix](#support-matrix)). ## Forms and validation Inertia forms do not get a 422 response. The server flashes the errors to the session and redirects back. The next page then shows them in `errors`. Megh does this for you when sessions are on: ```ts @Post("/contacts") store(@Body() body: CreateContactDto, @Session() session: MeghSession) { this.contacts.create(body); session.flash("success", "Contact added."); return Results.Redirect("/contacts", 303); } ``` If `CreateContactDto` fails validation on an Inertia request, Megh flashes `{ name: "Name must be at least 2 characters." }` (the first message for each field) and answers `303` to the `Referer`. If the `Referer` is missing or points to another site, it redirects to `/`. The client's `useForm()` then shows `form.errors.name`. If the client sends an `X-Inertia-Error-Bag` header, the errors go under that name instead. Errors are flashed, so they appear on the next request only. Each visitor's errors are stored in their own session. Without `useSession()`, a validation error is a normal 400. ## Redirects A `302` after an Inertia `PUT`, `PATCH`, `DELETE` or `QUERY` request is sent as `303 See Other`, so the client follows it with a `GET`. Redirects for other clients, and after `POST`, are unchanged. ## Asset versioning With `app.useVite()`, the asset version is a hash of the Vite build manifest, so it changes with every frontend build. On an Inertia `GET` whose `X-Inertia-Version` differs from it, Megh answers `409 Conflict` with `X-Inertia-Location: `. The client then loads that URL as a full page, so open tabs pick up the new assets. Flashed session data is kept for that reload. Without Vite, or to use your own value, pass `version`: ```ts app.useInertia({ version: process.env.BUILD_ID }); app.useInertia({ version: () => readBuildId() }); // called once per request ``` The version must stay the same throughout a deployment. ## Caching Every response from an app with `useInertia()` includes `Vary: X-Inertia`, added to any `Vary` values already set. This stops caches and proxies from serving the HTML page in reply to a JSON request, or the reverse. ## Support matrix Coverage of the Inertia v3 protocol in this release: | Capability | Status | | -------------------------------------------------------- | ------------------- | | First visit HTML with page-data script and mount element | Supported | | Inertia JSON visits, `X-Inertia` and `Vary` headers | Supported | | Shared and route props, lazy function props | Supported | | Asset-version mismatch (409 reload) | Supported | | 302 → 303 after PUT / PATCH / DELETE / QUERY | Supported | | Session validation errors and error bags | Supported | | Partial reloads (`only` / `except`, top-level names) | Supported | | Partial reloads with dot paths (`auth.user`) | Not supported | | Deferred, optional, always, merge, once and scroll props | Not supported | | `X-Inertia-Reset`, history encryption / clear history | Not supported | | External (`Inertia::location`) and fragment redirects | Not supported | | Precognition | Not supported | | Server-side rendering (SSR) | Not supported | Rendering the root view on the server is not Inertia SSR. In SSR, the page component's HTML is rendered on the server, and Megh does not do this. The supported features are tested with the official `@inertiajs/vue3` client in the [`inertia-vue` sample](https://github.com/meghjs/megh/tree/main/samples/inertia-vue). ## Errors - `Results.Inertia()` without `app.useInertia()` answers 500 and logs the reason. - A missing root view answers 500, like a missing `Results.View`. - `@inertia` used outside the Inertia root view throws when the view renders. - An empty component name, non-object props or an invalid `rootId` throws right away. :::: --- # File Uploads Source: https://meghjs.github.io/advanced/file-uploads Multipart support is an optional peer dependency: ```sh npm i @fastify/multipart ``` Enable it on the app: ```ts [app.ts] app.useMultipart({ limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB per file }); ``` The options go to `@fastify/multipart`. Megh sets `attachFieldsToBody: true` (which `@UploadFile` needs) and a **10 MB** per-file limit unless you pass your own `limits`. The smaller of this limit and `FileStorage`'s `maxFileSize` (50 MB, below) wins, so raise both to accept bigger files. ## Receiving a file `@UploadFile('field')` injects one file and `@UploadFiles()` injects all of them. Save them with the injected `FileStorage`: ```ts [controllers/files.controller.ts] import { Controller, Post, UploadFile, MultipartFile, FileStorage } from '@meghjs/core'; @Controller('/files') export class FilesController { constructor(private readonly storage: FileStorage) {} @Post('/avatar') async upload(@UploadFile('file') file: MultipartFile) { return this.storage.save(file, { to: 'avatars' }); } } ``` `save` returns: ```json { "filename": "3f9c0d0e-....png", "originalFilename": "me.png", "size": 48213, "uploadPath": "/uploads/avatars/3f9c0d0e-....png", "staticPath": "/static/avatars/3f9c0d0e-....png" } ``` Both paths are relative to `baseDir`, with the prefixes `/uploads/` and `/static/`. ## Safe defaults `FileStorage` assumes uploads are untrusted: | Default | Override | |---------|----------| | Saved under `/public` | `configure({ baseDir })` | | Random UUID filename that keeps the extension | `saveAs: 'name.png'` or `preserveFilename: true` | | Never overwrites an existing file | `overwrite: true` | | Only common safe extensions (images, PDF, office, text/CSV, zip, audio/video). HTML, SVG and JS are rejected | `allowedExtensions`, such as `[...DEFAULT_ALLOWED_UPLOAD_EXTENSIONS, '.heic']` | | No MIME check | `allowedMimeTypes: ['image/*']` | | 50 MB limit, enforced while streaming | `maxFileSize` | Every path, including `to`, is confined to `baseDir`. Paths that try to escape it, through `..` or a symlink, are rejected, both when saving and when reading. ::: info In 0.3.0, a file that breaks these rules gives a 500 response, not 400 or 413. ::: ## Configuring Set the defaults once, for example in a service constructor or at startup: ```ts storage.configure({ baseDir: 'public/uploads', allowedMimeTypes: ['image/*'], maxFileSize: 5_000_000, }); ``` Override per call: ```ts await storage.save(file, { to: 'documents', saveAs: 'contract.pdf', overwrite: true, allowedExtensions: ['.pdf'], }); await storage.saveAll(files, { to: 'gallery' }); ``` ## Saving to S3 and other disks Pass `disk` to save to a [storage disk](/advanced/storage) instead, such as S3, Azure Blob Storage or Google Cloud Storage. The same checks apply: ```ts await storage.save(file, { disk: 's3', to: 'avatars' }); ``` The result then has the file's `path` on that disk and the `disk` name. See [Uploads to a disk](/advanced/storage#uploads-to-a-disk). ## Image transforms With `sharp` installed, resize or convert images as they are saved. The extension follows the output format: ```ts await storage.save(file, { to: 'avatars', transform: { resize: { width: 256, height: 256 }, format: 'webp' }, }); ``` `storage.transform({...})` returns a scoped copy of the storage with that transform applied, so concurrent requests never share transform settings. ## Serving and removing files `download`, `downloadAs`, `getUploadFile` and `remove` take paths **relative to `baseDir`**. Anything outside it is rejected, and a missing file gives 404. ```ts @Get('/:name') download(@Param('name') name: string) { return this.storage.downloadAs(`documents/${name}`, name); } ``` Download responses get a safely encoded `Content-Disposition` header. To serve the upload directory as static files, see `useStaticFiles` (requires `@fastify/static`): ```ts app.useStaticFiles({ root: path.join(process.cwd(), 'public'), prefix: '/static/' }); ``` --- # Storage Source: https://meghjs.github.io/advanced/storage `Storage` reads and writes files on named **disks**. A disk is a folder on the server or a bucket in the cloud. Every disk has the same methods, so code written against the local disk works on S3, Azure or Google Cloud Storage unchanged. | Driver | Stores files in | Needs | | --- | --- | --- | | `local` | A folder on the server | Nothing | | `s3` | Amazon S3, or an S3-compatible service | `@aws-sdk/client-s3`, `@aws-sdk/s3-request-presigner` | | `azure` | Azure Blob Storage | `@azure/storage-blob` | | `gcs` | Google Cloud Storage | `@google-cloud/storage` | The cloud SDKs are optional peer dependencies. Install the one you use: ```sh npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner npm i @azure/storage-blob npm i @google-cloud/storage ``` Using a disk whose SDK isn't installed throws a `StorageError` that names the package to install. ## Disks Without any setup there is one disk, `local`, rooted at `/storage`. Add disks with `app.useStorage()`: ```ts [src/app.ts] app.useStorage({ default: 'local', disks: { local: { driver: 'local', root: 'storage' }, s3: { driver: 's3', bucket: process.env.S3_BUCKET!, region: process.env.AWS_REGION, }, }, }); ``` `default` names the disk used when no name is given (`local` if left out). The `local` disk is always there unless you replace it. Bad settings, such as a missing bucket or an unknown driver, throw at startup. `useStorage()` also takes an `@AppConfig` class that returns the same object, so the settings can live in `src/config/storage.config.ts`: ```ts [src/config/storage.config.ts] import { AppConfig, Environment, MeghConfig, StorageConfig } from '@meghjs/core'; @AppConfig export class StorageSettings extends MeghConfig { config(env: Environment): StorageConfig { return { default: env.get('STORAGE_DISK') ?? 'local', disks: { s3: { driver: 's3', bucket: env.getOrThrow('S3_BUCKET'), region: env.get('AWS_REGION'), }, }, }; } } ``` ```ts [src/app.ts] app.useStorage(StorageSettings); ``` ## Using a disk Inject `Storage` and pick a disk with `disk(name?)`: ```ts [src/services/avatar.service.ts] import { AppService, Storage } from '@meghjs/core'; @AppService export class AvatarService { constructor(private readonly storage: Storage) {} async save(userId: string, image: Buffer) { const path = `avatars/${userId}.png`; await this.storage.disk('s3').put(path, image); return this.storage.disk('s3').url(path); } } ``` Or inject one disk with `@InjectDisk(name?)`. Leave the name out for the default disk: ```ts import { AppService, Disk, InjectDisk } from '@meghjs/core'; @AppService export class ReportService { constructor(@InjectDisk('s3') private readonly disk: Disk) {} publish(id: string, pdf: Buffer) { return this.disk.put(`reports/${id}.pdf`, pdf); } } ``` `Storage.disk('s3')` works outside classes too. ### Methods | Method | Does | | --- | --- | | `put(path, data, { contentType?, visibility? })` | Writes a file, replacing any file at `path`. `data` is a `Buffer`, `Uint8Array`, string or readable stream | | `get(path)` | Reads the whole file as a `Buffer` | | `getStream(path)` | Reads the file as a stream | | `exists(path)` | `true` when the file is there | | `delete(path)` | Deletes the file. A missing file is not an error | | `copy(from, to)` | Copies a file, replacing any file at `to` | | `move(from, to)` | Moves a file, replacing any file at `to` | | `size(path)` | Size in bytes | | `lastModified(path)` | A `Date` | | `list(dir?)` | Every file under `dir` (the whole disk when left out), recursively, sorted | | `url(path)` | The public URL | | `temporaryUrl(path, expiresIn)` | A URL that reads the file for `expiresIn` seconds | Reading a missing file throws `FileNotFoundException`. It extends `NotFoundException`, so a controller that lets it through answers 404. `contentType` defaults to one guessed from the extension. `visibility` is `'public'` or `'private'`; see each driver for what it does. ### Paths Paths are relative to the disk's root and use `/`. They are cleaned up the same way on every disk: a leading `/`, empty segments and `./` are dropped, and `\` becomes `/`, so `/avatars//./me.png` and `avatars\me.png` both mean `avatars/me.png`. A path with a `..` segment, a null byte, or nothing left after cleaning is refused with a `StorageError`. On the local disk, a path can't leave the root, and neither can a symlink: one that points outside the root is refused when reading, writing and listing. `list('a')` lists the folder `a`: it returns `a/1.txt` but not `ab/2.txt`. ## Local disk ```ts local: { driver: 'local', root: 'storage', // relative to the working directory url: '/storage', // for url(); optional signer: (path, expiresAt) => signedRoute(path, expiresAt), // for temporaryUrl(); optional } ``` - `url()` needs `url`. Serve the folder yourself, for example with `app.useStaticFiles({ root: path.join(process.cwd(), 'storage'), prefix: '/storage/' })`. - `temporaryUrl()` throws unless you give a `signer`: a function that returns the URL, for example a route of your app that checks a signature. - `visibility` and `contentType` are ignored. ## S3 ```ts s3: { driver: 's3', bucket: 'my-bucket', region: 'eu-west-1', credentials: { accessKeyId: '...', secretAccessKey: '...' }, // optional root: 'uploads', // a folder in the bucket; optional url: 'https://cdn.example.com', // for url(); optional visibility: 'private', // default for put(); optional options: { maxAttempts: 5 }, // extra S3Client options; optional } ``` Without `credentials`, the AWS SDK finds them the usual way: `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, a profile, or the instance's IAM role. `region` falls back to `AWS_REGION`. - `url()` is `https://.s3..amazonaws.com/`, or `url` plus the path when set. The object must be public for that URL to work. - `temporaryUrl()` is a presigned `GetObject` URL. S3 allows up to 7 days. - `visibility` is sent as an ACL (`public-read` or `private`). Buckets created since 2023 have ACLs turned off and refuse them, so only set it when your bucket uses ACLs. Without `visibility`, no ACL is sent. - Streams are uploaded in 8 MiB parts when they are bigger than one part, so memory use stays flat for large uploads. - `client` takes an `S3Client` you built yourself, in place of the connection settings. ### S3-compatible services Set `endpoint` (and `forcePathStyle` when the service wants the bucket in the path) to use any S3-compatible service: | Service | Settings | | --- | --- | | Cloudflare R2 | `endpoint: 'https://.r2.cloudflarestorage.com'`, `region: 'auto'` | | MinIO | `endpoint: 'http://localhost:9000'`, `region: 'us-east-1'`, `forcePathStyle: true` | | DigitalOcean Spaces | `endpoint: 'https://.digitaloceanspaces.com'`, `region: ''` (e.g. `nyc3`) | | Backblaze B2 | `endpoint: 'https://s3..backblazeb2.com'`, `region: ''` (e.g. `us-west-004`) | | Wasabi | `endpoint: 'https://s3..wasabisys.com'`, `region: ''` (e.g. `eu-central-1`) | ```ts r2: { driver: 's3', bucket: 'media', region: 'auto', endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`, credentials: { accessKeyId: process.env.R2_ACCESS_KEY_ID!, secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!, }, url: 'https://media.example.com', // R2 buckets have no public address of their own } ``` With an `endpoint`, `url()` is `//` when `forcePathStyle` is on, and `https://./` otherwise. Most of these services don't support ACLs, so leave `visibility` out and make the bucket public (or not) in the service's console. ## Azure Blob Storage ```ts azure: { driver: 'azure', container: 'uploads', connectionString: process.env.AZURE_STORAGE_CONNECTION_STRING, } ``` Instead of a connection string, give `accountName` with `accountKey`, or with `credential`, a token credential such as `new DefaultAzureCredential()` from `@azure/identity`. `endpoint` overrides the blob service URL (`https://.blob.core.windows.net`). For Azurite, the local emulator, use `connectionString: 'UseDevelopmentStorage=true'`. - `url()` is the blob's URL, or `url` plus the path when set. The container must allow public access for that URL to work. - `temporaryUrl()` is a read-only SAS URL. With an account key (or a connection string that has one), Megh signs it itself. With a token credential, it asks Azure for a user delegation key first, which needs the *Storage Blob Delegator* role. - `visibility` is ignored: Azure sets access on the container, not the blob. - `root` is a folder in the container. `client` takes a `ContainerClient` you built yourself. ## Google Cloud Storage ```ts gcs: { driver: 'gcs', bucket: 'my-bucket', projectId: 'my-project', // optional keyFilename: 'service-account.json', // optional } ``` Without `keyFilename` or `credentials` (`{ client_email, private_key }`), the SDK uses Application Default Credentials. `apiEndpoint` points it at an emulator. `options` holds extra `Storage` options. - `url()` is `https://storage.googleapis.com//`, or `url` plus the path when set. - `temporaryUrl()` is a v4 signed URL, which needs a service account key (or the IAM Credentials API on Cloud Run and GKE). GCS allows up to 7 days. - `visibility` is sent as a predefined ACL (`publicRead` or `private`). Buckets with uniform bucket-level access refuse it, so leave it out there. - `root` is a folder in the bucket. `client` takes a `Bucket` you built yourself. ## Uploads to a disk `FileStorage.save()` and `saveAll()` take a `disk` option, so [file uploads](/advanced/file-uploads) go to any disk with the same checks: extension and MIME allowlists, the size limit (enforced while streaming), no overwrite unless asked, and image transforms. ```ts [src/controllers/avatar.controller.ts] import { Controller, FileStorage, MultipartFile, Post, UploadFile } from '@meghjs/core'; @Controller('/avatars') export class AvatarController { constructor(private readonly files: FileStorage) {} @Post() upload(@UploadFile('avatar') file: MultipartFile) { return this.files.save(file, { disk: 's3', to: 'avatars', allowedMimeTypes: ['image/*'], transform: { resize: { width: 256, height: 256 }, format: 'webp' }, }); } } ``` The result has the file's `path` on the disk and the `disk` name, next to the fields it always had: ```json { "filename": "3f9c0d0e-....webp", "originalFilename": "me.png", "size": 9120, "path": "avatars/3f9c0d0e-....webp", "disk": "s3", "uploadPath": "/uploads/avatars/3f9c0d0e-....webp", "staticPath": "/static/avatars/3f9c0d0e-....webp" } ``` Get a URL for it with `storage.disk('s3').url(result.path)` or `temporaryUrl(result.path, 300)`. Where a save goes when it names no disk: 1. `disk` set with `fileStorage.configure({ disk })`. 2. The default disk, once `app.useStorage()` was called, unless `configure({ baseDir })` was. 3. Otherwise `baseDir` (`/public`), as before. Saving to a local disk uses the same code as `baseDir`, including the symlink checks. ## Presigned URLs `temporaryUrl(path, expiresIn)` gives a link that works for `expiresIn` seconds without making the file public. Use it to let a browser download a private file straight from the bucket: ```ts @Get('/invoices/:id') async download(@Param('id') id: string) { const url = await this.storage.disk('s3').temporaryUrl(`invoices/${id}.pdf`, 300); return Results.Redirect(url); } ``` It doesn't check that the file exists; the link answers 404 if it doesn't. ## Testing `Storage.fake(name?)` replaces a disk (the default one when no name is given) with an in-memory disk, and returns it. It behaves like a real disk and adds assertions: ```ts import { Storage } from '@meghjs/core'; afterEach(() => Storage.restore()); it('stores the avatar', async () => { const disk = Storage.fake('s3'); await avatars.save('42', png); disk.assertExists('avatars/42.png'); disk.assertExists('avatars/42.png', png); // and its content disk.assertMissing('avatars/41.png'); }); ``` | Assertion | Passes when | | --- | --- | | `assertExists(path, content?)` | A file is at `path` (with this content, when given) | | `assertMissing(path)` | No file is at `path` | | `assertCount(n, dir?)` | There are `n` files under `dir` (the whole disk when left out) | | `assertDirectoryEmpty(dir?)` | There are no files under `dir` | A failed assertion throws an error that lists the files on the disk, so it works with any test runner. `disk.files` holds the files themselves, with their content type and visibility. `Storage.restore(name?)` undoes one fake, or all of them. Disks injected with `@InjectDisk` look the disk up on every call, so a fake made after the service was built still applies. A disk taken with `storage.disk('s3')` and kept in a field does not: call `disk()` when you use it, or fake before building the service. `FileStorage` uploads go to the fake when they name the disk, or when the app called `useStorage()` and the fake replaces the default disk. --- # Messaging Source: https://meghjs.github.io/advanced/messaging Messaging carries events between processes. One part of the system publishes an event, and listeners in any replica, or any other service, handle it. The same transport layer carries [distributed events](#distributed-events), raw messages, and, on RabbitMQ, [queue jobs](/advanced/queue). Retries, dead letters, dedupe and the outbox work the same on every transport. ## Transports | Transport | Runs on | Use it for | |-----------|---------|------------| | `memory` | This process | Development and tests. The default. | | `redis` | Redis Streams | Production, when you already run Redis | | `rabbitmq` | A RabbitMQ broker | Production, when you run RabbitMQ | The Redis client (`@redis/client`) and the RabbitMQ client (`amqplib`) ship with `@meghjs/core`. There is nothing to install. The `memory` transport never leaves the process, and loses messages on restart. Use it to run the app without a broker. Kafka is not supported. ## Configuration Pick the transport with `app.useMessaging()`: ```ts [src/app.ts] import { Megh } from '@meghjs/core'; const app = Megh.createApplication(); app.useMessaging({ transport: 'redis', url: process.env.REDIS_URL, // redis:// or rediss:// }); ``` Or leave it to the environment: ```sh [.env] MEGH_MESSAGING_TRANSPORT=rabbitmq MEGH_MESSAGING_URL=amqps://user:pass@rabbit.internal ``` ```ts app.useMessaging(); // reads MEGH_MESSAGING_TRANSPORT and MEGH_MESSAGING_URL ``` Options passed to `useMessaging()` win over the environment. Without either, Megh uses `memory`. | Variable | Default | Description | |----------|---------|-------------| | `MEGH_MESSAGING_TRANSPORT` | `memory` | `memory`, `redis` or `rabbitmq` | | `MEGH_MESSAGING_URL` | | Broker URL. Required for `rabbitmq` | | `MEGH_MESSAGING_SOURCE` | `megh://` | The CloudEvents `source` of messages this app publishes | All options: | Option | Default | Description | |--------|---------|-------------| | `transport` | env, then `'memory'` | `'memory'`, `'redis'`, `'rabbitmq'`, or your own `Transport` object | | `url` | `MEGH_MESSAGING_URL` | Broker URL | | `redis` | | Redis connection and stream options, see [Redis](#redis) | | `rabbitmq` | | RabbitMQ options, see [RabbitMQ](#rabbitmq) | | `memory` | | `{ sync: true }` delivers inside `publish()`. For tests | | `source` | `MEGH_MESSAGING_SOURCE` | CloudEvents `source` | | `retry` | `{ retries: 3, backoff: 1000, maxBackoff: 60000 }` | Default retry policy for every listener | | `dedupe` | `{ window: 24h, store: 'auto' }` | Default dedupe for every listener, or `false` | | `maxPayloadBytes` | `262144` (256 KiB) | Largest encoded message | | `allowInsecure` | `false` | Allow a non-TLS URL to a remote broker in production | | `outbox` | `false` | Turn on the [transactional outbox](#outbox) | `useMessaging()` also adds a `messaging` check to `GET /ready` (see [Health Checks](/advanced/health)), and closes the transport when the app shuts down. ## Distributed events An event becomes distributed when you mark its class with `@DistributedEvent`. Dispatching it then publishes it on the transport: ```ts [src/events/order-placed.event.ts] import { DistributedEvent, MeghEvent } from '@meghjs/core'; @DistributedEvent('order.placed') export class OrderPlaced extends MeghEvent<{ orderId: number; total: number }> {} ``` ```ts await new EventDispatcher().dispatch(new OrderPlaced({ orderId: 7, total: 42 })); ``` The argument is the type on the wire. It defaults to the class name. Give it explicitly when other services consume the event, so renaming the class doesn't break them. `dispatch()` resolves once the transport has accepted the event. It does not wait for listeners. ### Listeners A listener is a class marked with `@Listener`. It is resolved through [dependency injection](/core-concept/dependency-injection), so it can inject services: ```ts [src/listeners/charge-customer.listener.ts] import { Listener, MeghEventListener } from '@meghjs/core'; import { OrderPlaced } from '../events/order-placed.event'; import { PaymentService } from '../services/payment.service'; @Listener(OrderPlaced, { group: 'billing' }) export class ChargeCustomer extends MeghEventListener { constructor(private readonly payments: PaymentService) { super(); } async handler(event: OrderPlaced) { await this.payments.charge(event.payload.orderId, event.payload.total); } } ``` Listeners start in `app.run()` and stop in `app.close()`. Importing the file is enough to register one; no `use*` call is needed. | Option | Default | Description | |--------|---------|-------------| | `group` | the class name | Consumer group, see below | | `retry` | the bus default | `{ retries?, backoff?, maxBackoff? }` for this listener | | `dedupe` | the bus default | `{ window?, store? }`, or `false` for a handler that is safe to run twice | | `concurrency` | `1` | Events this listener handles at once, per replica | The listener receives an instance of the event class, rebuilt from the message. Its constructor does not run, and the payload went through JSON, so a `Date` arrives as a string. ### Groups Every group receives each event once. Replicas in the same group share the work: each event goes to one of them. With three replicas of a billing service and two of a mail service: - `@Listener(OrderPlaced, { group: 'billing' })` runs once per order, on one billing replica. - `@Listener(OrderPlaced, { group: 'mail' })` runs once per order, on one mail replica. Give two listeners for the same event different groups. The default group is the class name, which is usually what you want. ### Local events `@Listener` works on an event without `@DistributedEvent` too. The listener then joins the in-process [event registry](/advanced/events) at `app.run()`, and `group`, `retry`, `dedupe` and `concurrency` don't apply. Listeners registered by hand with `EventRegistry.getInstance().register()` always run in the process that dispatches, distributed event or not. ### Delays `delay` publishes the event now and delivers it later: ```ts await dispatcher.dispatch(new OrderPlaced({ orderId: 7, total: 42 }), { delay: '10m' }); ``` All three transports support delays. See the [limitations](#limitations) for Redis Cluster. ## Raw messages Without event classes, publish and listen on the bus directly: ```ts import { Messaging } from '@meghjs/core'; await Messaging.publish('invoice.paid', { invoiceId: 12 }); await Messaging.publish('invoice.reminder', { invoiceId: 12 }, { delay: 86_400_000 }); const subscription = await Messaging.listen( 'invoice.paid', async (data, envelope) => { console.log(data.invoiceId, envelope.id); }, { group: 'accounting' }, ); await subscription.close(); ``` `publish()` takes `{ delay?, id?, outbox? }` and resolves to the envelope it sent. `listen()` takes the same options as `@Listener`, but `group` is required. ## The envelope Every message travels as a [CloudEvents 1.0](https://cloudevents.io) JSON envelope, so services not written with Megh can produce and consume it: ```json { "id": "5f1c…", "type": "order.placed", "source": "megh://shop-api", "time": "2026-11-28T10:00:00.000Z", "specversion": "1.0", "datacontenttype": "application/json", "traceparent": "00-…", "meghrequestid": "…", "data": { "name": "OrderPlaced", "timestamp": 1764324000000, "payload": { "orderId": 7, "total": 42 } } } ``` - `traceparent` is set when the app uses OpenTelemetry, and `meghrequestid` when the event was dispatched during a request. - A distributed event's `data` is `{ name, timestamp, payload }`. - The redis and rabbitmq transports refuse a message larger than `maxPayloadBytes` (256 KiB). Store large data elsewhere and send a reference. ## Delivery guarantees Delivery is **at least once**. A message that was published reaches every group, but a group can see it twice: a replica can crash after the handler ran and before it acknowledged the message, and the broker hands it out again. Dedupe catches most of those copies. Before a handler runs, Megh claims the message ID for the group. A second copy with the same ID is skipped, and counted in [`stats()`](#stats) as a duplicate. IDs are remembered for 24 hours by default. Where the IDs are kept: | `dedupe.store` | Shared by replicas | Needs | |----------------|--------------------|-------| | `'auto'` (default) | depends | `redis` with the redis transport, else `database` when the outbox is on, else `memory` | | `'redis'` | Yes | The redis transport | | `'database'` | Yes | Megh ORM and the [messaging tables](#the-messaging-tables) | | `'memory'` | No: one process only | | ```ts app.useMessaging({ transport: 'rabbitmq', dedupe: { store: 'database', window: 7 * 24 * 60 * 60 * 1000 }, // a week }); ``` Dedupe narrows the window for duplicates; it doesn't close it. Make handlers that move money or send mail safe to run twice, for example by checking whether the work was already done. Turn dedupe off with `dedupe: false` on a listener whose handler already is. ## Retries and dead letters A handler that throws is retried, waiting `backoff` milliseconds before the first retry and twice as long before each next one, up to `maxBackoff`. The default is 3 retries, 1, 2 and 4 seconds apart. ```ts @Listener(OrderPlaced, { group: 'billing', retry: { retries: 5, backoff: 2000 } }) ``` A message that still fails is **dead-lettered**: stored with the error, the group and the number of attempts, and logged at `error` level. The other groups are not affected. List, retry and discard dead letters from the CLI: ```sh npx megh messaging:failed # list them npx megh messaging:failed --json --limit 20 npx megh messaging:failed retry # publish it again npx megh messaging:failed retry --all npx megh messaging:failed discard # drop it for good ``` The CLI connects from `MEGH_MESSAGING_TRANSPORT` and `MEGH_MESSAGING_URL` in the environment or `.env`. With `memory` there is nothing to inspect: dead letters live inside the app process. Retrying sends the message to the one group that failed. The other groups don't see it twice. The same operations are on the bus, for an admin page or a script: ```ts const letters = await Messaging.deadLetters(50); // DeadLetter[], oldest first await Messaging.retryDeadLetter(letters[0].id); await Messaging.discardDeadLetter(letters[1].id); ``` ## Outbox Saving a row and publishing an event are two steps. A crash between them loses the event, or publishes one for a write that rolled back. The outbox closes that gap. Inside a database transaction, a distributed event is stored in the `megh_outbox` table with your data, and published after the transaction commits. If the transaction rolls back, the event goes with it. It needs [Megh ORM](/advanced/orm) and the messaging tables. Turn it on: ```ts [src/app.ts] app .useMeghORM() .useMessaging({ transport: 'redis', url: process.env.REDIS_URL, outbox: true }); ``` Then dispatch inside a transaction as usual: ```ts await Order.transaction(async () => { const order = await Order.create({ customer_id: 3, total: 42 }); await dispatcher.dispatch(new OrderPlaced({ orderId: order.id, total: 42 })); }); ``` A relay in every replica publishes what the outbox holds. Each row is claimed before it is published, so replicas don't publish it twice. A failed publish is tried again, 2 seconds later at first and at most 5 minutes apart, until the broker takes it. - Outside a transaction, events are published directly. - `outbox: true` on a dispatch or publish stores it in the outbox anyway, and `outbox: false` publishes directly inside a transaction: ```ts await dispatcher.dispatch(event, { outbox: false }); await Messaging.publish('audit.logged', data, { outbox: true }); ``` - On RabbitMQ, queue jobs added inside a transaction go through the outbox too. - `{ outbox: { pollInterval: 1000, batchSize: 100 } }` changes how often the relay looks for rows, and how many it publishes per round. - `await Messaging.flushOutbox()` publishes one batch now. For tests and scripts. With the outbox on, the default dedupe store is the database, so replicas share it. ### The messaging tables The outbox, [scheduler locks](/advanced/scheduler#multiple-replicas) and the database dedupe store use three tables: `megh_outbox`, `megh_locks` and `megh_dedupe`. Create them with a migration: ```sh npx megh make:messaging npx megh migrate ``` `make:messaging` writes: ```ts [src/database/migrations/20261128100000_create_messaging_tables.ts] import { createMessagingTables, defineMigration, dropMessagingTables } from "@meghjs/core"; export default defineMigration({ up: (schema) => createMessagingTables(schema), down: (schema) => dropMessagingTables(schema), }); ``` ## Security - **TLS in production.** With `NODE_ENV=production`, a `redis://` or `amqp://` URL to a host other than `localhost`, `127.0.0.1` or `::1` is refused at startup, whether it comes from `url`, `redis.url`, `rabbitmq.url`, a `redis.host` without `tls: true`, or the queue's `MEGH_REDIS_URL`. Use `rediss://` or `amqps://`. On a private network you trust, set `allowInsecure: true` or `MEGH_ALLOW_INSECURE_BROKER=true`. - **No memory transport for distributed listeners in production.** A `@Listener` for a distributed event fails at startup when the transport is `memory`, since other replicas would never see the events. - **Payload limit.** Messages over 256 KiB are refused, so one large event can't fill the broker. - Broker URLs are logged with their passwords removed. ## Stats `Messaging.stats()` returns counters since the process started: ```ts const { published, processed, retried, failed, duplicates } = Messaging.stats(); ``` `failed` counts dead letters; `duplicates` counts copies skipped by dedupe. Expose them on a metrics route, or log them. ## Testing `Messaging.fake()` records events, messages and jobs instead of sending them. See [Testing](/advanced/testing#events-messages-and-jobs). ## Redis Each message type is a stream, `megh:stream:`. Each group is a consumer group on it. A message a crashed consumer never acknowledged is handed to another one after `claimAfter`. Delayed messages wait in the sorted set `megh:delayed`, which every replica checks once a second. Dead letters are in the stream `megh:dlq`. ```ts app.useMessaging({ transport: 'redis', redis: { url: process.env.REDIS_URL, prefix: 'shop', // keys start with shop: instead of megh: maxStreamLength: 100_000, // messages kept per type, roughly claimAfter: 60_000, // redeliver unacknowledged messages after a minute }, }); ``` `redis` also takes `host`, `port`, `username`, `password`, `db`, `tls`, `blockFor` and `delayPollInterval`. Streams keep up to `maxStreamLength` processed messages, so you can read them again with Redis tools. ## RabbitMQ Events are published to the durable topic exchange `megh.events`, routed by type. Each group gets a durable queue, `megh..`, bound to the types it handles. Dead letters go to the queue `megh.dlq`. Delays use a queue per type and delay, `megh.delay..`, whose messages expire into the exchange. No broker plugin is needed. RabbitMQ deletes a delay queue after a minute without use. ```ts app.useMessaging({ transport: 'rabbitmq', url: process.env.RABBITMQ_URL, rabbitmq: { exchange: 'shop.events', // default megh.events prefetch: 10, // messages fetched ahead per listener heartbeat: 30, // seconds }, }); ``` Megh reconnects after a dropped connection and restores its listeners. ## Limitations - **Kafka is not supported.** - **Delays on Redis Cluster.** Delayed messages move from `megh:delayed` to their streams in one Lua script, which touches keys in different slots. That works on a single Redis server or a replicated one, but not on Redis Cluster. - **Dedupe on RabbitMQ is per process** unless you use the database store. Without the outbox, `'auto'` picks `memory`, and Megh logs a warning in production. Set `dedupe: { store: 'database' }` to share it. - **Retries wait inside the consumer.** While a message waits for its next attempt, it holds one of the listener's `concurrency` slots. A long `backoff` with many retries slows that listener down. For long waits, dead-letter early and retry with `megh messaging:failed retry`. - **Ordering.** Redis keeps the order of messages of one type, but retries and `concurrency` above 1 can still change the order handlers see. RabbitMQ guarantees no order. Don't rely on it. --- # Events Source: https://meghjs.github.io/advanced/events Events let one part of your application announce that something happened without knowing who reacts to it. Megh's event system is typed, supports synchronous, delayed and queued delivery, and can broadcast over Socket.IO. Events stay in the process that dispatches them, unless you mark them with `@DistributedEvent`. Then they travel to every replica and service over [messaging](/advanced/messaging). See [Distributed events](#distributed-events). ::: tip Generate them `npx megh make:event UserCreated` and `npx megh make:listener SendWelcomeEmail --event UserCreated` write both files. See [Generators](/cli/generators#events). ::: ## Defining an event An event extends `MeghEvent`. The payload type is yours; the base class fills in `name` and `timestamp`. ```ts [events/user-created.event.ts] import { MeghEvent } from '@meghjs/core'; export type UserCreatedPayload = { userId: number; name: string; }; export class UserCreatedEvent extends MeghEvent {} ``` ## Defining a listener A listener extends `MeghEventListener` and implements `handler`. It may be synchronous or return a promise. ```ts [listeners/user-created.listener.ts] import { MeghEventListener } from '@meghjs/core'; import { UserCreatedEvent } from '../events/user-created.event'; export class UserCreatedListener extends MeghEventListener { async handler(event: UserCreatedEvent): Promise { console.log(`User created → id=${event.payload.userId}, name=${event.payload.name}`); } } ``` ## Registering listeners The simplest way is `@Listener`. The class is resolved through dependency injection, so it can inject services, and it is registered when the app runs: ```ts [listeners/user-created.listener.ts] import { Listener, MeghEventListener } from '@meghjs/core'; import { UserCreatedEvent } from '../events/user-created.event'; import { MailService } from '../services/mail.service'; @Listener(UserCreatedEvent) export class UserCreatedListener extends MeghEventListener { constructor(private readonly mail: MailService) { super(); } async handler(event: UserCreatedEvent): Promise { await this.mail.welcome(event.payload.userId); } } ``` `@Listener` classes start in `app.run()`, so they don't run in a script that never calls it. ### By hand `EventRegistry` is a singleton. Register listeners on it once during app setup. ```ts [app.ts] import { EventRegistry } from '@meghjs/core'; import { UserCreatedEvent } from './events/user-created.event'; import { UserCreatedListener } from './listeners/user-created.listener'; const registry = EventRegistry.getInstance(); registry.register(UserCreatedEvent, new UserCreatedListener()); ``` An event may have several listeners — they run in registration order. Use `once` for a listener that should fire a single time and then be discarded: ```ts registry.once(UserCreatedEvent, { handler(event: UserCreatedEvent) { console.log(`Sending welcome email to ${event.payload.name}`); }, }); ``` ## Dispatching ```ts [services/user.service.ts] import { AppService, EventDispatcher } from '@meghjs/core'; import { UserCreatedEvent } from '../events/user-created.event'; @AppService export class UserService { private readonly dispatcher = new EventDispatcher(); async create(name: string) { const userId = 1; // ...persist the user await this.dispatcher.dispatch(new UserCreatedEvent({ userId, name })); return { userId, name }; } } ``` By default listeners run synchronously, in the current tick, before `dispatch` resolves. ### Queued delivery Pass `queue: true` to hand the event to the in-memory queue instead. Listener failures are then retried: ```ts await dispatcher.dispatch(new UserCreatedEvent({ userId: 1, name: 'Tareq' }), { queue: true, retry: 3, retryDelay: 500, // milliseconds between attempts }); ``` `retry` and `retryDelay` are only accepted together with `queue: true`. Jobs that still fail after their last retry are kept, up to 1000 of them, and logged: ```ts import { EventQueue } from '@meghjs/core'; const queue = EventQueue.getInstance(); const failed = queue.getFailedJobs(); // FailedEventJob[] queue.clearFailed(); await queue.whenIdle(); // useful in tests ``` ### Delayed delivery `delay` takes milliseconds or a duration string: `'500ms'`, `'5s'`, `'2m'`, `'1h'`, `'1d'`. It also works together with `queue: true`. ```ts await dispatcher.dispatch(new UserCreatedEvent({ userId: 1, name: 'Tareq' }), { delay: '5s', // fire listeners 5 seconds from now }); ``` ### Broadcasting Add a `broadcast` option to forward the event to Socket.IO as well as to the local listeners. Clients receive `{ name, payload }` on the channel: ```ts await dispatcher.dispatch(event, { broadcast: { type: 'socket', channel: 'user:create', room: 'admins' }, }); ``` Socket broadcast needs `app.useSocketIo()`. Without it, `dispatch` rejects and the local listeners do not run. `type: 'socket'` is the only broadcast type. Broadcasting is for browsers; to reach other servers, use a [distributed event](#distributed-events). ::: info A listener that throws is logged and does not stop the other listeners for that event. With `queue: true`, the failure is retried according to `retry`. ::: ### Listener registry - Listeners are keyed by the event **class**, so two event classes with the same name do not collide. - `once` listeners fire exactly once, even when the event is dispatched concurrently. - `registry.getListeners(UserCreatedEvent)` takes the class or an event instance. `registry.clear(UserCreatedEvent)` removes its listeners, and `registry.clear()` removes all of them. ## Distributed events Mark an event with `@DistributedEvent` and `dispatch()` publishes it on the [messaging](/advanced/messaging) transport. `@Listener` classes receive it in whichever replica or service picks it up: ```ts import { DistributedEvent, Listener, MeghEvent, MeghEventListener } from '@meghjs/core'; @DistributedEvent('user.created') export class UserCreatedEvent extends MeghEvent {} @Listener(UserCreatedEvent, { group: 'mail', retry: { retries: 5 } }) export class SendWelcomeMail extends MeghEventListener { async handler(event: UserCreatedEvent) { // runs once per event, on one replica in the "mail" group } } ``` - Every listener group receives each event once. Replicas in one group share the work. - A failing listener is retried with backoff, then dead-lettered. Delivery is at least once, with dedupe by message ID. - `delay` works as for local events. `queue`, `retry` and `retryDelay` only apply to listeners registered by hand in this process. - Inside a database transaction, with the [outbox](/advanced/messaging#outbox) on, the event is published only after the transaction commits. Pass `outbox: false` to publish at once, or `outbox: true` to store it in the outbox outside a transaction too. With no transport configured, distributed events use the in-process `memory` transport, so they work in development without a broker. See [Messaging](/advanced/messaging) for transports, groups, retries and the outbox. --- # Queue Source: https://meghjs.github.io/advanced/queue A queue runs work in the background: sending mail, building a report, calling a slow API. The request adds a job and returns; a worker runs it. There are two ways to work with jobs: a **queue class**, which both produces and consumes jobs, and a **worker class**, which only consumes a queue someone else fills. ::: tip For email you don't need your own queue: `mailer.to(user.email).queue(mail)` uses a built-in mail queue. See [Mail](/advanced/mail#queueing-mail). ::: ::: tip Generate them `npx megh make:queue OrderExport` and `npx megh make:worker Report --queue reports` write a queue or worker to fill in. See [Generators](/cli/generators#queues-and-workers). ::: ## Transports Jobs live where the transport puts them: | Transport | Jobs live in | Notes | |-----------|--------------|-------| | `memory` | This process | The default. Jobs are lost on restart | | `redis` | Redis, through BullMQ | Every feature on this page | | `rabbitmq` | RabbitMQ, through [messaging](/advanced/messaging) | No `getJob`, `getJobs`, `clean`, `pause` or `resume` | Everything is bundled with `@meghjs/core`, so there is nothing to install. Megh picks a transport in this order: 1. the `transport` option on `@Queue` or `@MeghWorker`; 2. `setQueueTransport()`; 3. the `MEGH_QUEUE_TRANSPORT` environment variable; 4. `MEGH_MESSAGING_TRANSPORT`, so queues follow [messaging](/advanced/messaging); 5. `memory`. ```sh [.env] MEGH_QUEUE_TRANSPORT=redis MEGH_REDIS_URL=rediss://default:secret@redis.internal:6379 ``` With `redis`, the connection comes from the `redis` option, then `MEGH_REDIS_URL`, then `MEGH_MESSAGING_URL` when messaging also runs on Redis, then `127.0.0.1:6379`. The `rabbitmq` transport sends jobs through the messaging bus, so configure messaging for RabbitMQ too (`MEGH_MESSAGING_TRANSPORT=rabbitmq` and `MEGH_MESSAGING_URL`, or `app.useMessaging()`). ::: warning Production With `NODE_ENV=production`, a queue refuses to start on `memory` unless you chose it: with `transport: 'memory'` on the queue, or `setQueueTransport()`. Jobs in memory vanish on restart and never reach other replicas. ::: ## A queue Extend `MeghQueue` and decorate it with `@Queue`. `T` is the shape of the job payload. ```ts [queues/email.queue.ts] import { MeghQueue, Queue, JobHandler, Job } from '@meghjs/core'; export type EmailPayload = { to: string; subject: string; }; @Queue({ name: 'email', transport: 'redis', redis: { url: process.env.REDIS_URL }, }) export class EmailQueue extends MeghQueue { constructor() { super(); } @JobHandler('welcome') async sendWelcome(job: Job) { console.log(`Sending welcome mail to ${job.data.to}`); } @JobHandler('reset-password') async sendReset(job: Job) { console.log(`Sending reset mail to ${job.data.to}`); } } ``` `transport` and `redis` are optional. Leave them out to take both from the environment. ::: warning A `@Queue` class must declare a constructor that calls `super()`. Without one, resolving it through dependency injection gives it the wrong queue name. Inject other services through the same constructor. ::: Each `@JobHandler('name')` handles jobs added under that name. For jobs added without a name — or with a name no handler matches — define a `handler` method on the class, or pass `handler` in the decorator config. `@Queue` options: | Option | Description | |--------|-------------| | `name` | Queue name. Required | | `transport` | `'memory'`, `'redis'` or `'rabbitmq'` | | `redis` | Redis connection: `{ url?, host?, port?, username?, password?, db?, tls?, prefix? }` | | `sync` | Memory only: run each job inside `add()`. For tests | | `worker` | `{ concurrency? }`, or `false` for a [producer-only queue](#producer-only-queues) | | `handler` | Processor for jobs no `@JobHandler` matches | | `defaultJobOptions` | Options applied to every job added to this queue | ### Registering `useWorker` resolves the class through the container, which is what starts its worker. Workers are closed automatically when the app shuts down. ```ts [app.ts] import { Megh } from '@meghjs/core'; import { EmailQueue } from './queues/email.queue'; const app = Megh.createApplication(); app.useWorker([EmailQueue]); export default app; ``` ### Adding jobs Inject the queue anywhere and call `add`: ```ts [services/signup.service.ts] import { AppService } from '@meghjs/core'; import { EmailQueue } from '../queues/email.queue'; @AppService export class SignupService { constructor(private readonly emailQueue: EmailQueue) {} async register(email: string) { await this.emailQueue.add('welcome', { to: email, subject: 'Welcome aboard', }); } } ``` Other producer methods: ```ts // run 30 seconds from now await emailQueue.delay('welcome', { to, subject }, 30_000); // add with job options await emailQueue.add('welcome', { to, subject }, { attempts: 3, backoff: 1000 }); // inspect and control (memory and redis) const job = await emailQueue.getJob(jobId); await emailQueue.pause(); await emailQueue.resume(); ``` ### Job options `JobOptions` is the same on every transport: | Option | Description | |--------|-------------| | `delay` | Run after this many milliseconds | | `attempts` | Total attempts, including the first. Default `1` | | `backoff` | Wait between attempts: ms, or `{ type: 'fixed' \| 'exponential', delay }` | | `jobId` | Your own ID. On Redis, adding a second job with the same ID does nothing | | `priority` | Lower runs first. Redis only | | `removeOnComplete` | Remove the job once it completes, or keep the newest N. Redis and memory | | `removeOnFail` | Remove the job once it fails, or keep the newest N. Redis and memory | A handler receives a `Job`: `id`, `name`, `data`, `queueName`, `attemptsMade`, `timestamp`, `opts`, plus `updateProgress()` and `log()`. `attemptsMade` counts the current attempt, so it is `1` on the first run. ### Producer-only queues When another process consumes the jobs, pass `worker: false`. The queue only adds jobs and never starts a worker: ```ts @Queue({ name: 'report', worker: false }) export class ReportProducer extends MeghQueue { constructor() { super(); } } ``` ## A worker When the producer lives elsewhere, extend `MeghWorkerBase` and point `@MeghWorker` at the queue name. Implement `process`; the lifecycle hooks are optional. ```ts [workers/report.worker.ts] import { MeghWorker, MeghWorkerBase, Job } from '@meghjs/core'; export type ReportPayload = { reportId: number }; @MeghWorker({ queue: 'report', concurrency: 5, transport: 'redis', redis: { url: process.env.REDIS_URL }, }) export class ReportWorker extends MeghWorkerBase { async process(job: Job) { return { generated: job.data.reportId }; } onCompleted(job: Job, result: any) { console.log(`Report ${job.data.reportId} done`, result); } onFailed(job: Job | undefined, error: Error) { console.error(`Report failed:`, error.message); } } ``` Register it the same way: ```ts app.useWorker([EmailQueue, ReportWorker]); ``` Decorating a class with `@MeghWorker` does not start it. A worker starts when it is registered with `app.useWorker([...])` or when you call `.start()` yourself. `isRunning()` tells you whether it has started. Errors thrown by `onCompleted`, `onFailed` and `onError` are caught and logged, so a faulty hook cannot crash the process. Failed jobs are always logged. ## RabbitMQ On `rabbitmq`, each queue is a message type, `job:`, with one consumer group, so replicas compete for jobs. `attempts` and `backoff` work as on Redis. A job that fails its last attempt is dead-lettered: list and retry it with [`megh messaging:failed`](/advanced/messaging#retries-and-dead-letters). RabbitMQ is a message broker, not a job store. `getJob`, `getJobs`, `clean`, `pause` and `resume` throw on this transport. ## The engine underneath `raw()` returns the engine's own queue object: BullMQ's `Queue` on Redis, the in-memory queue, or the AMQP connection on RabbitMQ. Use it for features Megh does not wrap. It is not covered by Megh's compatibility promise. `hasWorker()` tells you whether the queue's worker has started, and `transport` which transport it runs on. ## Running without Redis The `memory` transport needs no broker. Jobs run asynchronously in-process and honour `delay`. It supports `attempts`, concurrency, pause and resume, and keeps failed jobs. With `sync: true`, `add()` runs the job before it resolves and ignores `delay`. That suits tests: ```ts [signup.service.test.ts] import { setQueueTransport, waitForMemoryQueues, resetMemoryQueues } from '@meghjs/core'; beforeAll(() => setQueueTransport('memory')); afterEach(() => resetMemoryQueues()); it('sends a welcome mail', async () => { await signupService.register('a@example.com'); await waitForMemoryQueues(); // wait for queued jobs to finish expect(mailer.sent).toHaveLength(1); }); ``` `setQueueTransport('memory', { sync: true })` runs every job inline instead. `setQueueTransport(undefined)` goes back to the environment. Both apply to queues created afterwards. To check which jobs were added without running them, use [`Messaging.fake()`](/advanced/testing#events-messages-and-jobs). --- # Scheduler Source: https://meghjs.github.io/advanced/scheduler Run code on a schedule with decorators. Mark a class with `@ScheduledTask()`, then decorate its methods with `@Cron`, `@Interval` or `@Timeout`. Cron support comes from [node-cron](https://github.com/node-cron/node-cron), which is installed with `@meghjs/core`. ::: tip Generate one `npx megh make:task CleanupTokens --cron "0 3 * * *"` writes a task class to fill in. See [Generators](/cli/generators#scheduled-tasks). ::: ## A task class ```ts [src/tasks/report.task.ts] import { Cron, Interval, ScheduledTask, Timeout } from '@meghjs/core'; import { ReportService } from '../services/report.service'; import { CacheWarmer } from '../services/cache-warmer.service'; @ScheduledTask() export class ReportTask { constructor( private readonly reports: ReportService, private readonly cache: CacheWarmer, ) {} @Cron('0 8 * * 1-5', { timezone: 'Asia/Dhaka' }) // 08:00 on weekdays async sendDailyReport() { await this.reports.sendDaily(); } @Interval(60_000) // every minute async pollPending() { await this.reports.processPending(); } @Timeout(5_000) // once, 5 seconds after startup async warmCache() { await this.cache.warmUp(); } } ``` `@ScheduledTask()` takes parentheses. A class can have any number of scheduled methods, and one method can carry several decorators. ## Registering tasks Pass the classes to `useScheduler`: ```ts [src/app.ts] import { Megh } from '@meghjs/core'; import { ReportTask } from './tasks/report.task'; const app = Megh.createApplication(); app.useScheduler([ReportTask]); ``` Or scan a folder: ```ts app.useScheduler({ path: 'src/tasks' }); ``` The scan works like controller auto-discovery: - `src/tasks` is the conventional folder. - Subfolders are scanned too. Files ending in `.test`, `.spec` or `.e2e-spec` are skipped. - Every exported class marked with `@ScheduledTask()` is registered. Other exports are ignored. - In a compiled app, the tsconfig `rootDir` (default `src`) is swapped for its `outDir` (default `dist`, or `.megh/build` under `megh serve`) and `.js` files are loaded. When TypeScript runs directly (ts-node, tsx), the `.ts` files in `src` are loaded. An absolute path is used as-is. - `useScheduler({})` and `useScheduler()` scan `src/tasks`. - A missing folder logs a warning and the app starts without those tasks. A file that fails to import stops startup. A class registered in the list and found by the scan runs once, not twice. Two different classes with the same name, in different files, both run. ## Decorators | Decorator | Runs | |-----------|------| | `@Cron(expression, options?)` | On a cron expression | | `@Interval(ms, options?)` | Every `ms` milliseconds, first run after `ms` | | `@Timeout(ms, options?)` | Once, `ms` milliseconds after the scheduler starts | The expression is a 5-field cron string, or 6 fields with seconds first: ```ts @Cron('0 0 * * *') // midnight every day @Cron('*/5 * * * *') // every 5 minutes @Cron('*/10 * * * * *') // every 10 seconds ``` ### Options All three decorators take: | Option | Default | Description | |--------|---------|-------------| | `name` | `ClassName#method` | Name shown in logs. Also identifies the job between replicas | | `disabled` | `false` | Skip this job. It is logged as disabled and never runs | | `perInstance` | `false` | Run on every replica. See [Multiple replicas](#multiple-replicas). Ignored by `@Timeout` | `@Cron` also takes: | Option | Default | Description | |--------|---------|-------------| | `timezone` | server time | IANA zone, such as `'Asia/Dhaka'` or `'Europe/London'` | | `runOnInit` | `false` | Also run once when the scheduler starts | The option types are exported as `BaseJobOptions` and `CronOptions`, so you can build options outside the decorator: ```ts import type { CronOptions } from '@meghjs/core'; const nightly: CronOptions = { timezone: 'Europe/London', name: 'nightly' }; ``` `disabled` is handy for feature flags: ```ts @Cron('0 3 * * *', { disabled: process.env.NIGHTLY_CLEANUP !== 'true' }) async cleanup() { ... } ``` ## Dependency injection Task classes are resolved through [dependency injection](/core-concept/dependency-injection), so constructor parameters and `inject()` both work. Each class is built once when the scheduler starts, and that instance is shared with the rest of the app. ```ts @ScheduledTask() export class CleanupTask { private readonly sessions = inject(SessionService); @Cron('0 * * * *') async purge() { await this.sessions.deleteExpired(); } } ``` Scheduled methods are inherited. A subclass can override one by redeclaring the method with the same kind of decorator (`@Cron`, `@Interval` or `@Timeout`). ## When tasks run Tasks start inside `app.run()`, after the `onInit` hooks (so MeghORM is connected) and after routes are mapped, but before the server listens. They stop in `app.close()`, right after the HTTP server stops. See [Application](/getting-started/application) for the full order. This means: - `@Timeout(0)` and `runOnInit` jobs can run before the server accepts requests and before `onReady`. - Nothing runs if you never call `run()`, for example in tests. - `close()` stops new runs and waits for a job that is in the middle of running. On SIGTERM/SIGINT that wait counts toward `shutdownTimeout`, so very long jobs can still be cut off. - If startup fails after the tasks started (an error in `app.ready()`, the port already in use), they are stopped before `run()` rejects. An invalid cron expression throws when the scheduler starts, so `run()` fails with `Invalid cron expression "..." on ReportTask#sendDailyReport`. ## Errors and overlapping runs A job that throws or rejects is logged at `error` level and keeps its schedule. It never crashes the process. Logs go through the [logger](/advanced/logging): ``` [Megh Scheduler] Error in "ReportTask#sendDailyReport": SMTP timeout ``` If a run is still going when the next one is due, the new run is skipped with a warning. A slow `@Interval(1000)` job never runs twice at once. Handle errors you care about inside the job, for example to alert or retry. ## Multiple replicas With several replicas, a `@Cron` or `@Interval` job runs **once per tick across all of them**, not once per replica. Before a run, each replica tries to take a lock for that tick. One gets it and runs the job; the others skip it. The lock lives in the first of these that is available: 1. Redis, when [messaging](/advanced/messaging) runs on the redis transport (`app.useMessaging({ transport: 'redis' })`, or just `MEGH_MESSAGING_TRANSPORT=redis` in the environment); 2. the `megh_locks` table, when Megh ORM is connected and the table exists (`npx megh make:messaging`, then `npx megh migrate`); 3. memory, which only works within one process. In production Megh logs a warning, since every replica then runs every job. Replicas recognise the same job by its `name`, or `ClassName#method` without one. Keep it the same across replicas. For a job that should run on every replica, such as clearing a local cache, pass `perInstance: true`: ```ts @Interval(60_000, { perInstance: true }) async clearLocalCache() { this.cache.clear(); } ``` `@Timeout` jobs always run on each instance: they belong to that process's startup. The lock picks one replica per tick; it does not make the work itself safe to repeat. If a job must never run twice, for example to charge customers, also make it idempotent, or have it push work onto a [queue](/advanced/queue) with a fixed `jobId`, such as the date, via `dispatch(name, data, 0, { jobId })`. On Redis, a job whose ID already exists is ignored. See [Deployment](/production/deployment) for running replicas. ## `MeghScheduler` `useScheduler` is enough for most apps. `MeghScheduler` is the class behind it, for running tasks in a process without the HTTP app, such as a dedicated scheduler container: ```ts [src/scheduler.ts] import { MeghScheduler } from '@meghjs/core'; import { ReportTask } from './tasks/report.task'; import { CleanupTask } from './tasks/cleanup.task'; const scheduler = new MeghScheduler(); scheduler.addTaskClasses([ReportTask, CleanupTask]); scheduler.start(); const stop = async () => { await scheduler.stopAll(); // waits for runs in progress process.exit(0); }; process.once('SIGTERM', stop); process.once('SIGINT', stop); ``` | Method | Description | |--------|-------------| | `addTaskClasses(classes)` | Add task classes. Adding the same class again is ignored | | `start()` | Build each class and start its jobs. Call it once | | `stopAll()` | Stop every job. Returns a promise that resolves when runs in progress finish | | `setLockStore(store)` | Use this `LockStore` for tick locks instead of choosing one: `MemoryLockStore`, `DatabaseLockStore`, or your own `{ name, acquire(key, ttlMs, owner) }` | Outside `app.run()` there are no lifecycle hooks, so anything the tasks need, such as a database connection, must be set up before `start()`. A class without `@ScheduledTask()` is skipped with a warning. --- # Mail Source: https://meghjs.github.io/advanced/mail Megh sends email through **mailables**: one class per kind of email, holding its subject, body and attachments. The injected `Mailer` sends them through a **mailer**, which is SMTP or a provider's HTTP API. Mail can be sent straight away or queued. SMTP goes through [Nodemailer](https://nodemailer.com), an optional peer dependency: ```sh npm i nodemailer ``` The SendGrid, Mailgun, Postmark and Resend mailers call the provider's API with Node's built-in `fetch`, so they need no extra package. ## Turning mail on ```ts [src/app.ts] app.useMail(); ``` `useMail()` reads its settings from `MEGH_MAIL_*` variables in `.env`: ```ini [.env] MEGH_MAIL_MAILER=smtp MEGH_MAIL_HOST=smtp.example.com MEGH_MAIL_PORT=587 MEGH_MAIL_USERNAME=apikey MEGH_MAIL_PASSWORD=secret MEGH_MAIL_ENCRYPTION=tls MEGH_MAIL_FROM_ADDRESS=hello@example.com MEGH_MAIL_FROM_NAME="Example" ``` Anything passed to `useMail()` overrides `.env`, either as an object or as an `@AppConfig` class that returns one: ```ts app.useMail({ from: 'Shop ' }); app.useMail(MailSettings); // @AppConfig class MailSettings extends MeghConfig ``` [Setting it up](#setting-it-up) lists the steps for a new project. ### Which mailer is used `MEGH_MAIL_MAILER` (or `default` in `useMail()`) names the mailer. When it is not set: | Situation | Mailer | | --- | --- | | `MEGH_MAIL_HOST` is set | `smtp` | | `NODE_ENV=development` | `log`: messages are written to the log, not sent | | `NODE_ENV=test` | `array`: messages are kept in memory | | Otherwise (production) | none. `useMail()` throws at startup | The last row is deliberate: a production app with no mailer fails when it starts, instead of dropping mail without anyone noticing. The default mailer is also checked at startup. A missing host, API key or domain fails `useMail()` with the setting to fix, for example: ``` [Megh Mail] The default mailer "sendgrid" needs an API key: set MEGH_MAIL_SENDGRID_API_KEY or apiKey. ``` Other mailers are checked the first time they are used. ## Writing a mailable Generate one with the CLI: ```sh npx megh make:mail OrderShipped ``` ```ts [src/mail/order-shipped.mail.ts] import { Mailable } from '@meghjs/core'; import { Order } from '../models/order.model'; export class OrderShippedMail extends Mailable { constructor(private readonly order: Order) { super(); } envelope() { return { subject: `Order #${this.order.id} has shipped`, replyTo: 'support@example.com', }; } content() { return { html: `

Your order is on its way. Track it at ${this.order.trackingUrl}.

`, text: `Your order is on its way. Track it at ${this.order.trackingUrl}.`, }; } attachments() { return [{ filename: 'invoice.pdf', path: `storage/invoices/${this.order.id}.pdf` }]; } } ``` | Method | Returns | Notes | | --- | --- | --- | | `envelope()` | `{ subject?, from?, replyTo?, to?, cc?, bcc?, headers? }` | All optional. The subject defaults to the class name as words (`OrderShippedMail` → "Order Shipped Mail"). `from` overrides `MEGH_MAIL_FROM_*`. | | `content()` | `{ html?, text? }` | Required. Give `html`, `text` or both. | | `attachments()` | `MailAttachment[]` | Optional. Each is `{ filename?, content?, path?, contentType?, cid? }`. `path` is a file, a `data:` URI, or an `http(s)` URL when `allowUrlAccess` is on. See [Attachment paths](#attachment-paths). | Each method may be `async`, to load data or render a template. An address can be written as `'ann@example.com'`, `'Ann '` or `{ name: 'Ann', address: 'ann@example.com' }`. Addresses, subjects and headers that contain a line break are rejected, so user input cannot inject headers. Each address must be a single `local@domain`. Megh rejects one that contains a space, `,`, `;`, `<`, `>` or `"`, such as `'ann@example.com, evil@example.com'`, so an address taken from user input (a password reset, an invite, a contact form) can't add a second recipient. Pass several addresses as separate arguments instead: `to('ann@example.com', 'lee@example.com')`. A display name with a comma must be quoted (`'"Lee, Ann" '`) or given as an object. ### Inline images Give the attachment a `cid` and use it in the HTML: ```ts content() { return { html: ` Welcome!` }; } attachments() { return [{ filename: 'logo.png', path: 'public/logo.png', cid: 'logo' }]; } ``` ### Attachment paths An attachment's `path` is read when the message is sent. If any part of it comes from user input (`{ path: dto.file }`), a client could make the app read `/etc/passwd` or fetch `http://169.254.169.254/` (cloud metadata) and mail the result out. Megh checks every path when the message is built, for every mailer, SMTP included: | Option on `useMail()` | Default | | |---|---|---| | `allowUrlAccess` | `false` | Allow `http(s)://` paths. Other schemes are always refused. | | `allowFileAccess` | `true` | Allow local file paths. | | `attachmentRoot` | | Only read files inside this folder. Relative paths resolve against it, and symlinks can't lead out. | ```ts app.useMail({ attachmentRoot: 'storage/invoices', // invoice.pdf → storage/invoices/invoice.pdf allowUrlAccess: true, // only if every URL is yours }); ``` A refused path throws `MailError` before anything is sent. `content` (a string or `Buffer`) and `data:` URIs are always allowed, so the safest way to attach something from user input is to read it yourself and pass `content`. ## Sending Inject `Mailer` like any service: ```ts [src/services/order.service.ts] import { AppService, Mailer } from '@meghjs/core'; import { OrderShippedMail } from '../mail/order-shipped.mail'; @AppService export class OrderService { constructor(private readonly mailer: Mailer) {} async ship(order: Order) { // ... await this.mailer.to(order.customerEmail).send(new OrderShippedMail(order)); } } ``` `to()`, `cc()` and `bcc()` each take one or more addresses and can be chained: ```ts await this.mailer .to(order.customerEmail) .cc('sales@example.com') .bcc(['audit@example.com', 'archive@example.com']) .send(new OrderShippedMail(order)); ``` Recipients returned by `envelope()` are added to these. `send()` resolves to `{ mailer, message, messageId?, response? }`: the mailer used, the built message, and the provider's message ID and raw reply. To use a mailer other than the default, name it: ```ts await this.mailer.mailer('postmark').to(user.email).send(new ReceiptMail(user)); ``` ## Mailers | Mailer | Settings in `.env` | `useMail({ mailers })` options | | --- | --- | --- | | `smtp` | `MEGH_MAIL_HOST`, `MEGH_MAIL_PORT`, `MEGH_MAIL_USERNAME`, `MEGH_MAIL_PASSWORD`, `MEGH_MAIL_ENCRYPTION` | `host`, `port`, `username`, `password`, `encryption`, `options` | | `sendgrid` | `MEGH_MAIL_SENDGRID_API_KEY` | `apiKey`, `endpoint`, `timeout` | | `mailgun` | `MEGH_MAIL_MAILGUN_API_KEY`, `MEGH_MAIL_MAILGUN_DOMAIN`, `MEGH_MAIL_MAILGUN_ENDPOINT` | `apiKey`, `domain`, `endpoint`, `timeout` | | `postmark` | `MEGH_MAIL_POSTMARK_TOKEN`, `MEGH_MAIL_POSTMARK_MESSAGE_STREAM` | `token`, `messageStream`, `endpoint`, `timeout` | | `resend` | `MEGH_MAIL_RESEND_API_KEY` | `apiKey`, `endpoint`, `timeout` | | `failover` | `MEGH_MAIL_FAILOVER=sendgrid,smtp` | `mailers: string[]` | | `log` | | | | `array` | | | ### SMTP encryption | `MEGH_MAIL_ENCRYPTION` | Meaning | Usual port | | --- | --- | --- | | `ssl` | TLS from the first byte | 465 | | `tls` | STARTTLS, and refuse to send without it | 587 | | `none` | Plain, upgraded with STARTTLS when the server offers it | 25 or 1025 | Left unset, port 465 means `ssl` and any other port means `none`. Extra [Nodemailer transport options](https://nodemailer.com/smtp/) (pooling, timeouts, DKIM) go in `options`: ```ts app.useMail({ mailers: { smtp: { transport: 'smtp', options: { pool: true, maxConnections: 5 } } }, }); ``` ### Regional endpoints EU accounts use a different API host: ```ini MEGH_MAIL_MAILGUN_ENDPOINT=https://api.eu.mailgun.net ``` ```ts app.useMail({ mailers: { sendgrid: { transport: 'sendgrid', endpoint: 'https://api.eu.sendgrid.com' } }, }); ``` A mailer passed to `useMail()` is merged over the same mailer from `.env`, so this keeps `MEGH_MAIL_SENDGRID_API_KEY`. A mailer with a different `transport` replaces it instead. ### Failover A `failover` mailer tries each mailer in order until one sends. Each failure is logged as a warning: ```ini MEGH_MAIL_MAILER=failover MEGH_MAIL_FAILOVER=sendgrid,smtp ``` When every mailer fails, the error lists each reason. At startup, a failover default checks that every mailer in its list is configured, so a wrong backup key is caught before an outage. ### Your own mailer Any object with a `send(message)` method is a mailer: ```ts import { MailMessage, MailTransport } from '@meghjs/core'; class SparkPostTransport implements MailTransport { async send(message: MailMessage) { const res = await fetch('https://api.sparkpost.com/api/v1/transmissions', { method: 'POST', headers: { Authorization: process.env.SPARKPOST_KEY!, 'Content-Type': 'application/json' }, body: JSON.stringify(toSparkPost(message)), }); return { messageId: (await res.json()).results.id }; } } app.useMail({ default: 'sparkpost', mailers: { sparkpost: new SparkPostTransport() } }); ``` `message` is fully built: `from`, `to`, `cc`, `bcc` and `replyTo` as `{ name?, address }` objects, plus `subject`, `html`, `text`, `attachments` and `headers`. An optional `close()` method is called when the app shuts down. ### Errors When a provider refuses a message, `send()` throws a `MailTransportError` with `provider`, `status` (the HTTP status) and `body` (the provider's response). Mistakes in a mailable, such as no recipients, no sender or no body, throw a `MailError` that names the class. ## Queueing mail Sending inside a request makes the client wait for the mail server. Queue the mail instead, and a worker sends it in the background. Queueing uses [Megh's queue](/advanced/queue), so it runs on the queue transport: `memory` by default, `redis` or `rabbitmq` in production: ```ts [src/app.ts] app.useMail({ queue: true }); ``` ```ts await this.mailer.to(user.email).queue(new WelcomeMail(user)); await this.mailer.to(user.email).later(60_000, new ReminderMail(user)); // in a minute await this.mailer.to(user.email).later(new Date('2026-12-24T09:00:00Z'), new GreetingMail(user)); ``` `queue()` and `later()` resolve to `{ mailer, message, jobId, delay }`. The message is **built when you queue it**, and the job holds that built message. The worker only delivers it, through the mailer named when it was queued. Two consequences: - A mistake in the mailable throws from `queue()`, in your request, not later in the worker. - An attachment given by `path` is read when the mail is sent, so the file must exist where the worker runs. `Buffer` attachments travel inside the job. ### Queue options ```ts app.useMail({ queue: { name: 'mail', // the default transport: 'redis', // or 'memory' / 'rabbitmq'; defaults to MEGH_QUEUE_TRANSPORT redis: { url: process.env.REDIS_URL }, worker: { concurrency: 5 }, // or false: see below jobOptions: { attempts: 5 }, }, }); ``` `transport`, `redis` and `sync` work as for any [queue](/advanced/queue#transports). By default a job is tried 3 times, 10 then 20 seconds apart. Sent jobs are removed, since they hold email addresses. Failed jobs are kept, so you can inspect them. The worker starts as soon as `useMail({ queue })` runs, so mail queued before a restart is still sent. In a process that should only queue mail, while another process sends it, pass `worker: false`. Calling `queue()` without the `queue` option throws, instead of quietly creating a queue. ## Testing `Mailer.fake()` records mail instead of sending it, and gives you assertions. The mailable is still built, so a broken one fails the test. ```ts import { Mailer } from '@meghjs/core'; it('sends a welcome mail', async () => { const mail = Mailer.fake(); await signup.register('ann@example.com'); mail.assertSent(WelcomeMail, (sent) => sent.hasTo('ann@example.com')); mail.assertNotSent(PasswordResetMail); mail.restore(); }); ``` | Assertion | Passes when | | --- | --- | | `assertSent(Type, check?)` | A `Type` was sent with `send()` (and passed `check`) | | `assertSent(Type, n)` | A `Type` was sent exactly `n` times | | `assertNotSent(Type, check?)` | No `Type` (passing `check`) was sent | | `assertNothingSent()` | Nothing was sent | | `assertSentCount(n)` | `n` messages were sent in all | | `assertQueued(Type, check? \| n)` | A `Type` was queued with `queue()` or `later()` | | `assertNotQueued(Type, check?)` | No `Type` (passing `check`) was queued | | `assertNothingQueued()` | Nothing was queued | The `check` receives a `SentMail`: - `sent.mailable`: your instance. - `sent.message`: the built message. - `sent.delay`: for queued mail, the delay in milliseconds. - `sent.hasTo(address)`, `hasCc()`, `hasBcc()` and `hasFrom()`: compare addresses case-insensitively. `sent`, `queued`, `sentOf(Type, check?)` and `queuedOf(Type, check?)` give you the recorded mail itself. A failed assertion explains itself, and points out mail that was queued when you expected it sent, or the reverse: ``` Expected WelcomeMail to be sent, but it was not. Nothing was sent. It was queued instead; use assertQueued(). ``` ## Setting it up 1. Install the SMTP transport: `npm i nodemailer`. The API mailers don't need it. 2. Call `app.useMail()` in `src/app.ts`. 3. Generate a mailable: `npx megh make:mail Welcome`. 4. Add the mail settings to `.env`: ```ini [.env] # Mail: app.useMail(). With no MEGH_MAIL_MAILER, mail goes to the log in # development, and the app will not start in production until one is set. # MEGH_MAIL_MAILER=smtp # MEGH_MAIL_HOST=127.0.0.1 # MEGH_MAIL_PORT=1025 # MEGH_MAIL_USERNAME= # MEGH_MAIL_PASSWORD= # MEGH_MAIL_ENCRYPTION=tls # Or an API mailer: sendgrid, mailgun, postmark or resend. # MEGH_MAIL_SENDGRID_API_KEY= MEGH_MAIL_FROM_ADDRESS=hello@example.com MEGH_MAIL_FROM_NAME="Shop" ``` `npm run start:dev` then writes every mail to the console. To see real messages during development, run a local mail catcher such as [Mailpit](https://mailpit.axllent.org) and point SMTP at it: ```ini MEGH_MAIL_HOST=127.0.0.1 MEGH_MAIL_PORT=1025 ``` Mailpit's inbox is at `http://localhost:8025`. --- # Notifications Source: https://meghjs.github.io/advanced/notifications A notification is one message, such as "your invoice was paid", that goes out on one or more channels. Megh has two channels: | Channel | Delivers through | Needs | |---------|------------------|-------| | `mail` | `Mailer`, with your [mail](/advanced/mail) settings | `app.useMail()` | | `broadcast` | Socket.IO, to a room or to every client | `app.useSocketIo()` | ## Writing a notification Extend `Notification`. `via()` returns the channels; add `toMail()` and/or `toBroadcast()` for the channels it returns. ```ts import { Mailable, Notification } from '@meghjs/core'; class InvoicePaidMail extends Mailable { constructor(private readonly invoice: Invoice) { super(); } envelope() { return { subject: `Invoice ${this.invoice.number} paid` }; } content() { return { text: `We received ${this.invoice.total}. Thank you!` }; } } export class InvoicePaid extends Notification { constructor(private readonly invoice: Invoice) { super(); } via() { return ['mail', 'broadcast'] as const; } toMail() { return new InvoicePaidMail(this.invoice); } toBroadcast() { return { data: { invoiceId: this.invoice.id } }; } } ``` `via()` gets the recipient, so it can choose channels per user, for example `return user.wantsEmail ? ['mail', 'broadcast'] : ['broadcast']`. `toBroadcast()` returns `{ data, event?, room? }`. `event` defaults to `"notification"`, and clients receive `{ type: 'InvoicePaid', data }`. ## Recipients Anything with a `routeNotificationFor(channel)` method can be notified. Return an email address for `mail` and a Socket.IO room for `broadcast`: ```ts import type { Notifiable, NotificationChannel } from '@meghjs/core'; export class User implements Notifiable { id!: number; email!: string; routeNotificationFor(channel: NotificationChannel) { return channel === 'mail' ? this.email : `user.${this.id}`; } } ``` With no room (from `toBroadcast()` or `routeNotificationFor`), a broadcast goes to every connected client. ## Sending Inject `Notifier`, or use the `notifier` helper: ```ts import { Notifier } from '@meghjs/core'; @AppService export class BillingService { constructor(private readonly notifier: Notifier) {} async markPaid(invoice: Invoice, user: User) { // ... await this.notifier.send(user, new InvoicePaid(invoice)); } } ``` `send()` also takes an array, and sends to each recipient in turn. Sending throws `NotificationError` when a channel in `via()` has no matching `to*()` method, when `routeNotificationFor('mail')` returns no address, or when `broadcast` is used without `app.useSocketIo()`. ::: tip Send in the background Notifications are sent while you wait. To keep a request fast, return a mailable that is sent through the mail queue, or dispatch the notification from a [queue job](/advanced/queue). ::: ## Testing `Notifier.fake()` records notifications instead of sending them: ```ts import { Notifier } from '@meghjs/core'; afterEach(() => Notifier.restore()); it('notifies the customer', async () => { const notifications = Notifier.fake(); await billing.markPaid(invoice, user); notifications.assertSentTo(user, InvoicePaid); expect(notifications.sentTo(user, InvoicePaid)).toHaveLength(2); // mail + broadcast }); ``` | Method | Checks | |--------|--------| | `assertSentTo(user, Type)` | At least one `Type` was sent to `user` | | `assertNothingSent()` | Nothing was sent | | `sentTo(user, Type)` | Returns the recorded sends, one per channel | | `sent` | Every recorded `{ notifiable, notification, channel }` | --- # OpenAPI Source: https://meghjs.github.io/microservices/openapi Megh generates an OpenAPI document from your controllers and serves a browsable UI. Request bodies and query strings come from your DTOs, responses from `@ApiResponse()` with a DTO or MeghORM model, and the errors a route can return from what its controller declares. The UI packages are optional peer dependencies. Install the one you use: ::: code-group ```sh [Swagger UI] npm i @fastify/swagger @fastify/swagger-ui ``` ```sh [Scalar] npm i @fastify/swagger @scalar/fastify-api-reference ``` ::: ## Enabling ```sh npx megh make:config openapi ``` ::: code-group ```ts [config/openapi.config.ts] import { AppConfig, MeghConfig, Environment, OpenApiUiOptions } from '@meghjs/core'; @AppConfig export class OpenApiConfig extends MeghConfig { config(env: Environment): OpenApiUiOptions { return { info: { title: 'My API', version: '1.0.0', description: 'API documentation', }, routePrefix: '/docs', }; } } ``` ```ts [app.ts] import { Megh } from '@meghjs/core'; import { OpenApiConfig } from './config/openapi.config'; import { WelcomeController } from './controllers/welcome.controller'; const app = Megh.createApplication(); if (app.isDevelopment()) { app.useOpenApi(OpenApiConfig); } app.useControllers([WelcomeController]); export default app; ``` ::: The UI is then served at `routePrefix` — `http://localhost:4000/docs` above. `isDevelopment()` is true only when `NODE_ENV=development`. With `NODE_ENV` unset, the guard above turns the docs off. `OpenApiUiOptions` is fully typed, so your editor completes and checks every option, down to Swagger UI's settings. `useOpenApi` also accepts a plain options object if you do not need a config class: ```ts app.useOpenApi({ info: { title: 'My API', version: '1.0.0' }, routePrefix: '/docs', }); ``` ### Options | Option | Description | |--------|-------------| | `info` | Title, version and description. Defaults to `{ title: 'API', version: '1.0.0' }` | | `routePrefix` | Where the UI is served. Defaults to `/swagger`; the JSON document is at `/json` | | `provider` | `'default'` (Swagger UI) or `'scalar'` | | `auth` | Security scheme for `@Authorized` routes: `'bearer'`, `'apiKey'` or any OpenAPI security scheme. See [Securing routes](#securing-routes) | | `servers` | Base URLs the API is served from | | `tags` | Tag descriptions. Each controller is a tag, named after the class without `Controller` | | `security` | Security requirement for every route. Prefer `auth`, which applies to `@Authorized` routes only | | `components` | Extra schemas, responses and security schemes, merged into the generated ones | | `externalDocs` | A link to more documentation | | `uiConfig` | Swagger UI settings: `docExpansion`, `persistAuthorization`, `filter`, … | | `scalar` | Scalar settings, with `provider: 'scalar'` | | `logo` | Swagger UI top-bar logo. Defaults to the Megh logo | | `theme` | Swagger UI `title`, `css`, `js` and `favicon`. Defaults to the Megh favicon | | `openapi` | OpenAPI version of the document. Defaults to `3.0.3` | | `paths` | Extra paths documented as given, for routes outside Megh | For example, keep the "Authorize" credentials across reloads and start with operations collapsed: ```ts app.useOpenApi({ info: { title: 'My API', version: '1.0.0' }, uiConfig: { docExpansion: 'list', persistAuthorization: true }, }); ``` ### Logo and favicon Swagger UI shows the Megh logo and favicon. To use your own, pass a `logo` (an image as a string or `Buffer`, with its MIME type) and a `favicon` in `theme`: ```ts import { readFileSync } from 'fs'; app.useOpenApi({ info: { title: 'My API', version: '1.0.0' }, logo: { type: 'image/svg+xml', content: readFileSync('public/logo.svg'), href: 'https://example.com', // where the logo links to; defaults to the app root }, theme: { title: 'My API docs', favicon: [ { filename: 'favicon.png', rel: 'icon', type: 'image/png', sizes: '32x32', content: readFileSync('public/favicon.png') }, ], }, }); ``` Set `logo: null` for Swagger UI's own logo. ### Scalar UI To use [Scalar](https://scalar.com) instead of Swagger UI, install `@scalar/fastify-api-reference` and set the provider: ```ts app.useOpenApi({ info: { title: 'My API', version: '1.0.0' }, provider: 'scalar', scalar: { layout: 'modern', darkMode: true }, }); ``` The CLI can wire this up for you — pick *Scalar UI* when running `megh new`. ## Documenting routes Use `@OpenApi` on a controller or a route method to enrich the generated document. The route decorators take the same options as `openapi`: `@Get('/', { openapi: { summary: 'List users' } })`. ```ts [controllers/welcome.controller.ts] import { Controller, Get, OpenApi } from '@meghjs/core'; @OpenApi({ tags: ['welcome'] }) @Controller('/welcome') export class WelcomeController { @OpenApi({ summary: 'Say hello', description: 'Returns a greeting.', response: { 200: { description: 'A greeting' }, }, }) @Get() sayHello() { return 'Hello world!'; } } ``` Useful `@OpenApi` fields: | Field | Description | |-------|-------------| | `summary` / `description` | Human-readable text | | `tags` | Groups the route in the UI | | `params` / `query` / `headers` | Document inputs | | `requestBody` | Document the body | | `response` | Responses keyed by status code. See [Responses](#responses) | | `deprecated` | Mark the route deprecated | | `exclude` | Hide the route from the document | | `security` | Per-route security requirements | For example, documenting inputs: ```ts @OpenApi({ params: { id: { type: 'string', example: 'abc-123' } }, query: { page: { type: 'integer', example: 1 } }, }) @Get('/:id') findOne(@Param('id') id: string) { return { id }; } ``` ### Query parameters `@Query()` parameters are documented automatically, in the order of the method's parameters: ```ts @Get() index(@Query() query: ListUsersQuery, @Query('role') role: string) { return this.userService.paginate(query); } ``` A DTO (`@Query() query: ListUsersQuery`) becomes one query parameter per property, with its type and validation constraints (`@Min(1)` as `minimum: 1`, `@MaxLength(255)` as `maxLength`, …). A property is required when it has `@IsNotEmpty()` or `@IsDefined()`, as for body DTOs. A single value (`@Query('role') role: string`) becomes one parameter, typed from the parameter's type and required unless you pass `{ required: false }`. This is documentation only: the values are still validated by the DTO. A parameter given in `@OpenApi({ query })` takes precedence over the generated one of the same name. To show a date format, add it to the DTO property with `@OpenApiProperty`: ```ts @IsOptional() @OpenApiProperty({ format: 'date', example: '2026-11-10' }) @Matches(/^\d{4}-\d{2}-\d{2}$/) @IsDateString({ strict: true }) startDate?: string; ``` ### Request bodies A `@Body()` DTO is documented automatically as a required `application/json` body (or `multipart/form-data` when it has a `format: 'binary'` field). Nested DTOs become `$ref`s under `components.schemas`. `requestBody` refines or replaces that. It only affects the document, and validation still comes from the DTO: ```ts // Describe the DTO body @OpenApi({ requestBody: { description: 'The new user' } }) @Post() create(@Body() body: CreateUserDto) {} // Inline schema with an example; `required` defaults to true @OpenApi({ requestBody: { required: false, schema: { type: 'object', properties: { q: { type: 'string' } } }, example: { q: 'megh' }, }, }) // One schema per media type (schemas may be DTO classes) @OpenApi({ requestBody: { content: { 'application/json': { schema: CreateUserDto }, 'text/csv': { schema: { type: 'string' } }, }, }, }) ``` `requestBody` also takes a DTO class (`requestBody: CreateUserDto`) or a `$ref` to `#/components/requestBodies/*`. Use `contentType` to document `schema` under other media types, and `examples` / `encoding` as in the OpenAPI spec. ## Responses Document what a route returns with `@ApiResponse(status, type)`. The type is a DTO class, a MeghORM model, `[Class]` for an array, `Paginated(Class)` for a page, or a JSON schema: ```ts [controllers/user.controller.ts] import { Controller, ApiResponse, Body, Get, Paginated, Param, Post, Query } from '@meghjs/core'; import { User } from '../models/user.model'; @Controller('/users') export class UserController { @Get() @ApiResponse(200, Paginated(User)) // { data: User[], meta } index(@Query() query: ListUsersQuery) { return this.users.paginate(query); } @Get('/:id') @ApiResponse(200, User) @ApiResponse(404) // the error shape show(@Param('id') id: number) { return this.users.findOrFail(id); } @Post() @ApiResponse(201, { type: UserDto, description: 'The new user' }) create(@Body() body: CreateUserDto) { return this.users.create(body); } } ``` A model is documented from its column decorators: each column's type, nullability and length, and nothing else, so the schema follows the model as it changes. A DTO is documented from its validation decorators (Megh's or class-validator's), as request bodies are. `@ApiResponse` on the controller class applies to every route in it. Responses are documentation only: the handler's return value is sent as it is, so fields outside the documented schema (loaded relations, `withCount()` counts) still reach the client. `@OpenApi({ response: { 200: User } })` works the same way. A plain JSON schema there (`{ 200: { type: 'object', … } }`) is also Fastify's response schema, which serializes the reply and drops fields it doesn't list. `megh make:resource` writes these annotations for you: a page of the model for `index`, the model for `show`, `create` and `update`, and `404` where the service calls `findOrFail()`. ::: info Why not from the return type? TypeScript's types don't exist at runtime, so Megh can't read that `show()` returns a `Promise`. Name the type once in `@ApiResponse`. ::: ### Errors Megh adds the errors a route can return from what its controller declares, so you don't document them by hand: | When | Response | |------|----------| | The route validates a `@Body()` or `@Query()` DTO | `400` with the validation error shape: `{ code, status, message, errors: [{ path, constraints }] }` | | The route or its controller is `@Authorized` | `401` and `403` | | `@ApiResponse(404)` (any `4xx`/`5xx`) with no type | That status with Megh's error shape: `{ code, status, message, data? }` | An `@ApiResponse` for the same status replaces the generated one. ## Securing routes Set `auth` and every `@Authorized` route gets the security scheme, so the "Authorize" button applies to it and the UI shows its lock icon: ```ts app.useOpenApi({ info: { title: 'My API', version: '1.0.0' }, auth: 'bearer', // Authorization: Bearer }); ``` `'apiKey'` documents an `X-API-Key` header instead. For anything else, pass an OpenAPI security scheme: `auth: { type: 'apiKey', in: 'query', name: 'token' }`. Routes without `@Authorized` stay open. ## Inline routes Routes registered with `mapGet` and friends return a chainable object, so they can carry their own OpenAPI metadata: ```ts [app.ts] import { Megh } from '@meghjs/core'; const app = Megh.createApplication(); app.mapGet('/', () => 'Welcome to Megh.').useOpenApi({ tags: ['welcome'], summary: 'Root greeting', }); export default app; ``` The same object also exposes `useMiddleware`: ```ts app.mapGet('/secret', handler) .useMiddleware([ApiKeyMiddleware]) .useOpenApi({ tags: ['internal'] }); ``` --- # WebSocket Source: https://meghjs.github.io/microservices/websocket Megh's realtime layer is built on [Socket.IO](https://socket.io). It and its Fastify adapter are optional peer dependencies: ```sh npm i socket.io fastify-socket.io ``` ## Enabling websockets Call `useSocketIo` during app setup. Options are passed straight through to the Socket.IO server. ```ts [app.ts] import { Megh } from '@meghjs/core'; import { ChatSubscriber } from './subscribers/chat.subscriber'; const app = Megh.createApplication(); app.useSocketIo({ cors: { origin: '*' }, }); export default app; ``` The server is created when the app runs; connecting clients are wired to your subscribers automatically. ## Subscribing to events Mark any service method with `@Subscribe('event')` to handle an incoming client event. The class must be registered with the container — `@AppService` does that. ```ts [subscribers/chat.subscriber.ts] import { AppService, Subscribe } from '@meghjs/core'; @AppService export class ChatSubscriber { @Subscribe('message') onMessage(payload: { room: string; text: string }) { console.log(`[${payload.room}] ${payload.text}`); } @Subscribe('typing') onTyping(payload: { user: string }) { console.log(`${payload.user} is typing`); } } ``` Handlers run inside a socket context, so the originating socket is available through `SocketContextService` for the duration of the call. ## Emitting to clients Inject `SocketEventDispatcher` to push events out: ```ts [services/chat.service.ts] import { AppService, SocketEventDispatcher } from '@meghjs/core'; @AppService export class ChatService { constructor(private readonly socket: SocketEventDispatcher) {} async announce(text: string) { await this.socket.dispatch('announcement', { text }); } async toRoom(room: string, text: string) { await this.socket.dispatch('message', { text }, { room }); } async toEveryoneElse(room: string, text: string) { // skips the socket that triggered the current handler await this.socket.dispatch('message', { text }, { room, broadcast: true }); } } ``` `dispatch` accepts: | Option | Description | |--------|-------------| | `room` | Emit only to this room | | `broadcast` | Exclude the current socket | | `transports` | Defaults to `['socket']`, the only transport in 1.0. Any other value throws. | | `retry` | Attempts on failure | | `retryDelay` | Base delay in ms; backs off per attempt | ## Authentication With `app.useAuthentication(Handler)` registered, the same handler runs once on each Socket.IO handshake. What it returns becomes `socket.data.user`: - a user: the socket is connected as that user; - `null` or `undefined`: the socket connects as a guest, and `@PrivateChannel` listeners ignore it; - a thrown error: the connection is refused, and the client's `connect_error` has the message `Unauthorized`. The handler gets a request-shaped object: the handshake `headers`, `query`, `auth` and `ip`. Browsers can't set headers on a WebSocket, so a token sent as `auth.token` arrives as `authorization: Bearer `, and a handler that reads the HTTP header works unchanged: ```ts [client] const socket = io('https://api.example.com', { auth: { token } }); ``` ## Private channels `@PrivateChannel` restricts a subscriber method to a channel derived from the connecting socket — use it for per-user streams. Its listeners only run for sockets with a `socket.data.user`: ```ts import { AppService, Subscribe, PrivateChannel } from '@meghjs/core'; @AppService export class NotificationSubscriber { @PrivateChannel((socket) => `user:${socket.handshake.auth.userId}`) @Subscribe('notify') onNotify(payload: unknown) { // only reachable on the caller's own channel } } ``` ## Reaching the raw server For anything the helpers do not cover, resolve the Socket.IO `Server` itself: ```ts import { MeghContainer, SocketIoServer } from '@meghjs/core'; const io = MeghContainer.get(SocketIoServer); io.emit('ping', Date.now()); ``` ::: warning `SocketIoServer` is only registered once the app is running and websockets are enabled. Resolving it during module load will fail. ::: Resolve services through `MeghContainer`. Megh has its own container and no longer installs `typedi`. ## Broadcasting events The [event system](/advanced/events) can forward a dispatched event to Socket.IO, which keeps domain events and realtime delivery in one place: ```ts await dispatcher.dispatch(new UserCreatedEvent({ userId, name }), { broadcast: { type: 'socket', channel: 'user:create' }, }); ``` --- # Caching Source: https://meghjs.github.io/advanced/caching Enable the cache on the app. It is in-memory by default: ```ts [app.ts] app.useCache({ provider: 'memory' }); ``` For Redis, pass connection options. The Redis client ships with `@meghjs/core`, and Megh opens the connection on first use and closes it on shutdown: ```ts app.useCache({ provider: 'redis', redis: { url: process.env.REDIS_URL }, // redis:// or rediss:// }); ``` `redis` also takes `host`, `port` (default `127.0.0.1:6379`), `username`, `password`, `db` and `tls`. ## Using the cache Inject `CacheManager`. `set` takes a key, a value, a TTL in seconds, and optional tags: ```ts [services/users.service.ts] import { AppService, CacheManager } from '@meghjs/core'; @AppService export class UsersService { constructor(private readonly cache: CacheManager) {} async findAll() { const cached = await this.cache.get('users:all'); if (cached) return cached; const users = await this.repo.find(); await this.cache.set('users:all', users, 3600, ['users']); return users; } async update(user: User) { await this.repo.save(user); await this.cache.invalidateTags('users'); // drops every key tagged 'users' } } ``` ## Expiry - A TTL of `0` or less means the entry never expires. - The memory store drops expired entries when they are read, and in a background sweep every 60 seconds. The sweep does not keep the process alive. - The memory store has no size limit, so give large or numerous entries a TTL. - In Redis, tag sets expire no earlier than the longest-lived key they track. ## Instances The `CacheManager` registered by `useCache` is a singleton shared through dependency injection. `new CacheManager(options)` creates an independent store, which is useful in tests: ```ts const cache = new CacheManager({ provider: 'memory', sweepIntervalMs: 1000 }); cache.sweep(); // remove expired entries now; returns how many await cache.close(); // stop the sweep timer and release resources ``` Call `await CacheManager.close()` on shutdown to close every instance, including the Redis connection. The app does this for you when it shuts down. --- # LLM Tools Source: https://meghjs.github.io/ai/tools `@meghjs/ai` lets a language model call your API. Mark a route with `@Tool()` and the model can call it as a tool, with Anthropic, OpenAI or any SDK that takes JSON Schema tools. - **One source of truth.** The tool's input schema is built from the route's path parameters, `@Query()` and `@Body()` DTO, the same ones used for validation and OpenAPI. - **No back door.** A tool call is an HTTP request to the route, sent inside the process. Middleware, authentication, `@Authorized`, validation, rate limits and exception filters all run, exactly as they do for a browser. - **Approval for side effects.** `confirm: true` marks a tool that changes data. It won't run until a person approves it. - **Errors the model can fix.** A 400 comes back as the validation errors, not as an exception. ## Install ```sh npm install @meghjs/ai ``` It's a [plugin](/advanced/plugins), so it's loaded automatically once it's installed. ## Mark routes as tools ```ts import { Controller, Authorized, Body, Get, Param, Post } from "@meghjs/core"; import { Tool } from "@meghjs/ai"; @Controller("/orders") export class OrderController { constructor(private readonly orders: OrderService) {} @Get("/:id") @Authorized() @Tool({ description: "Look up one order by its ID, with its items and status." }) find(@Param("id") id: string) { return this.orders.find(id); } @Post("/:id/refund") @Authorized("admin") @Tool({ description: "Refund an order, fully or in part.", confirm: true, tags: ["admin"] }) refund(@Param("id") id: string, @Body() body: RefundDto) { return this.orders.refund(id, body); } } ``` | Option | Meaning | |---|---| | `description` | Required. What the tool does, written for the model: when to use it and what it returns. | | `name` | The tool's name. Defaults to the controller and method in snake case: `OrderController.find` → `order_find`. | | `confirm` | `true`: the tool has side effects and needs a person's approval. | | `tags` | Labels for picking a set of tools: `app.tools({ tags: ["admin"] })`. | | `maxOutput` | Largest response, in characters, sent back to the model (default 20 000). | The model sees **one object** of arguments. For `refund` above that's `{ id, amount, reason }`: the path parameter and the DTO's fields side by side. When a body field has the same name as a path or query parameter, the body goes under a `body` key instead. A field is listed as required when the DTO marks it `@IsNotEmpty()` or `@IsDefined()`, the same rule the OpenAPI docs use. Validation still checks every rule, so if the model leaves out a field that is needed, it gets back a 400 it can correct. ## Give the tools to a model Inject `ToolSet` (or call `app.tools()`) to get the tools, in the shape each provider expects: ```ts constructor(private readonly tools: ToolSet) {} // every @Tool route const tools = this.tools.filter({ tags: ["orders"] }); // or app.tools({ tags: ["orders"] }) tools.forAnthropic(); // [{ name, description, input_schema }] tools.forOpenAI(); // [{ type: "function", function: { name, description, parameters } }] tools.forMcp(); // [{ name, description, inputSchema, annotations }] ``` The set is read when it's used, so it's complete once the app has started. ## Run the model's tool calls Pass the incoming request so the tools run **as the signed-in user**. Its `authorization`, `cookie`, `x-api-key` and `x-request-id` headers are forwarded: ```ts import Anthropic from "@anthropic-ai/sdk"; import { ToolSet } from "@meghjs/ai"; @Controller("/assistant") export class AssistantController { private readonly anthropic = new Anthropic(); constructor(private readonly tools: ToolSet) {} @Post("/") @Authorized() async ask(@Body() body: AskDto, @MeghRequest() req: IRequest) { const tools = this.tools.filter({ tags: ["orders"] }); const messages: Anthropic.MessageParam[] = [{ role: "user", content: body.question }]; for (let step = 0; step < 10; step++) { const res = await this.anthropic.messages.create({ model: "claude-sonnet-5-5", max_tokens: 1024, tools: tools.forAnthropic(), messages, }); messages.push({ role: "assistant", content: res.content }); if (res.stop_reason !== "tool_use") return { answer: res.content }; messages.push({ role: "user", content: await tools.anthropicResults(res.content, { request: req }) }); } throw new BadRequestException("The assistant took too many steps."); } } ``` For OpenAI, `tools.openAIResults(message.tool_calls, { request })` returns the `tool` messages to append. To run one tool yourself: ```ts const result = await this.tools.call("order_find", { id: "42" }, { request: req }); // { ok: true, status: 200, data: {...}, content: '{"id":"42",...}' } ``` Code with no request to forward, such as a queue job, can pass the user instead. The route gets it as `request.user` without signing in, and `@Authorized` still runs: ```ts await this.tools.call("order_find", { id: "42" }, { user }); ``` To let a model call tools in a loop on a queue, see [Agents](/ai/agents). `call` never throws for a failed route. A 403, 404 or validation error comes back with `ok: false`, its `status`, and a `content` the model can read. Unknown or missing arguments are refused before the route is called. ## Approval A `confirm: true` tool doesn't run unless the call says a person approved it: ```ts const r = await tools.call("order_refund", args, { request: req }); if (r.needsConfirmation) { // Nothing ran. Ask the user, then: await tools.call("order_refund", args, { request: req, confirmed: true }); } ``` Inside `anthropicResults` and `openAIResults`, an unapproved tool comes back to the model as an error that tells it so, and it can ask the user. In development, Megh warns about a `POST`, `PUT`, `PATCH` or `DELETE` tool with neither `confirm: true` nor `confirm: false`. ## Serve the tools over MCP `app.useMcp()` turns your app into an [MCP](https://modelcontextprotocol.io) server, so assistants such as Claude, ChatGPT, Cursor or VS Code can use your product directly, with the same permissions as the user who connects them. ```sh npm install @modelcontextprotocol/sdk ``` ```ts app.useMcp({ tools: { tags: ["public"] }, // required: which tools to serve, or "all" }); ``` The server speaks MCP's Streamable HTTP transport at `/mcp`. **Sign-in.** A client signs in exactly like an API client, with a bearer token or an API key, and your `useAuthentication` handler checks it. Each tool call runs as that caller, through its route's own `@Authorized`. So a user who can't refund orders over HTTP can't refund them through MCP either. ```json { "mcpServers": { "shop": { "type": "http", "url": "https://api.example.com/mcp", "headers": { "Authorization": "Bearer " } } } } ``` **Approval.** By default, a `confirm: true` tool asks the user before it runs. The server sends the question to the client mid-call (MCP *elicitation*), and the tool runs only if the user approves. A client that can't ask gets an error, and the tool doesn't run. Pick another way with `confirm`: | `confirm` | A `confirm: true` tool... | |---|---| | `"elicit"` (default) | runs once the user approves it through the client | | `"client"` | runs straight away. It's marked destructive, so clients that ask before each tool call (Claude Code does) still ask | | `"refuse"` | isn't served | All options: ```ts app.useMcp({ tools: { tags: ["public"] }, path: "/mcp", authorize: true, // @Authorized on the endpoint too: keeps the tool list private rateLimit: { max: 120, window: "1m" }, confirm: "elicit", sessions: true, // see below sessionTimeout: 30 * 60_000, // close idle sessions after 30 minutes name: "shop", version: "1.0.0", instructions: "Tools for the Example Shop API. Look up an order before refunding it.", }); ``` **Sessions.** By default, each client gets a session, kept in memory and closed after `sessionTimeout` without a request. A session is bound to the credentials that opened it, so a session ID alone can't be used by another client. Sessions live in one process: run a single instance, or route a client to the same instance (sticky sessions). With `sessions: false` the server is stateless and any instance can answer. It can't ask the user to approve then, so set `confirm` to `"client"` or `"refuse"`. The endpoint is left out of the OpenAPI document. ## Settings ```ts app.useTools({ maxOutput: 10_000, // characters sent back to the model forwardHeaders: ["authorization", "x-tenant"], // headers copied from `request` logArguments: false, // include arguments in the audit log }); ``` Each call is logged with the tool name, status, duration and request ID. Arguments are left out unless `logArguments` is on, since they can contain personal data. ## Safety checklist - A tool can do whatever its route does, with the caller's rights. Expose only what a model should do, and keep `@Authorized` on anything that isn't public. - Use `confirm: true` for every tool that changes data, unless the change is harmless. - Give each route `@RateLimit`: an agent in a loop can call it faster than any person. - Treat tool results as data. Text coming back from your API (a customer's note, a product description) can contain instructions meant for the model. ## See which routes are tools `megh route:list` adds a **TOOL** column once the app has `@Tool` routes, and `--json` adds a `tool` field. The [MCP server](/ai/mcp)'s `megh_list_ai_tools` lists them with warnings, such as a tool that changes data without `confirm` or without `@Authorized`. --- # Agents Source: https://meghjs.github.io/ai/agents An agent is a model that calls your [tools](/ai/tools) in a loop until the job is done. `@meghjs/ai` runs that loop on your [queues](/advanced/queue), so it fits in a web app: - **No long requests.** `agents.start()` saves the run and returns its ID at once. The run happens on a worker. - **Steps are saved.** Each step (one model call, then the tool calls it asked for) is one queue job, and the run is saved after every step. If a worker dies, the job is retried and the run continues from the last saved step. - **No new rights.** Tools run as the user who started the run, through the route's authentication, `@Authorized`, validation and rate limits. An agent can only call the tools you list for it. - **Hard limits.** Model calls, tokens, time and tool calls are capped per run. A run that reaches a limit fails, with the limit's name as the reason. ## Install ```sh npm install @meghjs/ai @anthropic-ai/sdk # or: openai ``` The provider SDK is only loaded when an agent first calls the model. Without it, the run fails with an error that names the package to install. ## Define an agent ```sh npx megh make:agent SupportTriage --tags orders,tickets ``` ```ts [src/agents/support-triage.agent.ts] import { Agent, MeghAgent } from "@meghjs/ai"; @Agent({ model: { provider: "anthropic", id: "claude-sonnet-5-5" }, system: "You triage support tickets. Look up the order before you answer.", tools: { tags: ["orders", "tickets"] }, limits: { steps: 20, tokens: 200_000, duration: "15m", toolCalls: 50 }, queue: "agents", }) export class SupportTriageAgent extends MeghAgent<{ ticketId: string }> { // The first message of the run. Optional: by default a string input is sent // as it is, and anything else as JSON. prompt(input: { ticketId: string }) { return `Triage ticket ${input.ticketId}.`; } } ``` | Option | Meaning | |---|---| | `model` | Required. `{ provider, id }`, plus optional `maxTokens` per call (default 16 000), `baseURL` and `apiKey`. | | `system` | The system prompt. | | `tools` | Which `@Tool` routes the agent may call, by `tags` or `names`. Without it the agent has no tools. | | `limits` | `steps` (model calls, default 20), `tokens` (input plus output, default 200 000), `duration` (default `'15m'`), `toolCalls` (default 50). | | `queue` | The queue its steps run on. Default `agents`. | | `name` | The name in runs and logs. Defaults to the class name in kebab case: `support-triage`. | | `attempts` | Attempts per step, for provider errors and crashed workers. Default 3. | Register your agents once: ```ts [src/app.ts] app.useAgents([SupportTriageAgent]); ``` The steps run on a [queue](/advanced/queue) like any other, so they use the queue transport you configured: memory in development, Redis or RabbitMQ in production. `useAgents([...], { worker: false })` starts runs without running steps in this process. ## Start a run Inject `AgentRunner` and start a run from a controller, an event listener or a scheduled task: ```ts import { AgentRunner } from "@meghjs/ai"; @Controller("/tickets") export class TicketController { constructor(private readonly agents: AgentRunner) {} @Post("/:id/triage") @Authorized() async triage(@Param("id") id: string, @AuthUser() user: User) { const run = await this.agents.start(SupportTriageAgent, { ticketId: id }, { user }); return { runId: run.id, status: run.status }; // "queued" } @Get("/runs/:runId") @Authorized() async run(@Param("runId") runId: string) { return this.agents.get(runId); // status, steps, usage, output, error } } ``` `user` defaults to the signed-in user of the current request. A run started from a task or listener has no user unless you pass one, so its tools run anonymously. | Method | Does | |---|---| | `start(Agent, input, { user, model })` | Saves the run and queues its first step. `model` replaces the agent's model for this run. | | `get(runId)` | The run, or `undefined`. | | `cancel(runId, { user })` | Stops the run. The call in progress finishes; nothing more runs. | | `list({ agent, status, limit })` | Recent runs, newest first. | A run has `id`, `agent`, `status`, `input`, `output` (the final answer), `error`, `usage` (`inputTokens`, `outputTokens`), `steps`, `messages` and `toolCalls`. Sending a run in a response leaves out the user. The status is one of `queued`, `running`, `succeeded`, `failed` or `cancelled`. (`waiting_approval` and `expired` are reserved for approvals, which are coming later.) ## How a run executes 1. The model gets the system prompt, the conversation so far and the agent's tools. 2. If it answers without tool calls, the run `succeeded` and its `output` is the answer. 3. Otherwise each tool call runs through `tools.call(name, args, { user })`: an HTTP request to the route, inside the process, as the run's user. A 403 or a validation error goes back to the model as a tool error, so it can try something else. The run doesn't crash. 4. The results are saved, and the next step is queued. Each tool request carries an `idempotency-key` header (`:`) that a route can use to ignore a repeated call. ## Limits and failures A failed run has `error: { reason, message }`. The reasons are: | `reason` | When | |---|---| | `steps`, `tokens`, `duration`, `toolCalls` | The run reached that limit. There's no "one more step". | | `approval` | The model called a `confirm: true` tool. The message starts with "approval needed". | | `interrupted` | A worker died while a tool with side effects was running. It may have run, so it isn't run again. | | `error` | The model call kept failing (provider error, missing SDK) after every attempt. | | `agent` | The worker has no agent with the run's name (it isn't in `useAgents`). | **Approval isn't supported yet.** A run that reaches a `confirm: true` tool fails with "approval needed", and the tool doesn't run. Waiting for a person to approve the call is coming in a later version. Until then, leave `confirm` tools out of an agent's tags, or give the agent read-only tools. **Crashes.** Before a tool runs, its step is saved as `started`. If the worker dies there, the retried job runs a read-only (`GET`) tool again, and fails the run with `interrupted` for any other tool rather than risk a second refund or a second email. ## Models | `provider` | Needs | Notes | |---|---|---| | `anthropic` | `@anthropic-ai/sdk` | Messages API. Reads `ANTHROPIC_API_KEY` unless you set `apiKey`. | | `openai` | `openai` | Chat Completions. Reads `OPENAI_API_KEY` unless you set `apiKey`. | For an OpenAI-compatible server, such as Ollama or vLLM, use `openai` with a `baseURL`: ```ts @Agent({ model: { provider: "openai", id: "llama3.1", baseURL: "http://localhost:11434/v1", apiKey: "ollama" }, tools: { tags: ["orders"] }, }) export class LocalAgent extends MeghAgent {} ``` To use your own client (a proxy, custom retries) or another provider, pass an adapter by name. An adapter is an object with `provider` and `generate(request)`: ```ts import Anthropic from "@anthropic-ai/sdk"; import { AgentModel } from "@meghjs/ai"; app.useAgents([SupportTriageAgent], { models: { anthropic: AgentModel.anthropic({ client: new Anthropic({ maxRetries: 4 }) }) }, }); ``` ## Where runs are kept By default runs are kept in memory, in the process that started them. That works for development and tests, and for one process with the memory queue transport. With Redis or RabbitMQ, workers in other processes can't see those runs, so Megh logs a warning. Pass your own store, an object with `create`, `get`, `update`, `saveStep`, `list` and `prune` (see `AgentRunStore`): ```ts app.useAgents([SupportTriageAgent], { store: new MyAgentRunStore() }); ``` A database store with migrations is coming later. ## Testing `AgentModel.fake()` answers every model call from a script, like [`Mailer.fake()`](/advanced/mail): no network calls, and assertions on what happened. Run the queues in memory and wait for them: ```ts import { setQueueTransport, waitForMemoryQueues, resetMemoryQueues } from "@meghjs/core"; import { AgentModel } from "@meghjs/ai"; beforeAll(() => setQueueTransport("memory")); afterEach(() => { AgentModel.restore(); resetMemoryQueues(); }); it("looks up the order", async () => { const model = AgentModel.fake([ { toolCalls: [{ name: "order_find", args: { id: "42" } }] }, { text: "Order 42 shipped yesterday." }, ]); const run = await agents.start(SupportTriageAgent, { ticketId: "t1" }, { user }); await waitForMemoryQueues(); run.assertStatus("succeeded"); run.assertToolCalled("order_find", (args) => args.id === "42"); model.assertCalledTimes(2); expect(model.requests[1].messages.at(-1)).toMatchObject({ role: "tool", isError: false }); }); ``` A scripted answer can also set `usage` (to test the token limit), `delay` (to test the duration limit) or `error` (to test retries). In the process that runs it, a run follows its own progress, so assertions after `waitForMemoryQueues()` see the final state. Elsewhere, call `run.refresh()` or `agents.get(id)`. ## Coming later - Approval: `waiting_approval`, `agents.approve()` and `agents.reject()`, and expiry. - A database store, with migrations and retention. - `agents.stream(runId)` over SSE and Socket.IO. - `megh agent:list`. --- # MCP Server Source: https://meghjs.github.io/ai/mcp `@meghjs/mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server for Megh. MCP is an open standard for connecting AI assistants to tools and data. With this server, assistants such as Claude Code, Claude Desktop, Cursor and VS Code work from your real project and the real Megh docs instead of guessing. ::: tip Serving your own app to AI assistants? This page is about a server for *building* Megh apps. To let assistants use *your app's* API, with your users' permissions, see [LLM Tools: Serve the tools over MCP](/ai/tools#serve-the-tools-over-mcp). ::: It gives an assistant: - **The Megh docs.** They ship with the server and match its version, so the assistant searches and reads the right API instead of relying on memory. - **A view of your project:** dependencies, source files by kind, routes, migration status, the `megh doctor` checks and type errors. - **The `megh` generators and scaffolds,** run the same way the CLI runs them. - **Migrations and seeders,** which it refuses to run against a production project. Without an MCP client, point an agent at [`/llms.txt`](https://meghjs.github.io/llms.txt), an index of these docs for agents, or [`/llms-full.txt`](https://meghjs.github.io/llms-full.txt), all of them in one file. It wraps the `megh` CLI. It uses the `@meghjs/cli` installed in your project when there is one, so generated code matches your `@meghjs/core`, and falls back to its own copy otherwise. ## Setup The server runs with `npx`, so there is nothing to install in your project. ### Claude Code From your project folder: ```sh claude mcp add megh -- npx -y @meghjs/mcp ``` ### VS Code Add `.vscode/mcp.json` to your project: ```json [.vscode/mcp.json] { "servers": { "megh": { "type": "stdio", "command": "npx", "args": ["-y", "@meghjs/mcp", "${workspaceFolder}"] } } } ``` ### Claude Desktop, Cursor and others Any client that reads an `mcpServers` config: ```json { "mcpServers": { "megh": { "command": "npx", "args": ["-y", "@meghjs/mcp", "/path/to/your/project"] } } } ``` Then ask the assistant something like "review this Megh project" or "add a products resource with a name and a price". ## Options ```sh megh-mcp [project-dir] [--read-only] ``` | Option | Environment | Description | | --- | --- | --- | | `project-dir` | `MEGH_PROJECT_ROOT` | The project the tools work on. Defaults to the folder the server starts in. Every tool also takes an optional `cwd`. | | `--read-only` | `MEGH_MCP_READ_ONLY=1` | Leave out every tool that writes files or changes the database, and the `megh-add-resource` prompt. | | | `MEGH_DOCS_DIR` | Serve docs from this folder instead of the bundled ones. | ::: tip Read-only for reviews Use `--read-only` when you only want the assistant to explain or review your code. It can still read the docs and inspect the project, but it can't change files or the database. ::: ## Tools ### Project | Tool | What it does | | --- | --- | | `megh_project_info` | Project root, `@meghjs/*` dependencies (declared and installed), scripts, `megh` settings, and whether it runs in production | | `megh_project_structure` | Source files grouped by kind (controllers, services, models, DTOs, migrations, seeders...), with counts and the entry file | | `megh_doctor` | The `megh doctor` checks: Node.js, `@meghjs/core`, `reflect-metadata`, decorator settings | | `megh_list_routes` | `megh route:list --json`. `static: true` reads the decorators without running your code | | `megh_list_ai_tools` | The routes exposed to LLMs with [`@Tool()`](/ai/tools), with warnings such as a tool that changes data without `confirm` or `@Authorized` | | `megh_list_templates` | `megh template:list [domain] --json` | | `megh_typecheck` | Runs the project's `tsc --noEmit` and returns the errors | | `megh_migrate_status` | `megh migrate:status --json` | ### Docs | Tool | What it does | | --- | --- | | `megh_search_docs` | Searches the Megh docs and returns the best-matching pages with snippets | | `megh_read_doc` | Reads a page as markdown, e.g. `core-concept/controller`. With no page, lists them all | ### Code generation | Tool | What it does | | --- | --- | | `megh_make` | `megh make: ` for model, controller, service, resource, dto, config, middleware, mail, event, listener, queue, worker, task, migration, seeder and factory | | `megh_sync_model` | `megh sync:model`: updates a model after an alter-table migration. `dryRun` shows the changes first | | `megh_scaffold_domain` | `megh scaffold:domain`: the tables (and models or resources) of a domain's templates | | `megh_scaffold_auth` | `megh scaffold:auth`: sign-up and sign-in with JWTs, API keys or both, optionally with roles | | `megh_scaffold_rbac` | `megh scaffold:rbac`: roles and permissions for an app that already has users | | `megh_build` | `megh build`: compiles to the output folder and copies assets | The generators never prompt, and they leave existing files alone unless `force` is set. ### Database | Tool | What it does | | --- | --- | | `megh_migrate` | Runs the pending migrations, optionally followed by the seeders | | `megh_migrate_rollback` | Undoes the last migration, or the last `step` | | `megh_db_seed` | Runs the seeders, or one `seeder` | These refuse to run when `NODE_ENV` is `production`, whether it is set in the server's environment or in the project's `.env`. `migrate:reset` and `migrate:refresh` aren't exposed, because they drop every table. Run those yourself. ## Resources and prompts | Resource | Contents | | --- | --- | | `megh://docs/{page}` | A docs page as markdown, e.g. `megh://docs/advanced/orm` | | `megh://project/info` | The project, as `megh_project_info` returns it | | `megh://project/structure` | The project's files, as `megh_project_structure` returns them | | Prompt | What it does | | --- | --- | | `megh-review-project` | Checks the setup, routes, structure and type errors, and points out problems | | `megh-explain` | Explains a Megh feature (`topic`) from the docs, with an example that fits the project | | `megh-add-resource` | Adds a table, model and CRUD API for `name` (with optional `fields`), migrates, and checks it compiles. Not offered in read-only mode | | `megh-add-ai-tools` | Marks routes (`routes`, optional) as [LLM tools](/ai/tools) with `@Tool()`, then checks them with `megh_list_ai_tools`. Not offered in read-only mode | ## Use it as a library ```ts import { createServer } from '@meghjs/mcp'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; const server = createServer({ projectRoot: '/path/to/app', readOnly: true }); await server.connect(new StdioServerTransport()); ``` --- # Testing Source: https://meghjs.github.io/advanced/testing `MeghTest` helps with two kinds of test: - **Unit tests**: build a controller or service with its dependencies, and call its methods. - **Route tests**: send requests to your app without opening a port. The examples use [Vitest](https://vitest.dev), which `megh new` sets up. ## Setup Megh's constructor injection needs decorator metadata, which Vitest's default transform (esbuild) doesn't emit. Use SWC instead: ```sh npm i -D vitest unplugin-swc @swc/core ``` ```ts [vitest.config.mts] import swc from 'unplugin-swc'; import { defineConfig } from 'vitest/config'; export default defineConfig({ plugins: [swc.vite()], test: { environment: 'node', include: ['src/**/*.spec.ts'], }, }); ``` `megh new` generates this file, plus `vitest.e2e.config.mts` for `test/**/*.e2e-spec.ts`. ::: tip Generated tests `megh make:service`, `make:controller`, `make:resource` and the other generators write a `.spec.ts` next to the file they create, and `megh make:test ` writes one for a file you already have. See [CLI: Tests](/cli/generators#tests). ::: ## Unit tests `MeghTest.getController` and `MeghTest.getProvider` resolve a class through [dependency injection](/core-concept/dependency-injection), with its dependencies built for you: ```ts [src/controllers/home.controller.spec.ts] import { beforeAll, describe, expect, it } from 'vitest'; import { MeghTest } from '@meghjs/core'; import { HomeController } from './home.controller'; describe('HomeController', () => { let controller: HomeController; beforeAll(() => { controller = MeghTest.getController(HomeController); }); it('returns a greeting', () => { expect(controller.sayHello()).toEqual({ message: 'Hello World!' }); }); }); ``` ### Replacing dependencies Pass stand-ins as the second argument, in constructor parameter order: ```ts [src/services/user.service.spec.ts] import { afterEach, expect, it, vi } from 'vitest'; import { MeghTest } from '@meghjs/core'; import { UserService } from './user.service'; // constructor(private users: UserRepository, private mailer: MailerService) const users = { create: vi.fn(async (data) => ({ id: 1, ...data })) }; const mailer = { send: vi.fn() }; afterEach(() => MeghTest.clean()); it('sends a welcome mail', async () => { const service = MeghTest.getProvider(UserService, [users, mailer]); await service.register('a@example.com'); expect(mailer.send).toHaveBeenCalledWith('a@example.com', 'Welcome!'); }); ``` How this works matters: - Every call builds a **new** instance. The stand-ins are used for that instance only; nothing is registered in the shared container, so other classes and other tests never see them. - Parameters you don't pass are resolved from the container as usual. - Only constructor parameters are matched. For `inject()` fields, register the stand-in with `MeghContainer.set(MailerService, fake)` before resolving the class. `MeghTest.clean()` drops every built instance in the container, so the next test starts fresh. Values set for tokens and strings are kept. To remove those too, so a mock registered with `MeghContainer.set(TOKEN, mock)` doesn't leak into the next test, pass `all: true`: ```ts afterEach(() => MeghTest.clean({ all: true })); ``` `MeghContainer.reset({ all: true })` does the same. Anything else set on a token, such as a database client an `onInit` hook registered, is removed as well, so use it between tests that build their own app. See [Testing in Dependency Injection](/core-concept/dependency-injection#testing). ::: info Before 0.6.5 Stand-ins were registered in the shared container, and a class that was already built was returned as-is, ignoring them. ::: ## Route tests `MeghTest.from(app)` wraps an app so you can send requests to it. Requests go through Fastify's `inject()`, so no port is opened: ```ts [test/users.e2e-spec.ts] import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { MeghTest, TestApplication } from '@meghjs/core'; import app from '../src/app'; describe('Users API', () => { let http: TestApplication; beforeAll(async () => { http = MeghTest.from(app); }); afterAll(() => http.close()); it('lists users', async () => { const res = await http.get('/users'); expect(res.statusCode).toBe(200); expect(res.json()).toBeInstanceOf(Array); }); it('rejects an invalid body', async () => { const res = await http.post('/users', { payload: { email: 'nope' } }); expect(res.statusCode).toBe(400); }); }); ``` This uses the app exported from `src/app.ts`, so middleware, authentication, exception filters and other `use*` settings apply. Keep `app.run()` in `src/serve.ts`, as `megh new` does, so importing the app doesn't start it. `TestApplication` has `get`, `post`, `put`, `patch`, `delete` and `options`. Each takes a URL and Fastify's inject options (`payload`, `headers`, `query`, `cookies`, ...). The response has `statusCode`, `headers`, `body` (a string) and `json()`. ```ts await http.get('/me', { headers: { authorization: `Bearer ${token}` } }); await http.get('/users', { query: { page: '2' } }); ``` It also has: | Member | Does | | --- | --- | | `http.app` | The app under test | | `http.ready()` | Resolves once the app has started; rejects with the startup error | | `http.close()` | Shuts the app down, like `app.close()` | | `http.getController(Controller, deps?)` | Same as `MeghTest.getController` | ### How the app starts `MeghTest.from(app)` starts the app the way `app.run()` does, without opening a port or installing SIGTERM/SIGINT handlers: 1. Environment and config schemas are validated. 2. The OpenAPI document is set up, if you called `useOpenApi()`. 3. `onInit` hooks run (MeghORM connects here). 4. Controllers are mapped, including those found by `useControllers({ auto: true })`, then inline routes (`app.mapGet`, ...). 5. Rate limiting, the error handler and Socket.IO are set up, and `@Listener` classes start. 6. `onReady` hooks run. Each request waits for this, and a startup error (a failing `onInit` hook, a class that isn't an `@Controller`) is thrown by every request and by `http.ready()`. After `from()`, the app counts as started: `onInit()`, `onReady()` and `run()` throw, as they do after `run()`. Scheduled tasks are found and registered but **not started**, so cron jobs don't fire in the middle of a test. Test a task by calling its method (build it with `MeghTest.getProvider`), or pass `scheduler: true` to start them; `close()` stops them: ```ts const http = MeghTest.from(app, { scheduler: true }); ``` Calling `from()` again for the same app is safe: it returns another client for the same started app, and nothing is mapped twice. Calling it after `app.run()` sends requests to the running app. ### Error details Vitest sets `NODE_ENV` to `test`, which Megh treats as production, so a 5xx response would say only "Internal Server Error". Under `MeghTest`, 5xx responses include the error's `message`, `error` (its name) and the first lines of its `stack`, as in development, so a failing test shows why: ```ts const res = await http.get('/crash'); res.json(); // { code: 500, status: 'Error', message: 'db down', error: 'Error', stack: [...] } ``` Only the error response changes: `app.isDevelopment()` stays `false`. To test the response production sends, pass `errorDetails: false`: ```ts const http = MeghTest.from(app, { errorDetails: false }); ``` ### Just a few controllers `MeghTest.createTestApplication` builds a fresh app with only the controllers you list, started like `from()`. It takes the same `errorDetails` and `scheduler` options: ```ts const http = MeghTest.createTestApplication({ controllers: [UserController] }); const res = await http.get('/users'); await http.close(); ``` Use `MeghTest.from(app)` when you need middleware, a database, or the rest of your app's setup. ::: info 0.8.0 and earlier `from()` mapped only the controllers listed in `useControllers([...])`: inline routes answered 404, and `onInit`/`onReady` hooks, auto-discovered controllers, OpenAPI and Socket.IO were skipped. Calling `from()` twice failed, `createTestApplication` gave no way to `close()` the app, and 5xx details were hidden. ::: ## Teardown Call `http.close()` (or `app.close()`) after the tests. It closes the Fastify instance, scheduled tasks, queue workers, listeners, messaging, the cache and the database connection (through the `onClose` hooks), so the test process can exit: ```ts afterAll(() => http.close()); ``` ## Events, messages and jobs `Messaging.fake()` records events, messages and queue jobs instead of sending them. Listeners and workers don't run, and no broker is needed. Assert on what the code did, then call `Messaging.restore()`: ```ts import { Messaging } from '@meghjs/core'; afterEach(() => Messaging.restore()); it('places an order', async () => { const messaging = Messaging.fake(); await orders.place(cart); messaging.expectDispatched(OrderPlaced, (e) => e.payload.total === 42); messaging.expectQueued(EmailQueue, 'receipt'); messaging.expectNotDispatched(OrderCancelled); }); ``` | Assertion | Passes when | | --- | --- | | `expectDispatched(Event, check?)` | An `Event` was dispatched (and passed `check`) | | `expectDispatched(Event, n)` | An `Event` was dispatched exactly `n` times | | `expectNotDispatched(Event, check?)` | No `Event` (passing `check`) was dispatched | | `expectNothingDispatched()` | No event was dispatched | | `expectPublished(type, check?)` | A message of `type` was sent with `Messaging.publish()` | | `expectQueued(Queue, jobName?, check?)` | A job was added to `Queue` (a class or a queue name) | | `expectNothingQueued()` | No job was added to any queue | `Event` is the event class, or the wire type of a distributed event. A failed assertion throws a `MessagingAssertionError` that lists what was recorded, so it works with any test runner. `dispatched(Event, check?)`, `published(type, check?)` and `queued(Queue, jobName?, check?)` return the recorded items themselves. `all()` returns everything, and `clear()` forgets it. The fake records every dispatch, local events included. To run the listeners instead, don't fake: on the default `memory` transport, distributed events are delivered in-process. `@Listener` classes start when `MeghTest.from()` (or `app.run()`) starts the app, and stop on `close()`. Without an app, start them with `await startListeners()` (and `await stopListeners()` after). `await Messaging.whenIdle()` waits until the events are handled. ## Queues in tests Queues run on the `memory` transport by default, so tests need no Redis. Jobs run asynchronously in-process and honour `delay`. To run each job inside `add()` instead, ignoring `delay`, use `sync`: ```ts import { setQueueTransport } from '@meghjs/core'; setQueueTransport('memory', { sync: true }); ``` The transport is picked when a queue is created. If `src/app.ts` calls `useWorker([...])`, its queues are created as soon as the app is imported, so call `setQueueTransport()` before importing it. If your `.env` sets `MEGH_QUEUE_TRANSPORT` or `MEGH_MESSAGING_TRANSPORT`, override it for tests: ```ts [vitest.e2e.config.mts] import swc from 'unplugin-swc'; import { defineConfig } from 'vitest/config'; export default defineConfig({ plugins: [swc.vite()], test: { include: ['test/**/*.e2e-spec.ts'], env: { MEGH_QUEUE_TRANSPORT: 'memory', MEGH_MESSAGING_TRANSPORT: 'memory' }, }, }); ``` Without `sync`, wait for jobs to finish and reset between tests: ```ts import { resetMemoryQueues, waitForMemoryQueues } from '@meghjs/core'; afterEach(() => resetMemoryQueues()); it('sends a welcome mail on signup', async () => { await http.post('/signup', { payload: { email: 'a@example.com' } }); await waitForMemoryQueues(); expect(mailer.sent).toHaveLength(1); }); ``` ## Environment `MeghTest` doesn't change `NODE_ENV`. Vitest sets it to `test`, which Megh treats as production: `app.isDevelopment()` is false, so development-only features stay off. 5xx responses still carry their details under `MeghTest`; see [Error details](#error-details). `.env` is loaded in tests the same way as in the app. See [Configuration](/core-concept/configuration). --- # Logging Source: https://meghjs.github.io/advanced/logging `LoggerService` wraps [pino](https://getpino.io). Inject it anywhere: ```ts [services/orders.service.ts] import { AppService, LoggerService } from '@meghjs/core'; @AppService export class OrdersService { constructor(private readonly logger: LoggerService) {} place(order: Order) { this.logger.info('order placed', { orderId: order.id }); } fail(error: Error) { this.logger.error('order failed', error); // logged as { err } } } ``` ## Output format | `NODE_ENV` | Output | |------------|--------| | `development`, with `pino-pretty` installed | Pretty, colored lines | | anything else, including unset | One JSON object per line | Install `pino-pretty` as a dev dependency for readable local logs: ```sh npm i -D pino-pretty ``` Megh's own logs (events, queues, workers, scheduler) go through the same logger, so they share its format and level. ## Configuring All `LoggerService` instances share one pino root. Configure it once at startup: ```ts import { LoggerService } from '@meghjs/core'; LoggerService.configure({ level: 'debug' }); // also: pretty, destination const log = LoggerService.child({ module: 'billing' }); log.info('invoice sent'); ``` ## Request IDs Every request gets an ID. Megh reuses the incoming `x-request-id` header when it is short and log-safe (letters, digits, `_ . : -`, at most 128 characters), so an ID set by a proxy or the calling service carries through; otherwise it generates a UUID. The ID is sent back in the `x-request-id` response header. Log lines written while a request is handled get a `reqId` field, from `LoggerService` and from Megh's own logs alike: ```json {"level":30,"reqId":"7f9c…","msg":"charging card"} ``` Read the ID anywhere in the request's call chain with `getRequestId()`, for example to pass it to another service: ```ts import { getRequestId } from '@meghjs/core'; await fetch(url, { headers: { 'x-request-id': getRequestId() ?? '' } }); ``` Change the header or the generator, or turn request IDs off, when you create the app: ```ts MeghApplication.getApp({ requestId: { header: 'x-correlation-id', generate: () => nanoid() }, }); MeghApplication.getApp({ requestId: false }); ``` `server.genReqId` in the Fastify options overrides Megh's generator. ## Fastify request logs Megh does not pass this logger to Fastify. To route Fastify's request logs through the same pino instance, use `LoggerService.getPino()`. --- # Tracing Source: https://meghjs.github.io/advanced/tracing `app.useTracing()` creates an [OpenTelemetry](https://opentelemetry.io) span for every request, so you can follow a request through your services in Jaeger, Grafana Tempo, Honeycomb, Datadog or any other OTLP backend. Megh only creates spans, through `@opentelemetry/api`. You choose the SDK and where the spans are sent. ## Setup Install the API, the Node SDK and an exporter: ```bash npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http ``` Start the SDK before the app, in its own file: ```ts // src/tracing.ts import { NodeSDK } from '@opentelemetry/sdk-node'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; const sdk = new NodeSDK({ serviceName: 'orders-api', traceExporter: new OTLPTraceExporter(), // OTEL_EXPORTER_OTLP_ENDPOINT, default http://localhost:4318 }); sdk.start(); process.on('SIGTERM', () => sdk.shutdown()); ``` ```ts // src/app.ts import './tracing'; import { Megh } from '@meghjs/core'; const app = Megh.createApplication(); app.useTracing({ ignore: ['/health', '/ready'] }); app.useControllers([OrderController]); app.run(4000); ``` To see spans without a backend, use the SDK's `ConsoleSpanExporter` as the `traceExporter`; each span is printed when the request ends. ## What a span holds One `SERVER` span per request: | Field | Value | |-------|-------| | Name | `GET /orders/:id`: the method and route pattern, so spans group by route | | `http.request.method` | `GET` | | `http.route` | `/orders/:id` | | `url.path` | `/orders/42` (no query string) | | `http.response.status_code` | `200` | | `server.address`, `user_agent.original` | From the request | A span is marked as an error when the handler throws (with the exception recorded) or the response is a 5xx. If the request has a `traceparent` header, the span continues that trace, so a call from another traced service shows up as one trace. ## Options | Option | Default | Description | |--------|---------|-------------| | `name` | `"megh"` | Tracer name | | `ignore` | `[]` | Paths not traced: exact strings or regular expressions, e.g. `['/health', /^\/assets\//]` | Calling `useTracing()` twice, or after `app.run()`, throws. Without `@opentelemetry/api` installed, it throws with the install command. ::: info Not traced yet Spans cover HTTP requests only. Database queries, queue jobs and messaging don't create spans of their own yet. ::: --- # Monitoring Source: https://meghjs.github.io/advanced/monitoring `megh monit` opens a live dashboard for a running app. It shows: - **Current values:** requests per second, p95 latency, 5xx rate, heap, CPU and event loop lag - **Charts** of the last 5 minutes: throughput, latency, memory, CPU and event loop lag, each with a hover tooltip and a table view - **Services** the app turned on (mail, cache, storage, messaging, queues, scheduler, Socket.IO, sessions, tracing and more) - **Health** checks, refreshed every 5 seconds - **Routes** with request counts, 5xx counts and average time - **Logs**, streamed live: every line the Megh logger writes, plus one line per request. Filter by level or text, pause and clear. ## Setup Turn the monitor on in the app: ```ts const app = Megh.createApplication(); app.useMonitor(); app.useControllers([OrderController]); app.run(4000); ``` Start the app, then in another terminal: ```bash npx megh monit --open ``` The dashboard runs at `http://127.0.0.1:4545` and watches `http://localhost:4000` (or `$PORT`). Point it elsewhere with `--url`. ## Watching a remote app Without a token, the app answers the monitor only from its own machine, and `useMonitor()` refuses to start in production. Set the same token on both sides to watch an app elsewhere: ```ts app.useMonitor({ token: process.env.MEGH_MONITOR_TOKEN }); ``` ```bash MEGH_MONITOR_TOKEN=... npx megh monit --url https://api.example.com ``` The dashboard itself listens on `127.0.0.1` and sends the token to the app for you, so the token never reaches the browser. ::: warning The monitor shows routes, log lines and service settings. Use a long random token, and serve the app over HTTPS when you watch it remotely. ::: ## Options `app.useMonitor(options)`: | Option | Default | Description | |--------|---------|-------------| | `path` | `/_megh/monitor` | Where the endpoints live | | `token` | `MEGH_MONITOR_TOKEN` | Bearer token the dashboard must send | | `history` | `300` | Seconds of metrics kept for the charts | | `logBuffer` | `500` | Log lines kept for dashboards that connect later | | `logRequests` | `true` | Add one log line per request | `megh monit`: | Flag | Default | Description | |------|---------|-------------| | `--url ` | `MEGH_MONITOR_URL`, then `http://localhost:$PORT` (4000) | The app's address | | `-p, --port ` | `4545` | Dashboard port | | `--host ` | `127.0.0.1` | Dashboard interface | | `--token ` | `MEGH_MONITOR_TOKEN` | The app's monitor token | | `--path ` | `/_megh/monitor` | The app's monitor path | | `-o, --open` | | Open the dashboard in the browser | ## Endpoints The app serves two routes, which you can also read from your own tools: | Route | Returns | |-------|---------| | `GET /_megh/monitor` | A snapshot: app info, services, routes, health, metric history and recent logs | | `GET /_megh/monitor/stream` | Server-Sent Events: `metrics` every second and `log` for each line | Metrics and logs are kept in memory in each process, so with several replicas, each one reports only itself. --- # Health Checks Source: https://meghjs.github.io/advanced/health `app.useHealth()` adds two routes for load balancers, Kubernetes probes and uptime monitors: | Route | Answers | Use it for | |-------|---------|------------| | `GET /health` | `200 { "status": "ok" }` while the process serves requests | Liveness: restart the process when it stops answering | | `GET /ready` | `200` when every check passes, `503` when one fails | Readiness: stop sending traffic until dependencies are back | ```ts app .useMeghORM({ dialect: 'postgres', url: process.env.DATABASE_URL }) .useHealth({ checks: { redis: () => redis.ping(), }, }); ``` ```json // GET /ready { "status": "ok", "checks": { "database": { "status": "up", "durationMs": 2 }, "redis": { "status": "up", "durationMs": 1 } } } ``` Megh ORM registers the `database` check itself (`select 1`), and `useMessaging()` a `messaging` check that pings the broker, so you only add checks for the services you connect to yourself. ## Checks A check is a function. It passes unless it throws, rejects or returns `false`. Checks run concurrently, and one that takes longer than `timeout` counts as down. ```ts app.addHealthCheck('payments-api', async () => { const res = await fetch('https://payments.internal/ping'); return res.ok; }); ``` Plugins add checks with `ctx.addHealthCheck(name, check)`, the same way Megh ORM does. When a check fails, `/ready` answers 503 with the check marked `down`. The failure reason is included as `error` only when `NODE_ENV=development`, since it can describe internal hosts or credentials. ## Options | Option | Default | | |--------|---------|---| | `path` | `/health` | Liveness route | | `readyPath` | `/ready` | Readiness route | | `checks` | `{}` | Checks to add, by name | | `timeout` | `5000` | Milliseconds before a check counts as failed | Call `useHealth()` before `run()`. The routes are hidden from the OpenAPI document and skip middleware (including global `useMiddlewares`) and `@Authorized`, so probes still answer behind an API key check. Keep them off the public internet if the check names are sensitive. ## Kubernetes ```yaml livenessProbe: httpGet: { path: /health, port: 4000 } readinessProbe: httpGet: { path: /ready, port: 4000 } ``` --- # Deployment Source: https://meghjs.github.io/production/deployment A Megh app is a plain Node.js program. You compile it to JavaScript, set `NODE_ENV=production`, and run the entry file with Node 22 or newer. ## Building ```bash npx megh build # or: npm run build in a scaffolded app ``` `megh build` compiles the project with the project's own `tsc`: - It uses `tsconfig.build.json`, else `tsconfig.json` (with a warning), or the file passed with `-p, --project `. - It deletes the output folder (`outDir`, default `dist`) first. - It copies every non-TypeScript file under `src/` (JSON, templates, images…) into the output folder. Dotfiles are skipped. - It fails if `typescript` is not installed in the project. The output is **CommonJS**, one `.js` file per source file: `src/serve.ts` becomes `dist/serve.js`, and `src/controllers/` becomes `dist/controllers/`. Megh itself ships only a CommonJS build. The scaffold's `tsconfig.json` sets `"module": "nodenext"`, which compiles to CommonJS as long as `package.json` has no `"type": "module"`. Older projects with `"module": "CommonJS"` also build CommonJS, but fail on TypeScript 6; see [the FAQ](../reference/faq.md#megh-build-fails-after-upgrading-to-typescript-6). You can also run `tsc -p tsconfig.build.json` directly. You then have to copy any assets yourself. ## Starting ```bash npx megh start # or: npm start ``` `megh start` runs the compiled entry with `node --enable-source-maps`. It sets `NODE_ENV=production` unless `NODE_ENV` is already set, and forwards `SIGINT` and `SIGTERM` to the app. It looks for the entry in this order: 1. `--entry ` 2. `megh.entry` in `package.json` 3. `main` in `package.json` (a `src/*.ts` path is mapped to the output folder) 4. `serve.js`, `server.js`, `main.js`, `index.js` in the output folder If none exists it stops with `No compiled entry file found (tried …)` and asks you to run `megh build` first or pass `--entry`. `megh start` is optional. Running Node yourself works the same: ```bash NODE_ENV=production node --enable-source-maps dist/serve.js ``` Start the app from the project root. Megh reads `.env` and resolves auto-discovered folders (`src/controllers`, `src/tasks`) relative to the current working directory. ## Environment | Variable | Effect | |----------|--------| | `NODE_ENV` | Anything other than `development` (including unset) is production | | `HOST` | Interface `run()` listens on. Default `0.0.0.0` | | `PORT` | Port `run()` listens on when you don't pass one. Default `4000` | | `LOG_LEVEL` | Log level. Default `info` | | `MEGH_DOTENV` | `false` stops Megh loading `.env` | | `DATABASE_URL`, `DB_*` | MeghORM connection | In production mode (`app.isDevelopment()` is `false`): - 5xx responses say only `Internal Server Error`, without the message, data or stack. See [Error Handling](/core-concept/error-handling). - Logs are JSON lines on stdout, even if `pino-pretty` is installed. See [Logging](/advanced/logging). - `/ready` leaves out the reason a health check failed. - Anything you put behind `if (app.isDevelopment())`, such as the OpenAPI docs in the scaffold, is off. ::: warning Keep `NODE_ENV=development` out of a deployed `.env` Values already in the environment win over `.env`. If a `.env` in the working directory sets `NODE_ENV=development` and nothing else sets `NODE_ENV`, the app runs in development mode and sends error details to clients. Projects created with 0.6.0 or later leave `NODE_ENV` out of `.env`; older projects should remove it. Don't ship `.env` to production; set real environment variables instead. ::: `app.run()` listens on `PORT`, else `4000`, unless you pass a port. A port passed to `run()` wins. An invalid `PORT` stops startup with an error. See [Configuration](/core-concept/configuration) for typed config classes. ## Health checks Turn on `/health` and `/ready` for load balancers and orchestrators: ```ts app.useHealth(); ``` Point liveness probes at `/health` and readiness probes at `/ready`. Both skip middleware and `@Authorized`. See [Health Checks](/advanced/health). ## Graceful shutdown On `SIGTERM` or `SIGINT`, `run()` stops accepting connections, waits for in-flight requests, stops scheduled tasks and workers, runs `onClose` hooks and exits with code 0. It exits with code 1 if that takes longer than `shutdownTimeout` (default 10 seconds). See [Application: Shutting down](/getting-started/application#shutting-down). Give the app at least `shutdownTimeout` before your platform kills it. In Kubernetes, `terminationGracePeriodSeconds` defaults to 30 seconds, which is enough for the default. ## Docker A multi-stage build compiles with dev dependencies and ships only production ones: ```dockerfile [Dockerfile] FROM node:22-slim AS build WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM node:22-slim WORKDIR /app ENV NODE_ENV=production COPY package*.json ./ RUN npm ci --omit=dev COPY --from=build /app/dist ./dist USER node EXPOSE 4000 CMD ["node", "--enable-source-maps", "dist/serve.js"] ``` ```text [.dockerignore] node_modules dist .megh .env .env.* coverage ``` - Run `node` directly in `CMD` (exec form), so `SIGTERM` reaches the app. - `WORKDIR` matters: it is the working directory Megh resolves paths from. - Optional integrations are peer dependencies. Anything the app calls in production (`@fastify/cors`, `@fastify/swagger`…) must be in `dependencies`, not `devDependencies`, or `npm ci --omit=dev` leaves it out and the app throws at startup. ## Process managers Without containers, keep the app running with a process manager. **PM2**: ```bash NODE_ENV=production pm2 start dist/serve.js --name api --kill-timeout 15000 ``` Set `--kill-timeout` above `shutdownTimeout`; PM2's own default is shorter. **systemd**: ```ini [/etc/systemd/system/api.service] [Service] WorkingDirectory=/srv/api ExecStart=/usr/bin/node --enable-source-maps dist/serve.js Environment=NODE_ENV=production EnvironmentFile=/etc/api.env Restart=on-failure User=api [Install] WantedBy=multi-user.target ``` systemd sends `SIGTERM` on stop and waits 90 seconds by default. ## Migrations on deploy Run migrations once per deploy, before the new version takes traffic, for example as a release step, a Kubernetes `Job` or an init container. In the runtime image, run the built migrations with `megh migrate --compiled`. It loads the `.js` files from `dist/` (the tsconfig `outDir`), so it needs `@meghjs/cli` installed but not the sources or a writable project folder. Without a `src/` folder this is the default, so plain `megh migrate` works there too. Set `DATABASE_URL`. See [Database Commands](/cli/database). ```bash npx megh migrate --compiled npx megh migrate:status --compiled ``` Where the sources are available (the build stage, a CI job), `megh migrate` compiles `src/` with SWC instead. `megh migrate --seed` and `megh db:seed` refuse to seed when `NODE_ENV=production` unless you add `--force`. To migrate without `@meghjs/cli` in the image, compile a small script with the app. It uses the same connection settings as `useMeghORM()`: ```ts [src/migrate.ts] import path from 'path'; import { Migrations, createDatabase, resolveDatabaseOptions } from '@meghjs/core'; async function main() { const db = createDatabase(resolveDatabaseOptions()); try { const folder = path.join(__dirname, 'database/migrations'); const ran = await new Migrations(db, { folder }).latest(); console.log(ran.length ? `Migrated: ${ran.join(', ')}` : 'Nothing to migrate'); } finally { await db.destroy(); } } main().catch((err) => { console.error(err); process.exit(1); }); ``` ```bash node dist/migrate.js ``` ## Scheduled tasks and replicas Every replica that calls `useScheduler` runs the scheduler, but a `@Cron` or `@Interval` job runs once per tick across all of them. The replicas agree through a lock in Redis (with the redis [messaging](/advanced/messaging) transport) or in the `megh_locks` table (with Megh ORM and `npx megh make:messaging`). Set up one of the two before scaling out: without either, each replica runs every job and Megh logs a warning. For work that must happen exactly once, enqueue a job from the task and let a [queue](/advanced/queue) worker process it. See [Scheduler: Multiple replicas](/advanced/scheduler#multiple-replicas). ## Messaging and queues In production, set a broker for [messaging](/advanced/messaging) and [queues](/advanced/queue). The in-process `memory` transport loses messages on restart and never reaches other replicas, so Megh refuses it for distributed listeners and for queues that didn't ask for it: ```sh MEGH_MESSAGING_TRANSPORT=redis MEGH_MESSAGING_URL=rediss://default:secret@redis.internal:6379 ``` Remote broker URLs must use TLS (`rediss://`, `amqps://`) unless you set `allowInsecure: true`. --- # CLI Source: https://meghjs.github.io/cli/basic Install the CLI globally, or run it with `npx`: ```sh npm i -g @meghjs/cli ``` ## Command Overview | Command | Alias | Description | |---------|-------|-------------| | `new` | | Create a new application | | `add` | | Add views, a Vite frontend or Inertia to an existing project | | `serve` | | Start the dev server with watch + rebuild | | `build` | | Compile using `tsconfig.build.json` | | `doctor` | | Check Node.js, `@meghjs/core`, `reflect-metadata` and the decorator settings | | `upgrade` | | Move the project to a new Megh version: packages, codemods, manual steps | | `self-update` | | Update the globally installed CLI | | `make:model` | `m:m` | Create a model: a plain class, a MeghORM model with `--orm` (columns from its migrations), or a TypeORM entity with `--typeorm` | | `sync:model` | `s:m` | Sync an existing model's columns with its migrations (was `update:model`) | | `make:resource` | `m:r` | Create a REST resource for a model: DTOs, CRUD service and controller | | `make:controller` | `m:c` | Create a controller | | `make:service` | `m:s` | Create a service | | `make:config` | `m:cnf` | Create a config class | | `make:middleware` | `m:mlwr` | Create a middleware | | `make:mail` | `m:mail` | Create a Mailable in `src/mail/` | | `make:event` | `m:ev` | Create an event in `src/events/` | | `make:listener` | `m:lsn` | Create an event listener in `src/listeners/` (`--event` to type it) | | `make:queue` | `m:q` | Create a queue with a job handler in `src/queues/` | | `make:worker` | `m:w` | Create a worker for a queue in `src/workers/` | | `make:task` | `m:task`, `make:scheduler` | Create a scheduled task in `src/tasks/` (`--cron`, `--interval`) | | `make:agent` | `m:agent` | Create an `@Agent` in `src/agents/` (`--provider`, `--model`, `--tags`) | | `make:dto` | `m:dto` | Create a DTO in `src/dtos/` | | `make:class` | `m:cls` | Create a plain class in `src/classes/` | | `make:view` | `m:v` | Create a `.megh.html` view (or `-c` component) in `views/` | | `make:page` | `m:p` | Create an Inertia page (Vue, React or Svelte) in `frontend/pages/` | | `make:test` | `m:t` | Create a unit test (`.spec.ts`) for an existing file | | `make:migration` | `m:mig` | Create a database migration | | `make:messaging` | | Create the migration for the messaging tables (outbox, scheduler locks, dedupe) | | `make:seeder` | `m:sd` | Create a database seeder | | `make:factory` | `m:f` | Create a model factory with Faker values | | `migrate` | | Run pending migrations (`--seed` to seed afterwards) | | `migrate:status` | | Show which migrations have run | | `migrate:rollback` | | Undo the last migration (`--step ` for more) | | `migrate:reset` | | Undo every migration | | `migrate:refresh` | | Undo every migration, then run them all again (`--seed` too) | | `db:seed` | | Run the seeders (`--seeder ` for one) | | `messaging:failed` | | List messages that failed after their retries, or `retry` / `discard` them. See [Messaging](/advanced/messaging#retries-and-dead-letters) | | `scaffold:domain` | `sc:domain` | Create the tables and models (or resources) of a business domain | | `scaffold:auth` | `sc:auth` | Add sign-up and sign-in with JWTs and/or API keys, optionally with roles | | `scaffold:rbac` | `sc:rbac` | Add roles and permissions to an app's users | | `template:list` | `templates` | List the model templates | | `make:agents` | | Write `AGENTS.md` (and a `CLAUDE.md` that imports it) for coding agents | | `make:hash` | | Print a value's hash, or check a value against a hash (`--verify`). See [Hashing a value](#hashing-a-value) | Every `make:*` command that writes a file takes `-f` / `--force` to overwrite an existing file. The generators except `make:model` and the database ones (`make:migration`, `make:messaging`, `make:seeder`, `make:factory`) also write a unit test next to the file; pass `--notest` (or `-nt`) to skip it. See [Tests](/cli/generators#tests). `make:model` and `make:resource` also build the table from a [template](/cli/scaffold/templates) with `--template` or `--fields`. ## Pages | Page | Commands | |---|---| | [Generators](/cli/generators) | `make:resource`, `make:controller`, `make:service`, `make:model`, `sync:model`, `make:middleware`, `make:config`, `make:mail`, `make:event`, `make:listener`, `make:queue`, `make:worker`, `make:task`, `make:agent`, `make:dto`, `make:class`, `make:test` | | [Database Commands](/cli/database) | `make:migration`, `make:messaging`, `migrate*`, `make:seeder`, `db:seed`, `make:factory` | | [Messaging](/advanced/messaging#retries-and-dead-letters) | `messaging:failed` | | [Scaffold](/cli/scaffold/) | `--template`, `--fields`, `scaffold:domain`, `scaffold:auth`, `scaffold:rbac`, `template:list` | ## Version and info ```sh npx megh -v # the CLI version, e.g. 0.8.0 (also --version) npx megh --info # the logo, CLI, Node.js and OS versions, and the project's Megh packages (also -i) ``` The logo appears only with `--info`; `-v`, `--help` and the other commands print without it. `--info` also shows the installed `@meghjs/core`, `@meghjs/data` and TypeScript versions when run inside an app: paste it into a bug report. ## Application ```sh npx @meghjs/cli new myapi ``` You are prompted for a package manager and optional features: OpenAPI docs, CORS and MeghORM. With MeghORM you also pick the database. Add [Mail](/advanced/mail#setting-it-up), Scalar UI or the [`@meghjs/data`](/advanced/database) plugin afterwards. Non-interactively: ```sh npx @meghjs/cli new myapi --yes --database postgres # also: mysql, sqlite, mssql ``` `--database` (or the `orm` feature, which defaults to SQLite) installs the driver, adds `app.useMeghORM()` to `src/app.ts`, writes `DATABASE_URL` to `.env` and creates `src/database/migrations/`. For a server-rendered app, pass `--mvc`: ```sh npx @meghjs/cli new myapp --mvc ``` It adds `app.useViews()` and `app.useMethodOverride()` to `src/app.ts`, a layout in `views/layouts/app.megh.html`, a page in `views/pages/home.megh.html`, and a `HomeController` that renders it with `Results.View('pages.home', ...)`. Add more pages with [`make:view`](/cli/generators#view). See [Views](/advanced/views). `--mvc` can't be combined with `--minimal`. For a single-page app with [Inertia.js](/advanced/inertia), pass `--inertia` and optionally the frontend framework (`vue` by default, `react` or `svelte`): ```sh npx @meghjs/cli@next new myapp --inertia # Vue npx @meghjs/cli@next new myapp --inertia react ``` It adds `useViews()`, `useVite()`, `useSession()` and `useInertia()` to `src/app.ts`, and: - `views/app.megh.html`: the HTML document, with `@vite` and `@inertia` - `frontend/app.ts` (`app.tsx` for React): the Inertia client entry - `frontend/pages/Home.vue` (`.tsx`, `.svelte`): the page `HomeController` returns with `Results.Inertia('Home', ...)` - `frontend/css/app.css` and `frontend/tsconfig.json` - `vite.config.mts`, which builds `frontend/` into `public/build` - a random `SESSION_SECRET` in `.env` `megh serve` builds the frontend too (see below), and `npm run build` runs `vite build` before `megh build`. Add pages with [`make:page`](/cli/generators#inertia-page). `--inertia` can't be combined with `--minimal` or `--mvc`. `--mvc` and `--inertia` run the same steps as [`megh add`](#add-to-a-project), so a project created plain and upgraded later ends up the same. ## Add to a project Start small and add layers as the app grows. Each step only adds files and setup. It never moves your code: ```sh npx megh add views # server-rendered .megh.html in views/ npx megh add vite # browser code in frontend/, built by Vite npx megh add inertia [vue|react|svelte] # Inertia pages in frontend/pages/ (adds vite) ``` | Command | Adds | | --- | --- | | `add views` | `views/layouts/app.megh.html`, `useViews()` and `useMethodOverride()` | | `add vite` | `frontend/` (`app.ts`, `css/`, `tsconfig.json`), `vite.config.mts`, `useVite()`, `vite` and `@fastify/static`, `public/build/` in `.gitignore`. A layout gets `@vite('frontend/app.ts')` | | `add inertia` | Vite if missing, the framework's packages and Vite plugin, `frontend/app.ts` (the Inertia entry), `frontend/pages/Home`, `views/app.megh.html`, `useViews()`, `useSession()` (with `SESSION_SECRET`), `useInertia()` | Setup goes into `src/app.ts` before `app.useControllers(...)`, or before the first route in a minimal app. The commands are safe to run again: what's already there is kept, and nothing changes the second time. Files Megh generated, such as the plain `frontend/app.ts` and `vite.config.mts` from `add vite`, are replaced when you haven't edited them. A `vite.config` you changed is patched in place (plugin and entry added). A `frontend/app.ts` with your code is never overwritten: move it, or pass `--force`. Changes to existing files are shown as a diff before they're kept. Pass `-y` to skip the prompt, or `--dry-run` to only see them. Run your package manager's install afterwards when dependencies were added. The project also gets an `AGENTS.md`: instructions for coding agents such as Claude Code, Codex, Cursor and Copilot. It lists the project's commands, where code goes, and the Megh rules that compile cleanly but fail at runtime (register new controllers, give every DTO property a validator, and so on). A `CLAUDE.md` containing `@AGENTS.md` makes Claude Code read the same file. Edit both freely: they're yours. To add them to an existing project, run `npx megh make:agents` (`--force` replaces an existing `AGENTS.md`; a `CLAUDE.md` of your own is never replaced). The new project is put under git with `git init`, unless git isn't installed or the folder is already inside a repository. Pass `--skip-git` (or set `MEGH_SKIP_GIT=1`) to skip it. Then: ```sh cd myapi npm run start:dev ``` ## Development Server ```sh npx megh serve ``` Compiles `src/` with SWC into `.megh/build/`, starts the app and restarts it on change. The entry point comes from `megh.entry` in `package.json`, falling back to `main`; an entry inside `dist/` (`dist/serve.js`) runs from `.megh/build/`. `.megh/` belongs to Megh: `serve` recreates `.megh/build/` on every start, the folder is safe to delete, and it should be in `.gitignore` (`megh new` adds it, `megh upgrade` adds it to existing projects). `dist/` only ever holds what `megh build` produced, so `megh build` and `megh serve` can run at the same time. Auto-registered controllers and scheduled tasks are loaded from `.megh/build/` under `megh serve` (it passes the folder to the app as `MEGH_BUILD_DIR`) and from `dist/` under `megh start`. When the project has a `vite.config` file (after `megh add vite` or `add inertia`), `serve` also starts Vite's dev server. Its output is prefixed `[VITE]`. Edits in `frontend/` then reach the open page with hot module replacement: no reload, and component state is kept. See [Vite](/advanced/vite#hot-module-replacement). | Option | Effect | | --- | --- | | `--no-hmr` | Run `vite build --watch` instead. Pages load the built files; reload to see changes | | `--no-vite` | Don't run Vite; run it yourself | A `vite.config` without the `megh()` plugin from `@meghjs/core/vite` gets `vite build --watch`, and `serve` says how to turn on HMR. ## Build ```sh npx megh build ``` Removes the output folder (`outDir`, usually `dist/`) and compiles the project with `tsconfig.build.json`. ## Doctor ```sh npx megh doctor ``` Checks Node.js, `@meghjs/core`, `reflect-metadata` and the decorator settings in `tsconfig.json`, and exits with 1 if a check fails. It also says when a newer Megh is out, for the project (run `megh upgrade`) and for the CLI (run `megh self-update`). It asks npm at most once a day and stays quiet when offline. Set `MEGH_NO_UPDATE_CHECK=1` to turn that off. ## Upgrade ```sh npx megh upgrade # to the latest release npx megh upgrade 0.8.0 # to a given version npx megh upgrade --tag next # to the latest prerelease npx megh upgrade --dry-run # show what would change, change nothing ``` `megh upgrade` moves a project to a new Megh version: 1. It refuses to run with uncommitted changes, so the upgrade is one diff you can review. `--force` runs it anyway (also outside git). 2. It finds the target version: the one you pass, else npm's `latest` tag (`--tag next` for prereleases). 3. It runs the codemods of every release between the project's version and the target, oldest first. A codemod only changes code it fully understands, keeps your formatting, and changes nothing on a second run. 4. It moves every `@meghjs` package the project depends on (`core`, `cli`, `ai`, `mcp`) to the target with your package manager (npm, pnpm, yarn or bun, from `packageManager` or the lockfile), and adds or removes the packages the release changed. Upgrading to 0.8.0 removes `ioredis`, `bullmq` and `kafkajs` unless your `src/` imports them. 5. It shows the diff of each changed file, then lists the manual steps: what it couldn't change safely, each with a link to its section of the upgrade guide. In the code, those spots get a `// TODO(megh-upgrade):` comment. | Option | Description | |--------|-------------| | `[version]` | The version to upgrade to, e.g. `0.8.0` or `0.8.0-next.2` | | `--tag ` | The npm tag to upgrade to: `latest` (default) or `next` | | `--dry-run` | Show the changes and the install commands, write and install nothing | | `-f, --force` | Run with uncommitted changes | | `--from ` | Run the codemods as if the project were on this version, e.g. after a partial upgrade | | `-y, --yes` | Don't ask before starting | The codemods come with the CLI that runs them. To get a release's own codemods, run that release's CLI: ```sh npx @meghjs/cli@0.8.0 upgrade 0.8.0 ``` A prerelease counts as part of its release: going to `0.8.0-next.2` runs the 0.8.0 codemods. ## Self-update ```sh megh self-update # to the latest release megh self-update --tag next # to the latest prerelease ``` Updates a globally installed `megh` with the package manager that installed it (`npm i -g`, `pnpm add -g`, `yarn global add` or `bun add -g`) and prints the old and new versions. Run through `npx`, there's nothing to update: `npx @meghjs/cli@latest` fetches the version you ask for. A CLI installed in a project moves with `megh upgrade`. ## Hashing a value ```sh megh make:hash < password.txt ``` Prints the hash of a value, for example a password for a seeder, the way the app's [`Hash`](/core-concept/hashing) makes it. Run it in the project: it goes through the project's `@meghjs/core`, so the hash matches what the app makes. Outside a project only scrypt is available. The value comes from the argument, or from stdin when the argument is `-` or left out. A value typed on the command line ends up in your shell history, so pipe it in instead: ```sh megh make:hash < password.txt printf %s "$ADMIN_PASSWORD" | megh make:hash - ``` One trailing newline is removed from stdin. | Option | Effect | | --- | --- | | `--scrypt`, `--bcrypt`, `--argon2` | The driver. Without one, the driver in `src/config/hashing.config.ts` or `app.useHashing({ ... })` when it's written there as a literal, else scrypt | | `--rounds ` | bcrypt cost (4 to 31), or argon2 iterations | | `--verify ` | Check the value against `` instead: prints `match` (exit code 0) or `no match` (exit code 1) | The driver's cost settings are read from the same place as the driver. ```sh megh make:hash --verify '$argon2id$v=19$m=19456,t=2,p=1$...' < password.txt ``` Quote the hash in single quotes so the shell leaves its `$` alone. --- # Generators Source: https://meghjs.github.io/cli/generators The `make:*` commands write new files from templates. Models are read from your migrations, and `make:resource` writes a complete REST API for a model. Most generators also write a unit test next to the file (see [Tests](#tests)). Every `make:*` command takes `-f` / `--force` to overwrite an existing file. ## Folders A plain name goes in the folder for its type. A name with a folder in front is a module: the module folder comes first, then the type folder. | Command | Writes | |---|---| | `make:model user` | `src/models/user.model.ts` | | `make:model users/user` | `src/users/models/user.model.ts` | | `make:controller users/user` | `src/users/controllers/user.controller.ts` | | `make:service users/user` | `src/users/services/user.service.ts` | | `make:resource users/user` | `src/users/{models,dtos,services,controllers}/user.*.ts` | `--root ` replaces the type folder: `make:model users/user --root domain` writes `src/users/domain/user.model.ts`. `useControllers({ auto: true })` finds controllers in every `controllers/` folder under `src/`, so module controllers are registered too. ::: info Before 0.6.3 Nested names wrote `src/models/users/user.model.ts`. Files already there keep working: `make:resource`, `make:factory` and `sync:model` look there when the new location has no file. ::: ## Reviewing changes A generator that would change a file that already exists (with `-f`, or `sync:model`) shows what it is about to do and asks first: ```txt Changes ~ changed src/blog/models/post.model.ts src/blog/models/post.model.ts title!: string; - @Column({ nullable: true, type: "text" }) - body!: string | null; @Column() Can affect: src/blog/services/post.service.ts imports it line 5 uses .body, which is removed ? Apply these changes to 1 existing file? (y/N) ``` - **Changes** lists new files (`+ new`) and changed ones (`~ changed`), with a diff of each changed file. - **Can affect** lists the files that import a changed file, and the lines that use a property or method the change removes or retypes. - Answering no puts everything back, including the new files the command made along the way. A command that only creates new files doesn't ask. `-y` / `--yes` applies without asking; so does running outside a terminal (scripts and CI), which still prints the review. ## Resource ```sh npx megh make:resource user # shorthand npx megh m:r user ``` Generates a complete REST resource for a [Megh ORM](/advanced/orm) model: | File | Contents | |------|----------| | `src/models/user.model.ts` | Reused if it exists; otherwise built from the migration that creates `users` (as `make:model` does) | | `src/dtos/user.dto.ts` | `CreateUserDto`, `UpdateUserDto` (every field optional) and `ListUsersQuery` (`page`, `perPage`) | | `src/services/user.service.ts` | `findAll`, `paginate`, `find`, `findOrFail`, `create`, `update`, `delete` | | `src/controllers/user.controller.ts` | `GET /users`, `GET /users/:id`, `POST /users`, `PUT /users/:id`, `DELETE /users/:id` | | `src/services/user.service.spec.ts` | A test for each service method, with the model's queries replaced by spies | | `src/controllers/user.controller.spec.ts` | A test for each route, with a stand-in service | The DTO validators come from the model's fields and the migration's column types: `varchar(255)` gets `@MaxLength(255)`, an `email` column `@IsEmail()`, nullable columns and columns with a default are optional, and the generated primary key and timestamps are left out. A missing row gives a 404. If there is neither a model nor a migration for the table, nothing is written; create the migration first (`megh make:migration create_users_table`). Use `--table ` when the table name isn't the plural snake_case name, and `-f` to overwrite existing DTO, service and controller files. Nested names work too: `megh m:r admin/user` writes to `src/admin/` and serves `/admin/users`. See [Folders](#folders). If the model is a [TypeORM](/advanced/database) entity instead, the service uses its repository and no DTOs are generated. A model that is a plain class (`make:model` without `--orm`) has no table, so the command stops and says to regenerate it with `make:model user --orm --force`. Register the controller in your app: ```ts app.useControllers([UserController]); ``` ## Controller ```sh npx megh make:controller user # shorthand npx megh m:c user ``` Pass `-r` for a full REST skeleton, and `-m ` to bind it to a model: ```sh npx megh m:c user -m user -r ``` With `-m`, the controller is generated like [`make:resource`](#resource): the model's DTOs, service and model (from its migration) are created if missing, and the controller delegates to the service, which queries the [MeghORM](/advanced/orm) model (`--orm` says so explicitly). To use a [TypeORM](/advanced/database) repository instead, add `--typeorm`. Use `-rt ` to place the file under a different directory, and `--base-path` to emit `@Controller` without a route prefix. ## Service ```sh npx megh make:service user ``` A resource service uses the [Megh ORM](/advanced/orm) model (generated from its migration if it doesn't exist yet): ```sh npx megh make:service user -m user -r ``` To use a [TypeORM](/advanced/database) repository instead, add `--typeorm`: ```sh npx megh make:service user -m user -r --typeorm ``` ## Model ```sh # Plain class npx megh make:model user # Megh ORM model npx megh make:model user --orm npx megh make:model user --orm --table app_users # table name other than "users" # TypeORM entity (with @meghjs/data) npx megh m:m user --typeorm ``` Without a flag, `make:model` writes a plain class, not mapped to a table: ```ts [src/models/user.model.ts] export class User { // Add the fields a User has, e.g. // id!: number; // name!: string; constructor(values: Partial = {}) { Object.assign(this, values); } } ``` If a migration already creates the table, the command says so and suggests `--orm`. ::: warning Before 0.6.5 `make:model user` wrote a Megh ORM model, and `--orm` made a TypeORM entity. Now `--orm` means Megh ORM and `--typeorm` means TypeORM, on `make:model`, `make:controller` and `make:service`. ::: With `--orm`, `make:model` writes a [Megh ORM](/advanced/orm) model. It looks for the model's table (by default the plural snake_case name: `User` → `users`, `BlogPost` → `blog_posts`) in your migrations. If one creates it, the model gets a decorated field for every column, with its type, nullability and value conversion. The primary key, auto-increment, timestamp and soft-delete columns get their own decorators. Later migrations that add, drop or rename columns are taken into account: ```ts // Columns read from the migrations (the table is created in 20260101000000_create_users_table.ts). @Table("users") export class User extends Model { @PrimaryKey() @AutoIncrement() id?: number; @Column() email!: string; @Column({ nullable: true, type: "string" }) name!: string | null; @Column({ type: "boolean" }) is_admin?: boolean; @CreatedAt() created_at?: Date; @UpdatedAt() updated_at?: Date; } ``` Columns the database fills in (auto-increment, defaults, timestamps) are declared with `?`, so `create()` can leave them out. Nullable columns name their type (`type: "string"`), since a `string | null` field's type isn't visible at runtime; [OpenAPI](/microservices/openapi#responses) uses it to document the model. If no migration creates the table, you get a model with an `id` and commented examples to fill in. The migrations are read, not run, so no database is needed. Relations aren't generated; add them yourself. To write the migration too, start from a template or a list of fields (these always build a Megh ORM model, so `--orm` isn't needed); see [Templates and Fields](/cli/scaffold/templates): ```sh npx megh make:model Product --template ecommerce/product npx megh make:resource Ticket --fields "title,body,status:in(open|closed),user_id:cascade" ``` ### Syncing a model After a migration alters the table, bring the model up to date without regenerating it: ```sh npx megh sync:model user npx megh s:m user --dry-run # show the review, write nothing npx megh s:m user --dto # also rewrite src/dtos/user.dto.ts npx megh s:m user --yes # apply without asking ``` It shows the changes and what they affect, and asks before writing (see [Reviewing changes](#reviewing-changes)). It was called `update:model` before 0.6.3; that name (and `u:m`) still works. For a migration such as: ```ts await schema.table("users", (table) => { table.string("phone", 20).nullable(); table.dropColumn("age"); }); ``` `sync:model` adds `@Column({ nullable: true, type: "string" }) phone!: string | null;` after the model's existing columns, removes the `age` field (with its doc comment), and rewrites any field still in the shape `make:model` writes when its type or nullability changed. Only column fields are touched: relations, methods, getters and comments stay as they are. A field you customized (a `name:` mapping, a custom cast, extra options) is kept as written and reported so you can check it. A renamed column shows up as one field removed and one added. The model must be a decorated (`@Table`) model; for an older model with `static table` and `static casts`, regenerate it with `make:model --orm --force`. Without `--dto`, a DTO from `make:resource` is not changed, and the command reminds you it may be out of date. ## Middleware ```sh npx megh make:middleware auth ``` Generates a class extending `MeghMiddleware`: ```ts [src/middlewares/auth.middleware.ts] import { AppMiddleware, MeghMiddleware, IRequest, IResponse } from '@meghjs/core'; @AppMiddleware export class AuthMiddleware extends MeghMiddleware { async invoke(req: IRequest, res?: IResponse) { // your logic goes here return req; } } ``` ## Mail ```sh npx megh make:mail OrderShipped ``` Generates a `Mailable` in `src/mail`, with `envelope()`, `content()` and `attachments()` to fill in. The `Mail` suffix is added for you, and a name like `admin/Invoice` writes to `src/admin/mail/invoice.mail.ts`: ```ts [src/mail/order-shipped.mail.ts] import { Mailable } from '@meghjs/core'; export class OrderShippedMail extends Mailable { envelope() { return { subject: 'Order Shipped' }; } content() { return { html: '

Order Shipped

', text: 'Order Shipped', }; } attachments() { return []; } } ``` If `src/app.ts` doesn't call `app.useMail()` yet, the command says so. See [Mail](/advanced/mail). ## View ```sh npx megh make:view pages.about # or pages/about # shorthand npx megh m:v pages.about ``` Writes `views/pages/about.megh.html`, which you render with `Results.View('pages.about', data)`. Views live in `views/` at the project root, not under `src/`, and no unit test is written. When `views/layouts/app.megh.html` exists (as in a `new --mvc` project) the page extends it: ```html [views/pages/about.megh.html] @extends('layouts.app') @section('title', 'About') @section('content')

About

@endsection ``` | Option | Effect | |--------|--------| | `-l, --layout ` | Extend another layout, e.g. `layouts.admin` | | `--no-layout` | Write a standalone HTML page | | `-c, --component` | Write a component in `views/components/`: `make:view forms/input -c` is used as `` | If `src/app.ts` doesn't call `app.useViews()` yet, the command says so. See [Views](/advanced/views). ## Inertia page ```sh npx megh make:page Users/Show # or users.show # shorthand npx megh m:p Users/Show ``` Writes an [Inertia](/advanced/inertia) page component to `frontend/pages/Users/Show.vue`, which you render with `Results.Inertia('Users/Show', props)`. Each part of the name becomes PascalCase. The framework comes from the Inertia client in `package.json`: | Client in `package.json` | File | |--------------------------|------| | `@inertiajs/vue3` | `frontend/pages/Users/Show.vue` | | `@inertiajs/react` | `frontend/pages/Users/Show.tsx` | | `@inertiajs/svelte` | `frontend/pages/Users/Show.svelte` | | Option | Effect | |--------|--------| | `--framework ` | Use `vue`, `react` or `svelte` instead of the one found in `package.json` | | `-f, --force` | Overwrite an existing page | ## Events ```sh npx megh make:event UserCreated npx megh make:listener SendWelcomeEmail --event UserCreated ``` `make:event` writes `src/events/user-created.event.ts`: a `UserCreatedEvent` extending `MeghEvent`, with a `UserCreatedPayload` type to fill in. `make:listener` writes `src/listeners/send-welcome-email.listener.ts`: a `SendWelcomeEmailListener` typed to the event, marked `@AppService` so it can inject services. With `--event` (`-e`), the event is created too if it doesn't exist yet; without it, the listener takes any `MeghEvent`. ```ts [src/listeners/send-welcome-email.listener.ts] import { AppService, MeghEventListener } from '@meghjs/core'; import { UserCreatedEvent } from '../events/user-created.event'; @AppService export class SendWelcomeEmailListener extends MeghEventListener { async handler(event: UserCreatedEvent): Promise { // event.payload is the data; event.name and event.timestamp are set for you. } } ``` Listeners are registered by hand, once at startup. The command prints the line to add to `src/app.ts`: ```ts EventRegistry.getInstance().register(UserCreatedEvent, MeghContainer.get(SendWelcomeEmailListener)); ``` See [Events](/advanced/events). ## Queues and workers ```sh npx megh make:queue OrderExport # queue "order-export" npx megh make:worker Report --queue reports # consumes "reports" ``` `make:queue` writes `src/queues/order-export.queue.ts`: an `OrderExportQueue` that both adds jobs and handles them, with a payload type and one `@JobHandler('process')` method. `--queue` (`-q`) sets the queue name; it defaults to the kebab-case name. ```ts [src/queues/order-export.queue.ts] import { Job, JobHandler, MeghQueue, Queue } from '@meghjs/core'; export type OrderExportPayload = { id: number; // replace with what the job needs }; @Queue({ name: 'order-export' }) export class OrderExportQueue extends MeghQueue { constructor() { super(); } @JobHandler('process') async handleProcess(job: Job) { // job.data is the payload } } ``` `make:worker` writes a `MeghWorkerBase` with `process()`, `onCompleted()` and `onFailed()`, for a queue another part of the system fills. Both print `app.useWorker([...])` if `src/app.ts` doesn't register the class. If neither `.env` nor `.env.example` sets `MEGH_QUEUE_TRANSPORT` or `MEGH_MESSAGING_TRANSPORT`, they also remind you that jobs run in memory until you pick a transport: set `MEGH_QUEUE_TRANSPORT=redis` (or `rabbitmq`) and `MEGH_MESSAGING_URL` for production. See [Queue](/advanced/queue#transports). ## Scheduled tasks ```sh npx megh make:task CleanupTokens # hourly npx megh make:task NightlyReport --cron "0 3 * * *" # 03:00 every day npx megh make:task PollPayments --interval 30000 # every 30 seconds ``` Writes `src/tasks/cleanup-tokens.task.ts`: a `@ScheduledTask()` class with one `@Cron` (or, with `--interval`, `@Interval`) method. `make:scheduler` is an alias. ```ts [src/tasks/cleanup-tokens.task.ts] import { Cron, ScheduledTask } from '@meghjs/core'; @ScheduledTask() export class CleanupTokensTask { @Cron('0 * * * *') // every hour, on the hour async run() { // your logic goes here } } ``` `--cron` takes 5 fields, or 6 with seconds first. The command prints `app.useScheduler([...])` unless `src/app.ts` already lists the class or scans a folder with `useScheduler({ path })`. See [Scheduler](/advanced/scheduler). ## Agents ```sh npx megh make:agent SupportTriage # Anthropic, claude-sonnet-5-5 npx megh make:agent Refunds --tags orders,billing # the @Tool tags it may call npx megh make:agent Summary --provider openai --model gpt-5 ``` Writes `src/agents/support-triage.agent.ts`: an `@Agent` class with an input type and a `prompt()` method, and a spec next to it unless `--notest`. Needs [`@meghjs/ai`](/ai/agents). ```ts [src/agents/support-triage.agent.ts] import { Agent, MeghAgent } from '@meghjs/ai'; export type SupportTriageInput = { id: string; // replace with what the agent needs }; @Agent({ name: 'support-triage', model: { provider: 'anthropic', id: 'claude-sonnet-5-5' }, system: 'Describe the job here: what to do, which tools to use first and when to stop.', tools: { tags: ['support-triage'] }, limits: { steps: 20, tokens: 200_000, duration: '15m', toolCalls: 50 }, queue: 'agents', }) export class SupportTriageAgent extends MeghAgent { prompt(input: SupportTriageInput) { return `Handle item ${input.id}.`; } } ``` | Option | Meaning | |---|---| | `--provider`, `-p` | `anthropic` (default) or `openai` | | `--model`, `-m` | The model ID. Defaults to `claude-sonnet-5-5` for Anthropic; required for OpenAI | | `--tags`, `-t` | Tags of the `@Tool` routes the agent may call, comma-separated. Defaults to the kebab-case name | | `--queue`, `-q` | The queue its steps run on (default `agents`) | The command prints `app.useAgents([...])` unless `src/app.ts` already lists the class, and the `npm install` line for `@meghjs/ai` and the provider SDK when they're missing. See [Agents](/ai/agents). ## Config ```sh npx megh make:config jwt ``` Generates a class extending `MeghConfig` and registered with `@AppConfig`: ```ts [src/config/jwt.config.ts] import { AppConfig, MeghConfig, Environment } from '@meghjs/core'; @AppConfig export class JwtConfig extends MeghConfig { config(env: Environment) { return {}; } } ``` ## DTO ```sh npx megh make:dto CreatePost ``` Writes `src/dtos/create-post.dto.ts`: a `CreatePostDto` with validation rules for a `name` and an optional `description`, to replace with your fields. Its test checks that a valid body passes and that `name` is required. ## Class ```sh npx megh make:class Money # shorthand npx megh m:cls billing/Money ``` Writes a plain class (no decorators, nothing to register) in `src/classes/money.ts`, or `src/billing/classes/money.ts` for the nested name, with a test that creates it. `--root ` picks another folder, e.g. `make:class Money --root utils` writes `src/utils/money.ts`. ## Tests Every generator except `make:model` and the database ones (`make:migration`, `make:seeder`, `make:factory`) writes a [Vitest](/advanced/testing) unit test next to the file it creates. The app's `vitest.config.mts` runs every `src/**/*.spec.ts`, so `npm test` picks them up: | Command | Also writes | |---|---| | `make:service user` | `src/services/user.service.spec.ts` | | `make:resource user` | `src/services/user.service.spec.ts`, `src/controllers/user.controller.spec.ts` | | `make:controller user -m user` | `src/controllers/user.controller.spec.ts` (and the service's, when it creates the service) | | `make:class Money` | `src/classes/money.spec.ts` | Each test matches what was generated: - **Resource services** (`make:resource`, `make:service -m`) get a test for every method: `findAll`, `paginate`, `find`, `findOrFail`, `create`, `update` (it checks that fields sent as `undefined` are skipped) and `delete`, including the 404 cases. The model's queries are replaced with `vi.spyOn`, so no database is needed. `create` and `update` use sample values for the model's columns (`email` gets `user@example.com`, a boolean `true`). With `--typeorm`, the repository is a stand-in. - **Resource controllers** get a test for every route, with a stand-in service passed to `MeghTest.getController`. - **Other files** (a basic service or controller, config, middleware, mail, event, listener, queue, worker, task, DTO, class) get a test of what the template does. Replace it as you write the real code. ```ts [src/services/user.service.spec.ts] describe('delete', () => { it('deletes the user', async () => { const existing = row(); vi.spyOn(User, 'findOrFail').mockResolvedValue(existing as never); const remove = vi.spyOn(existing, 'delete').mockResolvedValue(); await service.delete(1); expect(remove).toHaveBeenCalled(); }); }); ``` Skip the test with `--notest` (or `-nt`): ```sh npx megh make:service user -nt npx megh make:resource user --notest npx megh scaffold:domain ecommerce --resource --notest ``` Running a generator again with `-f` keeps an existing test, unless it is overwritten too (the review shows it first). ### make:test `make:test` writes the test for a file that already exists, next to it: ```sh npx megh make:test user.service # src/services/user.service.spec.ts npx megh make:test UserController # src/controllers/user.controller.spec.ts npx megh make:test user --type service # the same as user.service npx megh m:t price-calculator # finds src/**/price-calculator.ts npx megh m:t checkout # nothing matches: src/tests/checkout.spec.ts ``` The kind comes from the name (`user.service`, `UserService`) or `--type` (`service`, `controller`, `config`, `middleware`, `mail`, `event`, `listener`, `queue`, `worker`, `task`, `dto`, `model` or `class`). Without one, it looks for a file of that name anywhere under `src/`, and asks you to be more specific when several match. A resource service or controller is recognised and gets the full tests above. Any other class gets a test that creates it (through the container for services, controllers, middleware and the like) and a `it.todo()` for each of its public methods: ```ts [src/utils/price-calculator.spec.ts] import { describe, expect, it } from 'vitest'; import { PriceCalculator } from './price-calculator'; describe('PriceCalculator', () => { const priceCalculator = new PriceCalculator(); it('should be defined', () => { expect(priceCalculator).toBeDefined(); }); it.todo('total()'); it.todo('refresh()'); }); ``` A name that matches no file gets a starter spec in `src/tests/`. An existing spec is not replaced without `-f`. --- # Database Commands Source: https://meghjs.github.io/cli/database These commands create and run migrations, seeders and factories. ## Migrations ```sh npx megh make:migration create_users_table npx megh migrate ``` `make:migration` writes `src/database/migrations/_.ts`. A `create_
_table` name gives a create-table migration, and `add__to_
_table` an alter-table one; `--create
` and `--table
` choose explicitly. The `migrate` commands connect the way `app.useMeghORM()` does, from `DATABASE_URL` (or the `DB_*` variables) in the environment or `.env`. Set `megh.migrations` in `package.json` to use another folder. See [MeghORM: Migrations](/advanced/orm/migrations). By default they compile `src/` with SWC into `.megh/migrate/` first. With `--compiled` they run the `.js` files `megh build` wrote to the tsconfig `outDir` instead (`dist/database/migrations`, or `dist/src/database/migrations` when `rootDir` isn't set), so neither the sources nor a writable project folder are needed. This happens automatically when there is no `src/` folder, as in a production image. Every `migrate*` command and `db:seed` accepts `--compiled`. ```sh npx megh build npx megh migrate --compiled ``` ## Messaging tables ```sh npx megh make:messaging npx megh migrate ``` `make:messaging` writes a migration, `_create_messaging_tables.ts`, that creates the tables Megh's [messaging](/advanced/messaging) uses: `megh_outbox` for the [outbox](/advanced/messaging#outbox), `megh_locks` for [scheduler locks](/advanced/scheduler#multiple-replicas), and `megh_dedupe` for the database dedupe store. It calls `createMessagingTables(schema)` and, on rollback, `dropMessagingTables(schema)`. It refuses to write a second one when the migrations folder already has it; `--force` writes another anyway. ## Seeders ```sh npx megh make:seeder roles npx megh make:seeder users npx megh make:seeder database # the entry seeder: calls roles, then users npx megh db:seed ``` `make:seeder` writes `src/database/seeders/.seeder.ts` (`UserSeeder` and `user_seeder` both become `user.seeder.ts`): ```ts [src/database/seeders/roles.seeder.ts] import { defineSeeder } from '@meghjs/core'; import { Role } from '../../models/role.model'; export default defineSeeder({ async run() { await Role.create({ name: 'Admin' }); await Role.create({ name: 'Editor' }); }, }); ``` `db:seed` runs the `database` seeder, which calls the others in the order you choose; `make:seeder database` fills that in from the seeders that already exist. Without a `database` seeder, every seeder runs in file-name order. ```sh npx megh db:seed --seeder users # just one (also -s) npx megh migrate --seed # migrate, then seed npx megh migrate:refresh --seed # rebuild the schema and seed it ``` A whole run is one transaction: if a seeder throws, nothing is saved and the error names the seeder. Seeding refuses to run when `NODE_ENV` is `production` unless you pass `--force`. Set `megh.seeders` in `package.json` to use another folder. See [MeghORM: Seeding](/advanced/orm/seeding#seeding). ## Factories ```sh npx megh make:factory role npx megh make:factory user ``` `make:factory` reads the model's columns and writes `src/database/factories/.factory.ts` with a [Faker](https://fakerjs.dev) value for each, picked from the column's name and type: ```ts [src/database/factories/user.factory.ts] import { defineFactory } from "@meghjs/core"; import { User } from "../../models/user.model"; import { RoleFactory } from "./role.factory"; export const UserFactory = defineFactory(User, ({ faker }) => ({ name: faker.person.fullName(), email: faker.internet.email(), phone: faker.phone.number({ style: "international" }).slice(0, 20), is_active: faker.datatype.boolean(), role_id: RoleFactory, })); ``` A foreign key such as `role_id` uses `RoleFactory` when that factory exists, so create the related model's factory first; otherwise it is left as a comment (or `null` for a nullable key). Values are kept within short `varchar(n)` columns. The generated key and timestamps are left out. Edit the result freely: it's your code. Factories need `@faker-js/faker` (`npm install -D @faker-js/faker`); `megh new` adds it to projects with MeghORM. Set `megh.factories` in `package.json` to use another folder. See [MeghORM: Factories](/advanced/orm/seeding#factories). --- # Scaffold Source: https://meghjs.github.io/cli/scaffold/ The `scaffold:*` commands, and the `--template` / `--fields` options of `make:model` and `make:resource`, build complete parts of an app from templates. A template describes a table: its columns, foreign keys, timestamps and indexes. It becomes an ordinary `schema.create(...)` [migration](/advanced/orm/migrations), and the usual [generators](/cli/generators) then write the model, DTOs, service, controller and factory from that migration. Everything generated is plain code you own and can edit. | Command | Alias | Description | |---------|-------|-------------| | `make:model --template ` | `m:m` | A table and its model from a template | | `make:resource --template ` | `m:r` | A table and its full REST resource from a template | | `make:model --fields ` | `m:m` | A table described on the command line | | `scaffold:domain [domain]` | `sc:domain` | Several tables of a business domain at once | | `scaffold:auth` | `sc:auth` | Sign-up and sign-in with JWTs and/or API keys, optionally with roles | | `scaffold:rbac` | `sc:rbac` | Roles (one or many per user) and permissions | | `template:list [domain]` | `templates` | List the templates | ## Pages | Page | What it covers | |---|---| | [Templates and Fields](/cli/scaffold/templates) | `--template`, `--fields`, the field spec and presets, your own templates | | [Domains](/cli/scaffold/domains) | `scaffold:domain` and every built-in template | | [Auth](/cli/scaffold/auth) | `scaffold:auth`: JWT, API keys, the generated routes and code | | [RBAC](/cli/scaffold/rbac) | `scaffold:rbac`: roles, permissions and `@Authorized({ roles })` | ## Quick Start ```sh npx megh new shop --yes --database postgres cd shop # Sign-in with JWTs, many roles per user, roles grant permissions npx megh sc:auth --strategy jwt --roles multiple --permissions -y # The store: products, orders, payments, ... npx megh sc:domain ecommerce --resource -y npx megh migrate --seed npm run start:dev ``` ## How It Works 1. **Migrations.** Each template becomes a create-table migration in `src/database/migrations/`. Tables a foreign key points to are created too when no migration creates them yet (`products.category_id` brings in `categories`). Migrations are numbered so each table comes after the tables it references, and after every migration already in the folder. 2. **Models and more.** The migrations are read, not run, so no database is needed: `make:model`, `make:resource` and `make:factory` build the model, DTOs, service, controller and factory from their columns. 3. **Existing work is kept.** A table some migration already creates keeps that migration, and the template's columns are not applied to it. An existing model is reused. To change a table, write an alter-table migration and run [`sync:model`](/cli/generators#syncing-a-model). Then create the tables: ```sh npx megh migrate ``` ## Prompts In a terminal, commands ask for what is missing: a template, the templates of a domain, the sign-in strategy, the role mode, and whether to create the tables foreign keys point to. Pass `-y` / `--yes` to skip the prompts and use the options given (and the defaults), e.g. in scripts and CI. --- # Templates and Fields Source: https://meghjs.github.io/cli/scaffold/templates ## From a Template ```sh npx megh make:model Product --template ecommerce/product npx megh make:resource Product --template ecommerce/product # + DTOs, service, controller npx megh m:m Product --template # pick a domain, then a template ``` A template is named `/`. A bare name works when only one domain has it, and a `common` template wins (`--template category` is `common/category`). See every template on the [Domains](/cli/scaffold/domains) page, or list them: ```sh npx megh template:list # domains and templates npx megh templates ecommerce # one domain, with each template's columns npx megh templates --json ``` For `make:model Product --template ecommerce/product`: ```ts [src/database/migrations/20261110093000_create_products_table.ts] import { defineMigration } from "@meghjs/core"; export default defineMigration({ async up(schema) { await schema.create("products", (table) => { table.id(); table.foreignId("category_id").constrained("categories").nullOnDelete(); table.foreignId("brand_id").constrained("brands").nullOnDelete(); table.string("name"); table.string("slug").unique(); table.string("sku", 64).unique(); table.text("description").nullable(); table.decimal("price", 12, 2); table.decimal("compare_at_price", 12, 2).nullable(); table.decimal("cost", 12, 2).nullable(); table.integer("stock").default(0); table.decimal("weight", 10, 3).nullable(); table.string("status", 32).default("draft"); // draft | active | archived table.boolean("is_featured").default(false); table.timestamps(); table.softDeletes(); table.index("status"); }); }, async down(schema) { await schema.drop("products"); }, }); ``` Since no migration creates `categories` or `brands`, their migrations (`common/category`, `ecommerce/brand`) and models are written first. You are asked before they are added; `--no-deps` leaves them out (create those tables yourself before migrating). The model's name sets the table: `make:model Item --template ecommerce/product` creates `items` with the product columns. Pass `--table ` to choose it. ### Options | Option | Description | |---|---| | `--template [ref]` | The template; without a value, pick one | | `--fields ` | Columns to add to the template, or to replace its columns of the same name | | `--table ` | Table name (default: from the model name) | | `--factory` | Also write a [factory](/advanced/orm/seeding) for each model | | `--no-deps` | Don't create the tables foreign keys point to | | `-f`, `--force` | Overwrite the model (or the resource's files) if they exist | | `-y`, `--yes` | Don't prompt | ## From Fields Describe the table on the command line, with or without a template: ```sh npx megh make:resource Ticket --fields "title,body,priority,status:in(open|pending|closed),user_id:cascade" npx megh make:model Product --template ecommerce/product --fields "barcode?:string(64):unique,weight:decimal(8,2)" ``` Every table gets an `id` and timestamps. Foreign keys to tables no migration creates are handled as with templates (`user_id` above brings in `users`). ## Field Spec A field is written `name[?][:type[(args)]][:modifier]...`, and a list is separated by commas: | Spec | Column | |---|---| | `title` | The `title` preset: `string(255)` | | `slug` | The `slug` preset: `string(255)`, unique | | `email:unique` | The `email` preset, unique | | `phone?` | The `phone` preset, nullable (`?`) | | `address?` | The `address` group: six columns, all nullable | | `nickname?:string(50)` | `string(50)`, nullable | | `price:money` | `decimal(12,2)` | | `hours:decimal(5,1):default(0)` | `decimal(5,1)` with a default | | `status:in(draft\|published)` | `string(32)` that defaults to `draft`, the allowed values in a comment | | `kind:in(a\|b)` | `string(32)`, required | | `category_id` | A foreign key to `categories`, from the name | | `owner_id:foreign(users):cascade` | A foreign key to `users`, deleted with the user | Field names are snake_case. `key`, `save`, `fill`, `delete`, `restore` and `related` can't be used: they are `Model` methods. ### Types | Type | Column | |---|---| | `string(n)` | `VARCHAR(n)`, 255 by default | | `text` | Long text | | `integer` / `int`, `bigInteger` / `bigint` | Integers | | `decimal(p,s)` | Exact number, `(8,2)` by default | | `money` | `decimal(12,2)` | | `percent` | `decimal(5,2)` | | `float`, `double` | Floating point | | `boolean` / `bool` | Boolean | | `date`, `datetime`, `timestamp`, `time` | Dates and times | | `json` | JSON (`JSONB` on PostgreSQL) | | `uuid` | UUID | | `email` | `string(255)` | | `phone` | `string(32)` | | `url` | `string(2048)` | | `foreign(table)` / `foreignId` | Integer foreign key with its constraint | ### Modifiers | Modifier | Effect | |---|---| | `nullable` (or `?` after the name) | Allow NULL | | `unique` | Unique index | | `index` | Index | | `default(value)` | Default value: a number, `true` / `false`, or text | | `in(a\|b\|c)` | Allowed values. `status` defaults to the first one unless `default()` is given | | `cascade` | Foreign key: delete the row with the referenced row | | `nullOnDelete` | Foreign key: set it to NULL (makes it nullable) | | `restrict` | Foreign key: refuse to delete the referenced row | ### SQL Server SQL Server refuses a foreign key whose `ON DELETE` action (`CASCADE` or `SET NULL`) would form a cycle, including a table that references itself, or a second cascade path between two tables. When the project's database is SQL Server (from `megh.database`, `DB_DIALECT` or the `DATABASE_URL` scheme), the generated migrations account for the foreign keys already in your migrations: `CASCADE` is kept first, and a foreign key that would break the rule gets no `ON DELETE` action, with a comment in the migration and a line in the output: ```ts table.foreignId("parent_id").nullable().constrained("categories"); // no ON DELETE action: SQL Server allows one cascade path between tables ``` Deleting the referenced row then fails while rows point to it; clear or reassign them first. `restrict` is written as `onDelete("no action")`, since SQL Server has no `RESTRICT`. Other databases get the actions as given. Allowed values are written as a comment next to the column; the generated DTO doesn't check them. Add `@IsIn([...])` to the DTO to validate them. ### Presets A bare name that isn't a type picks a preset, the columns shared across models. Add modifiers to change one (`email:unique`, `price?`). | Group | Presets | |---|---| | Names and text | `name`, `title`, `slug` (unique), `code` (unique), `sku` (unique), `reference` (unique), `description`, `notes`, `body`, `summary`, `first_name`, `last_name`, `middle_name`, `username` (unique) | | Contact | `email`, `phone`, `mobile`, `website`, `url`, `image`, `avatar`, `logo` | | Auth | `password`, `remember_token`, `email_verified_at`, `last_login_at` | | State | `status` (default `active`, indexed), `type` (indexed), `priority` (`low` … `urgent`), `is_active` (default true), `is_featured`, `sort_order`, `color`, `rating` | | Money and quantities | `price`, `cost`, `amount`, `subtotal`, `discount`, `tax`, `total`, `balance` (all `money`), `tax_rate`, `currency` (default `USD`), `quantity`, `stock`, `weight` | | People | `gender`, `date_of_birth`, `national_id` | | Dates | `date`, `due_date`, `starts_at`, `ends_at`, `published_at`, `paid_at` | | Other | `uuid`, `ip_address`, `metadata`, `settings` (json) | | Column groups | `address` (`address_line1`, `address_line2`, `city`, `state`, `postal_code`, `country`), `geo` (`latitude`, `longitude`), `person` (`first_name`, `last_name`) | Optional-sounding presets (`description`, `phone`, `image`, dates such as `due_date`, …) are nullable. A name ending in `_id` without a type is a foreign key. ## Your Own Templates Put templates in `.megh/templates/.json`, one file per domain: ```json [.megh/templates/helpdesk.json] { "title": "Helpdesk", "description": "Support tickets", "templates": [ { "name": "ticket", "description": "A support request", "fields": ["user_id:cascade", "title", "body", "priority", "status:in(open|pending|closed)"], "softDeletes": true }, { "name": "ticket_tag", "fields": ["ticket_id:cascade", "tag_id:cascade"], "pivot": true } ] } ``` ```sh npx megh make:resource Ticket --template helpdesk/ticket npx megh sc:domain helpdesk ``` | Key | Description | |---|---| | `domain` | Domain name (default: the file name) | | `title`, `description` | Shown by `template:list` and the prompts | | `templates[].name` | snake_case singular name | | `templates[].fields` | Field specs, as for `--fields` | | `templates[].table` | Table name (default: the plural name) | | `templates[].timestamps` | `created_at` / `updated_at` (default `true`; `false` for a join table) | | `templates[].softDeletes` | `deleted_at` (default `false`) | | `templates[].pivot` | A join table: no `id`, the first two foreign keys are the primary key, and no model is generated | | `templates[].unique` | Composite unique keys, e.g. `[["customer_id", "product_id"]]` | A file named after a built-in domain adds templates to it, and a template with the same name as a built-in one replaces it. --- # Domains Source: https://meghjs.github.io/cli/scaffold/domains ```sh npx megh scaffold:domain ecommerce # checklist of the domain's templates npx megh sc:domain ecommerce -y --resource # every template, as REST resources npx megh sc:domain pos --only product,sale,sale_item --factory npx megh sc:domain medical --migrations-only npx megh sc:domain # pick a domain ``` `scaffold:domain` writes a migration for each template of a domain, in the order their foreign keys need, and then a model for each (join tables have none). Templates a foreign key points to from another domain are included, such as `common/user` for `ecommerce/customer`. Domains share tables: `ecommerce` and `pos` both have `products` and `customers`, and `hr` and `medical` both have `departments`. Scaffolding a second domain reuses the tables and models already there. | Option | Description | |---|---| | `--only ` | Only these templates, e.g. `product,order,order_item` | | `--all` | Every template, without the checklist | | `--resource` | Generate REST resources (DTOs, service, controller), not just models | | `--migrations-only` | Only write the migrations | | `--factory` | Also write a factory for each model | | `--no-deps` | Don't create the tables foreign keys point to | | `-f`, `--force` | Regenerate the models (and resources) that already exist | | `-y`, `--yes` | Don't prompt: every template (or `--only`), with their dependencies | Scaffold a single template with [`make:model --template`](/cli/scaffold/templates#from-a-template), and add your own domains in [`.megh/templates/`](/cli/scaffold/templates#your-own-templates). ## Built-in Templates Every table also has an `id`, `created_at` and `updated_at`, except join tables, which have neither. Run `npx megh templates ` for the same list in the terminal. ### Common `common` Users, roles, categories and other tables most apps share. | Template | Table | Columns | |---|---|---| | `user` | `users` (soft deletes) | name, email, password, email_verified_at, remember_token, is_active, last_login_at | | `role` | `roles` | name, slug, description | | `permission` | `permissions` | name, group, description | | `user_role` | `user_roles` (join table) | user_id, role_id | | `role_permission` | `role_permissions` (join table) | role_id, permission_id | | `category` | `categories` | parent_id, name, slug, description, image, sort_order, is_active | | `tag` | `tags` | name, slug | | `address` | `addresses` | addressable_type, addressable_id, label, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, is_default | | `attachment` | `attachments` | attachable_type, attachable_id, name, path, disk, mime_type, size | | `api_key` | `api_keys` | user_id, name, prefix, key_hash, last_used_at, expires_at, revoked_at | | `setting` | `settings` | name, value, group | ### E-commerce `ecommerce` An online store: catalog, carts, orders and payments. | Template | Table | Columns | |---|---|---| | `brand` | `brands` | name, slug, logo, description, website, is_active | | `product` | `products` (soft deletes) | category_id, brand_id, name, slug, sku, description, price, compare_at_price, cost, stock, weight, status, is_featured | | `product_variant` | `product_variants` | product_id, sku, name, price, stock, options, image | | `product_tag` | `product_tags` (join table) | product_id, tag_id | | `customer` | `customers` | user_id, first_name, last_name, email, phone, accepts_marketing | | `cart` | `carts` | customer_id, session_id, currency, status | | `cart_item` | `cart_items` | cart_id, product_id, product_variant_id, quantity, price | | `coupon` | `coupons` | code, description, discount_type, value, min_order_amount, max_uses, used_count, starts_at, ends_at, is_active | | `order` | `orders` | customer_id, coupon_id, number, status, subtotal, discount, tax, shipping_total, total, currency, shipping_address, billing_address, placed_at, notes | | `order_item` | `order_items` | order_id, product_id, product_variant_id, name, sku, quantity, price, discount, total | | `payment` | `payments` | order_id, method, provider, transaction_id, amount, currency, status, paid_at | | `shipment` | `shipments` | order_id, carrier, tracking_number, status, shipped_at, delivered_at | | `review` | `reviews` | product_id, customer_id, rating, title, comment, is_approved | | `wishlist` | `wishlists` | customer_id, product_id | ### Point of sale `pos` Shops and tills: outlets, shifts, sales, purchases and stock. | Template | Table | Columns | |---|---|---| | `outlet` | `outlets` | name, code, phone, email, address_line1, address_line2, city, state, postal_code, country, is_active | | `register` | `registers` | outlet_id, name, is_active | | `shift` | `shifts` | register_id, user_id, opened_at, closed_at, opening_cash, closing_cash, expected_cash, status, notes | | `customer` | `customers` | name, email, phone, loyalty_points, notes | | `supplier` | `suppliers` | name, contact_name, email, phone, address_line1, address_line2, city, state, postal_code, country, tax_number, is_active | | `tax_rate` | `tax_rates` | name, rate, is_inclusive, is_active | | `product` | `products` | category_id, name, sku, barcode, price, cost, stock, reorder_level, tax_rate_id, is_active | | `sale` | `sales` | outlet_id, register_id, shift_id, customer_id, user_id, number, subtotal, discount, tax, total, paid_amount, change_amount, status, sold_at | | `sale_item` | `sale_items` | sale_id, product_id, name, quantity, price, discount, tax, total | | `sale_payment` | `sale_payments` | sale_id, method, amount, reference | | `purchase` | `purchases` | supplier_id, outlet_id, number, status, subtotal, tax, total, ordered_at, received_at, notes | | `purchase_item` | `purchase_items` | purchase_id, product_id, quantity, unit_cost, total | | `stock_movement` | `stock_movements` | product_id, outlet_id, user_id, type, quantity, reference, notes | ### Medical `medical` Clinics and hospitals: patients, doctors, appointments and records. | Template | Table | Columns | |---|---|---| | `department` | `departments` | name, code, description, phone, is_active | | `doctor` | `doctors` | user_id, department_id, first_name, last_name, email, phone, specialization, license_number, consultation_fee, is_active | | `patient` | `patients` (soft deletes) | mrn, first_name, last_name, gender, date_of_birth, phone, email, address_line1, address_line2, city, state, postal_code, country, blood_group, allergies, emergency_contact_name, emergency_contact_phone | | `appointment` | `appointments` | patient_id, doctor_id, department_id, scheduled_at, duration_minutes, status, reason, notes | | `medical_record` | `medical_records` | patient_id, doctor_id, appointment_id, visit_date, chief_complaint, diagnosis, treatment, vitals, notes | | `medication` | `medications` | name, generic_name, form, strength, manufacturer, price, stock, is_active | | `prescription` | `prescriptions` | patient_id, doctor_id, medical_record_id, medication_id, dosage, frequency, duration, quantity, instructions, prescribed_at | | `lab_test` | `lab_tests` | patient_id, doctor_id, name, code, status, result, normal_range, unit, ordered_at, completed_at | | `insurance` | `insurances` | patient_id, provider, policy_number, group_number, coverage_percent, valid_from, valid_until, is_active | | `invoice` | `invoices` | patient_id, appointment_id, insurance_id, number, subtotal, discount, tax, total, paid_amount, status, issued_at, due_date | ### Construction `construction` Building projects: sites, contractors, work orders, materials and budgets. | Template | Table | Columns | |---|---|---| | `client` | `clients` | name, company, email, phone, address_line1, address_line2, city, state, postal_code, country | | `project` | `projects` (soft deletes) | client_id, manager_id, name, code, description, status, budget, start_date, end_date, address_line1, address_line2, city, state, postal_code, country | | `site` | `sites` | project_id, supervisor_id, name, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, is_active | | `contractor` | `contractors` | name, company, trade, email, phone, license_number, address_line1, address_line2, city, state, postal_code, country, rating, is_active | | `work_order` | `work_orders` | project_id, site_id, contractor_id, assigned_to_id, title, description, priority, status, due_date, completed_at, estimated_cost, actual_cost | | `material` | `materials` | name, sku, unit, unit_cost, quantity_on_hand, reorder_level, supplier | | `equipment` | `equipment` | site_id, name, code, category, serial_number, status, purchase_date, purchase_cost | | `timesheet` | `timesheets` | user_id, project_id, work_order_id, date, hours, overtime_hours, status, notes | | `inspection` | `inspections` | project_id, site_id, inspector_name, type, scheduled_at, inspected_at, result, notes | | `change_order` | `change_orders` | project_id, requested_by_id, number, title, description, amount, days_impact, status, approved_at | | `budget_item` | `budget_items` | project_id, category, description, budgeted_amount, actual_amount, notes | ### Marketing `marketing` Campaigns, leads, contacts, segments and email. | Template | Table | Columns | |---|---|---| | `campaign` | `campaigns` | owner_id, name, slug, type, status, budget, spent, starts_at, ends_at, description | | `contact` | `contacts` | first_name, last_name, email, phone, company, job_title, source, country, status | | `lead` | `leads` | contact_id, campaign_id, owner_id, name, email, phone, company, source, status, score, notes | | `segment` | `segments` | name, description, rules, is_dynamic | | `contact_segment` | `contact_segments` (join table) | contact_id, segment_id | | `email_template` | `email_templates` | name, subject, body, from_name, from_email, is_active | | `subscriber` | `subscribers` | email, name, status, source, subscribed_at, unsubscribed_at, ip_address | | `landing_page` | `landing_pages` | campaign_id, title, slug, content, meta_title, meta_description, status, published_at, views, conversions | | `utm_link` | `utm_links` | campaign_id, url, utm_source, utm_medium, utm_campaign, utm_term, utm_content, short_code, clicks | ### Real estate `real-estate` Properties, listings, agents, tenants, leases and rent. | Template | Table | Columns | |---|---|---| | `agent` | `agents` | user_id, first_name, last_name, email, phone, license_number, agency, commission_rate, avatar, is_active | | `property` | `properties` (soft deletes) | agent_id, title, slug, description, type, status, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, bedrooms, bathrooms, area, area_unit, lot_size, year_built, price, currency, is_featured | | `unit` | `units` | property_id, unit_number, floor, bedrooms, bathrooms, area, rent, status | | `amenity` | `amenities` | name, slug, icon, category | | `property_amenity` | `property_amenities` (join table) | property_id, amenity_id | | `listing` | `listings` | property_id, agent_id, type, price, currency, status, listed_at, expires_at, description, views | | `tenant` | `tenants` | user_id, first_name, last_name, email, phone, date_of_birth, national_id, employer, monthly_income, emergency_contact_name, emergency_contact_phone | | `lease` | `leases` | unit_id, tenant_id, start_date, end_date, rent_amount, deposit_amount, billing_day, status, terms, signed_at | | `rent_payment` | `rent_payments` | lease_id, amount, due_date, paid_at, method, reference, status, late_fee | | `inquiry` | `inquiries` | property_id, listing_id, agent_id, name, email, phone, message, status | | `viewing` | `viewings` | property_id, inquiry_id, agent_id, scheduled_at, status, feedback | | `maintenance_request` | `maintenance_requests` | unit_id, tenant_id, title, description, priority, status, reported_at, resolved_at, cost | ### HR `hr` Employees, departments, attendance, leave and payroll. | Template | Table | Columns | |---|---|---| | `department` | `departments` | name, code, description, is_active | | `position` | `positions` | department_id, title, description, min_salary, max_salary | | `employee` | `employees` (soft deletes) | user_id, department_id, position_id, employee_number, first_name, last_name, email, phone, gender, date_of_birth, hire_date, employment_type, salary, status, address_line1, address_line2, city, state, postal_code, country | | `attendance` | `attendances` | employee_id, date, check_in, check_out, status, hours, notes | | `leave_type` | `leave_types` | name, code, days_per_year, is_paid | | `leave_request` | `leave_requests` | employee_id, leave_type_id, approved_by_id, start_date, end_date, days, reason, status, approved_at | | `payroll` | `payrolls` | employee_id, period_start, period_end, basic_salary, allowances, deductions, tax, net_pay, status, paid_at | ### CRM `crm` Accounts, contacts, deal pipelines and activities. | Template | Table | Columns | |---|---|---| | `account` | `accounts` | owner_id, name, industry, website, phone, email, address_line1, address_line2, city, state, postal_code, country, annual_revenue, employee_count, status | | `contact` | `contacts` | account_id, owner_id, first_name, last_name, email, phone, job_title, notes | | `pipeline` | `pipelines` | name, is_default, sort_order | | `pipeline_stage` | `pipeline_stages` | pipeline_id, name, probability, sort_order, is_won, is_lost | | `deal` | `deals` | account_id, contact_id, pipeline_id, pipeline_stage_id, owner_id, title, amount, currency, expected_close_date, status, closed_at, lost_reason | | `activity` | `activities` | user_id, account_id, contact_id, deal_id, type, subject, description, due_at, completed_at | ### Education `education` Schools and courses: students, teachers, enrollments and grades. | Template | Table | Columns | |---|---|---| | `teacher` | `teachers` | user_id, staff_number, first_name, last_name, email, phone, specialization, hire_date, is_active | | `student` | `students` | user_id, student_number, first_name, last_name, email, phone, gender, date_of_birth, admission_date, status, address_line1, address_line2, city, state, postal_code, country | | `course` | `courses` | teacher_id, code, title, description, credits, level, capacity, price, status, starts_at, ends_at | | `enrollment` | `enrollments` | student_id, course_id, enrolled_at, status, progress, completed_at | | `grade` | `grades` | enrollment_id, assessment, score, max_score, letter, weight, graded_at, remarks | ### Logistics `logistics` Warehouses, vehicles, drivers and deliveries. | Template | Table | Columns | |---|---|---| | `warehouse` | `warehouses` | name, code, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, phone, capacity, is_active | | `vehicle` | `vehicles` | warehouse_id, plate_number, type, make, model, year, capacity_kg, status | | `driver` | `drivers` | user_id, vehicle_id, first_name, last_name, phone, email, license_number, license_expires_at, status | | `delivery` | `deliveries` | warehouse_id, vehicle_id, driver_id, tracking_number, recipient_name, recipient_phone, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, weight, status, scheduled_at, delivered_at, proof_url, notes | | `tracking_event` | `tracking_events` | delivery_id, status, location, latitude, longitude, occurred_at, notes | --- # Auth Source: https://meghjs.github.io/cli/scaffold/auth ```sh npx megh scaffold:auth # shorthand npx megh sc:auth ``` You are asked three things: 1. **How clients sign in:** JWT, API keys, or both. 2. **Roles:** none, single (one role per user, `users.role_id`), or multiple (any number per user, the `user_roles` table). 3. **Permissions:** whether roles grant permissions (with roles only). Or give the answers as options: ```sh npx megh sc:auth --strategy jwt -y npx megh sc:auth --strategy both --roles multiple --permissions -y npx megh sc:auth --strategy api-key --roles single --no-permissions -y ``` | Option | Description | |---|---| | `--strategy ` | `jwt`, `api-key` or `both` (default `jwt`) | | `--roles ` | `none`, `single` or `multiple` (default `none`) | | `--permissions` / `--no-permissions` | Roles grant permissions | | `-f`, `--force` | Overwrite the generated auth files | | `-y`, `--yes` | Don't prompt | JWTs use [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken), which the command tells you to install: ```sh npm install jsonwebtoken npm install -D @types/jsonwebtoken ``` Then create the tables and the roles: ```sh npx megh migrate --seed ``` ## Routes | Route | Body | Response | |---|---|---| | `POST /auth/register` | `{ name, email, password }` | Same as login | | `POST /auth/login` | `{ email, password }` | JWT: `{ token_type: "Bearer", access_token, expires_in, user }`. API keys only: `{ api_key, user }` | | `GET /auth/me` | | The signed-in user, with their roles | | `GET /auth/api-keys` | | The user's active keys (API keys) | | `POST /auth/api-keys` | `{ name, expires_at? }` | The new key, with `key` shown this once (API keys) | | `DELETE /auth/api-keys/:id` | | Revokes a key (API keys) | Send the token as `Authorization: Bearer `, or the key as `X-API-Key: `. A wrong password and an unknown email both answer `401 Invalid email or password.`; a registered email answers 400. Passwords need at least 8 characters. ```sh curl -X POST localhost:4000/auth/login -H 'content-type: application/json' \ -d '{"email":"ann@example.com","password":"secret123"}' curl localhost:4000/auth/me -H "authorization: Bearer $TOKEN" ``` ## Protecting Routes ```ts import { Controller, Authorized, AuthUser, Get, type Row } from '@meghjs/core'; import type { User } from '../models/user.model'; @Controller('/orders') export class OrderController { @Authorized() // signed in, else 401 @Get() mine(@AuthUser() user: Row) { /* ... */ } @Authorized({ roles: ['admin'] }) // and an admin, else 403 @Get('/all') all() { /* ... */ } @Authorized({ permissions: ['orders.manage'] }) @Get('/export') export() { /* ... */ } } ``` `@Authorized()` on the controller class protects all of its routes. Roles match by slug or name; see [RBAC](/cli/scaffold/rbac). ## Generated Files | File | Contents | |---|---| | `src/database/migrations/*` | `users`, and as chosen `roles`, `user_roles` or `users.role_id`, `permissions` with `role_permissions`, `api_keys` | | `src/models/*.model.ts` | `User` (with its `roles` / `role` relation), `Role`, `Permission`, `ApiKey` | | `src/auth/jwt.ts` | `signToken()` / `verifyToken()`: HS256 with `JWT_SECRET` | | `src/auth/api-keys.ts` | `generateApiKey()` / `hashApiKey()` | | `src/auth/authentication.ts` | `AppAuthentication`: reads the token or key and sets `request.user`, with its roles loaded | | `src/auth/authorization.ts` | `AppAuthorization`: the checks behind `@Authorized(...)` | | `src/auth/rbac.ts` | `rolesOf()`, `hasRole()`, `permissionsOf()`, `hasPermission()`, `assignRole()` | | `src/dtos/auth.dto.ts` | `RegisterDto`, `LoginDto`, `CreateApiKeyDto` | | `src/services/auth.service.ts` | `AuthService`: register, login and API keys. Passwords are hashed with [`Hash`](/core-concept/hashing), and rehashed at sign-in when the settings change | | `src/controllers/auth.controller.ts` | `AuthController`: the routes above | | `src/database/seeders/roles.seeder.ts` | The `admin` and `user` roles (and permissions), safe to run again | It also updates: - **`src/app.ts`**: registers the handlers and the controller. ```ts app.useAuthentication(AppAuthentication); app.useAuthorization(AppAuthorization); app.useControllers([HomeController, AuthController]); ``` - **`.env`**: `JWT_SECRET` (a random 96-character key) and `JWT_EXPIRES_IN=1d`. `.env.example` gets the names without the secret. - **`src/config/openapi.config.ts`**: `auth: 'bearer'` (`'apiKey'` with API keys only), for the Authorize button of the [docs page](/microservices/openapi). - **`src/database/seeders/database.seeder.ts`**, if you have one: calls `"roles"`, so `db:seed` runs it. New users get the `user` role. `User` and `ApiKey` leave the password, remember token and key hash out of their JSON, so responses never contain them. ## Security - Passwords are hashed with scrypt and a random salt, and compared in constant time. - Only the SHA-256 hash of an API key is stored. A key is shown once, when it is created; revoked and expired keys are refused. - Tokens are signed with HS256 and verified with only that algorithm. Keep `JWT_SECRET` out of version control. A JWT can't be revoked before it expires, so keep `JWT_EXPIRES_IN` short or use API keys where you need revocation. - Deactivated users (`is_active = false`) can't sign in, and their tokens stop working. - Not included: refresh tokens, email verification, password reset and rate limiting on login. ## An Existing Users Table If a migration already creates `users`, it is kept. An alter-table migration adds the columns sign-in needs and the table lacks (`email`, `password`, and `role_id` for a single role), as nullable columns since the table may have rows. The `User` model is updated with [`sync:model`](/cli/generators#syncing-a-model), and the generated code only uses columns the table has. ## Running It Again Generated files aren't overwritten: running `scaffold:auth` again fails with the files that exist. Pass `-f` to regenerate them, e.g. to switch from JWT to both. Migrations and models are never rewritten, and nothing is registered twice. A file that already has exactly the content it would get, such as `rbac.ts` from an earlier [`scaffold:rbac`](/cli/scaffold/rbac) with the same roles, is kept. See [Authentication](/core-concept/authentication) for how `MeghAuthentication` and `@Authorized` work. --- # RBAC Source: https://meghjs.github.io/cli/scaffold/rbac ```sh npx megh scaffold:rbac # shorthand npx megh sc:rbac --roles multiple --permissions -y ``` `scaffold:rbac` adds role-based access control to an app's users without the sign-in parts. Use it when you already authenticate users your own way, or to add roles before running [`scaffold:auth`](/cli/scaffold/auth). `scaffold:auth` asks the same questions and generates the same files, so you don't need both. | Option | Description | |---|---| | `--roles ` | `single` or `multiple` (default `multiple`) | | `--permissions` / `--no-permissions` | Roles grant permissions | | `-f`, `--force` | Overwrite the generated files | | `-y`, `--yes` | Don't prompt | ## Role Modes | Mode | Tables | `User` model | |---|---|---| | `single` | `roles`, `users.role_id` | `@BelongsTo(() => Role) role` | | `multiple` | `roles`, `user_roles` (`user_id`, `role_id`) | `@BelongsToMany(() => Role, { table: "user_roles" }) roles` | | `--permissions` | also `permissions`, `role_permissions` | `Role` gets `@BelongsToMany(() => Permission, { table: "role_permissions" }) permissions` | A role has a `name`, a unique `slug` and a `description`; a permission has a unique `name` such as `users.manage`, a `group` and a `description`. Without a `users` table, one is created from the `common/user` template; an existing one gets `role_id` through an alter-table migration. ## Generated Files | File | Contents | |---|---| | `src/database/migrations/*` | The tables above | | `src/models/role.model.ts`, `permission.model.ts` | The models, and the relations on `User` | | `src/auth/rbac.ts` | Role and permission helpers | | `src/auth/authorization.ts` | `AppAuthorization`, registered in `src/app.ts` with `app.useAuthorization()` | | `src/database/seeders/roles.seeder.ts` | The `admin` and `user` roles, and their permissions | Create the tables and roles: ```sh npx megh migrate --seed ``` The seeder finds roles and permissions by slug and name before creating them, so it is safe to run again. Edit its `ROLES` and `PERMISSIONS` to fit your app: ```ts [src/database/seeders/roles.seeder.ts] const ROLES = [ { name: "Admin", slug: "admin", description: "Full access" }, { name: "User", slug: "user", description: "A signed-up user" }, ]; /** Permissions per role slug. Check them with @Authorized({ permissions: [...] }). */ const PERMISSIONS: Record = { admin: ["users.view", "users.manage", "roles.manage"], user: [], }; ``` ## Checking Roles On a route: ```ts @Authorized({ roles: ['admin', 'editor'] }) // any of these roles @Authorized({ permissions: ['posts.publish'] }) // any of these permissions ``` A caller without a user gets 401 and one without the role or permission 403. Roles match by slug or name. In code, with the helpers from `src/auth/rbac.ts`: ```ts import { assignRole, hasPermission, hasRole } from '../auth/rbac'; if (await hasRole(user, ['admin'])) { /* ... */ } if (await hasPermission(user, ['posts.publish'])) { /* ... */ } await assignRole(user, 'editor'); // false if there is no such role ``` The helpers use the roles (and permissions) already loaded on the user, as the generated `AppAuthentication` loads them, and query them otherwise. ## Request User `AppAuthorization` reads `request.user`, which an [authentication handler](/core-concept/authentication) sets. `scaffold:auth` generates one. With your own, return a `User`, ideally with its roles loaded so the checks don't query them on every request: ```ts return User.with('roles.permissions').where('id', id).first(); ``` To manage roles over HTTP, generate resources for them: ```sh npx megh make:resource role npx megh make:resource permission ``` and protect them with `@Authorized({ roles: ['admin'] })` on the controller class. --- # Plugins Source: https://meghjs.github.io/advanced/plugins A plugin adds a feature to a Megh app: a new `app.use*` method, a service in the container, lifecycle hooks, health checks, or Fastify hooks that run on every request. `@meghjs/ai` (`app.useMcp()`, `app.useAgents()`) is a plugin, and so is the ORM. Write a plugin when the feature has to hook into the app itself. For code your routes call, a [service](/core-concept/dependency-injection) is enough, and for code that runs before some routes, [middleware](/core-concept/middleware) is. | You want to... | Use | |---|---| | Share logic between routes | A service | | Run code before the routes of one controller | Middleware | | Add `app.useX()`, run on every request, react to every route, or ship it as a package | A plugin | ## Using a plugin Install it. Megh finds plugins among the app's dependencies when the app is created, so there's nothing to register: ```sh npm install @acme/megh-redis ``` ```ts [src/app.ts] const app = Megh.createApplication(); app.useRedis({ url: process.env.REDIS_URL }); ``` `app.getPlugins()` lists the registered plugins, in the order they registered. To pass plugins yourself, see [Registering plugins explicitly](#registering-plugins-explicitly). ## How a plugin works A plugin is an object with a `name` and a `register(ctx)` function, made with `definePlugin`: ```ts import { definePlugin } from '@meghjs/core'; export default definePlugin({ name: '@acme/hello', register(ctx) { ctx.extend('useHello', function (name: string) { ctx.onReady(() => ctx.logger.info(`Hello, ${name}`)); return ctx.app; }); }, }); ``` `register(ctx)` runs once, when the app is created. It has to be synchronous, so the methods it adds exist as soon as `createApplication()` returns. Do async work, such as connecting to a server, in `ctx.onInit`. The context gives you: | Member | Use | |--------|-----| | `ctx.extend(name, fn)` | Add `app[name]`. Throws if core or another plugin already defines it. | | `ctx.container` | The app's container: `get`, `set`, `has` | | `ctx.onInit` | Run during `app.run()`, before the server listens. Connect here. | | `ctx.onReady` | Run once the server is listening | | `ctx.onClose` | Run on shutdown, in reverse order. Disconnect here. | | `ctx.addHealthCheck(name, check)` | A readiness check, reported by [`GET /ready`](/advanced/health) | | `ctx.http` | The Fastify instance, for Fastify hooks such as `onRequest`, `onRoute` and `onResponse` | | `ctx.logger` | A logger tagged with the plugin's name | | `ctx.app` | The application | The rest of this page builds three plugins, from a file in your app to a published package. ## Example: maintenance mode A plugin doesn't have to be a package. This one lives in the app and turns every request into a 503 while you migrate the database, except for the paths you allow. ```ts [src/plugins/maintenance.plugin.ts] import { definePlugin } from '@meghjs/core'; export type MaintenanceOptions = { /** Defaults to MAINTENANCE=true in the environment. */ enabled?: boolean; /** Paths that keep working, and everything under them. */ allow?: string[]; /** Seconds, sent as Retry-After. */ retryAfter?: number; message?: string; }; declare module '@meghjs/core' { interface MeghApplication { /** Answer 503 to every request except `allow`, while maintenance is on. */ useMaintenance(options?: MaintenanceOptions): this; } } export const maintenancePlugin = definePlugin({ name: 'maintenance', register(ctx) { let settings: Required | undefined; // Runs before routing, authentication and body parsing. ctx.http.addHook('onRequest', async (request, reply) => { if (!settings?.enabled) return; const path = request.url.split('?')[0]; if (settings.allow.some((p) => path === p || path.startsWith(`${p}/`))) return; return reply .code(503) .header('Retry-After', settings.retryAfter) .send({ code: 503, status: 'Error', message: settings.message }); }); ctx.extend('useMaintenance', function (options: MaintenanceOptions = {}) { settings = { enabled: options.enabled ?? process.env.MAINTENANCE === 'true', allow: options.allow ?? ['/health', '/ready'], retryAfter: options.retryAfter ?? 300, message: options.message ?? "We're down for maintenance. Back soon.", }; if (settings.enabled) ctx.logger.warn('Maintenance mode is on'); return ctx.app; }); }, }); ``` The app isn't a package that Megh discovers, so pass the plugin to `createApplication`: ```ts [src/app.ts] import { Megh } from '@meghjs/core'; import { maintenancePlugin } from './plugins/maintenance.plugin'; const app = Megh.createApplication({ plugins: [maintenancePlugin] }); app.useMaintenance({ allow: ['/health', '/ready', '/admin'] }); ``` ```sh MAINTENANCE=true npm start curl -i localhost:3000/orders # 503, Retry-After: 300 ``` Things to notice: - The hook is added in `register`, but it does nothing until `useMaintenance()` turns it on. Plugins should do nothing until the app asks for them. - The 503 uses the same body as Megh's errors (`{ code, status, message }`), so clients handle it like any other error. - `declare module '@meghjs/core'` gives `app.useMaintenance()` its types. Return `this` from the declared method so calls chain. ## Example: a Redis client package This plugin connects to Redis when the app starts, makes the client injectable, reports it in `/ready`, and closes it on shutdown. It's a package, `@acme/megh-redis`, so any app can install it. ``` megh-redis/ ├── src/ │ ├── index.ts # what apps import: the token and the types │ ├── token.ts │ └── plugin.ts # what Megh loads └── package.json ``` The client is a value, not a class, so services inject it with a [`Token`](/core-concept/dependency-injection#tokens): ```ts [src/token.ts] import { Token } from '@meghjs/core'; import type { createClient } from 'redis'; export type RedisClient = ReturnType; /** Inject with @Inject(REDIS). */ export const REDIS = new Token('REDIS'); ``` ```ts [src/plugin.ts] import { definePlugin } from '@meghjs/core'; import { createClient } from 'redis'; import { REDIS } from './token'; export type RedisOptions = { /** Defaults to REDIS_URL, else redis://localhost:6379. */ url?: string; }; declare module '@meghjs/core' { interface MeghApplication { /** Connect to Redis on start, and make the client injectable as REDIS. */ useRedis(options?: RedisOptions): this; } } export default definePlugin({ name: '@acme/megh-redis', register(ctx) { ctx.extend('useRedis', function (options: RedisOptions = {}) { const client = createClient({ url: options.url ?? process.env.REDIS_URL ?? 'redis://localhost:6379', }); client.on('error', (err) => ctx.logger.error({ err }, 'Redis error')); // Set now, so services can be built before the app starts. ctx.container.set(REDIS, client); ctx.onInit(async () => { await client.connect(); ctx.logger.info('Connected to Redis'); }); ctx.addHealthCheck('redis', () => client.ping()); ctx.onClose(() => client.close()); return ctx.app; }); }, }); ``` ```ts [src/index.ts] export { REDIS, type RedisClient } from './token'; export type { RedisOptions } from './plugin'; ``` `megh.plugin` in `package.json` tells Megh where the plugin is: ```json [package.json] { "name": "@acme/megh-redis", "version": "1.0.0", "main": "dist/index.js", "types": "dist/index.d.ts", "exports": { ".": "./dist/index.js", "./plugin": "./dist/plugin.js" }, "megh": { "plugin": "./dist/plugin.js" }, "dependencies": { "redis": "^6.0.0" }, "peerDependencies": { "@meghjs/core": "^0.8.0" } } ``` List `@meghjs/core` as a **peer dependency**, not a dependency. The plugin then uses the app's copy of core, and so the app's container. With its own copy, the token it sets would be in a container the app never reads. In an app, install it, call `useRedis()`, and inject the client: ```ts [src/app.ts] app.useRedis(); ``` ```ts [src/services/visit-counter.service.ts] import { AppService, Inject } from '@meghjs/core'; import { REDIS, type RedisClient } from '@acme/megh-redis'; @AppService export class VisitCounter { constructor(@Inject(REDIS) private readonly redis: RedisClient) {} hit(page: string) { return this.redis.incr(`visits:${page}`); } } ``` `GET /ready` now includes `redis`, and the app answers 503 there while Redis is down, so a load balancer stops sending it traffic. ## Example: an audit log for chosen routes A plugin can see every route as it's registered. This one adds an `@Audited` decorator and records who called those routes, with what result. It shows how a plugin reads route metadata with `getRouteDescriptor`, and how it lets the app choose where entries go. ```ts [src/audit.ts] import 'reflect-metadata'; import { Token } from '@meghjs/core'; export type AuditEntry = { action: string; userId: string | null; status: number; requestId: string; durationMs: number; at: Date; }; /** Where entries go: a table, a queue, a log service. */ export interface AuditSink { write(entry: AuditEntry): Promise; } export const AUDIT_SINK = new Token('AUDIT_SINK'); export const AUDITED = Symbol.for('acme:audited'); /** Record each call of this route as `action`. */ export function Audited(action: string): MethodDecorator { return (target, key) => Reflect.defineMetadata(AUDITED, action, target, key); } ``` ```ts [src/plugin.ts] import { definePlugin, getRouteDescriptor } from '@meghjs/core'; import { AUDITED, AUDIT_SINK, type AuditEntry, type AuditSink } from './audit'; declare module '@meghjs/core' { interface MeghApplication { /** Record @Audited routes. Without a sink, entries are logged. */ useAudit(options?: { sink?: AuditSink }): this; } } export default definePlugin({ name: '@acme/megh-audit', register(ctx) { // "POST /orders/:id/refund" → "order.refund" const actions = new Map(); // Called for every route, as the app registers it. ctx.http.addHook('onRoute', (route) => { const descriptor = getRouteDescriptor(route); // undefined for mapGet() routes if (!descriptor) return; const action = Reflect.getMetadata( AUDITED, descriptor.controller.prototype, descriptor.handler, ); if (!action) return; for (const method of [route.method].flat()) { actions.set(`${method} ${route.url}`, action); } }); // Called after each response is sent, so it never slows the response down. ctx.http.addHook('onResponse', async (request, reply) => { const action = actions.get(`${request.method} ${request.routeOptions.url}`); if (!action || !ctx.container.has(AUDIT_SINK)) return; const user = (request as { user?: { id?: string } }).user; const entry: AuditEntry = { action, userId: user?.id ?? null, status: reply.statusCode, requestId: request.id, durationMs: Math.round(reply.elapsedTime), at: new Date(), }; try { await ctx.container.get(AUDIT_SINK).write(entry); } catch (err) { // A failed audit write mustn't break the app; log it instead. ctx.logger.error({ err, action }, 'Could not write the audit entry'); } }); ctx.extend('useAudit', function (options: { sink?: AuditSink } = {}) { ctx.container.set( AUDIT_SINK, options.sink ?? { async write(entry) { ctx.logger.info({ audit: entry }, entry.action); }, }, ); return ctx.app; }); }, }); ``` The app marks the routes and decides where entries go. Here they go to a Megh ORM model: ```ts [src/controllers/orders.controller.ts] import { Controller, Post, Param, Authorized } from '@meghjs/core'; import { Audited } from '@acme/megh-audit'; @Controller('/orders') export class OrdersController { @Post('/:id/refund') @Authorized() @Audited('order.refund') refund(@Param('id') id: string) { return this.orders.refund(id); } } ``` ```ts [src/app.ts] import { AuditLog } from './models/audit-log.model'; app.useAudit({ sink: { write: (entry) => AuditLog.create(entry).then(() => undefined) }, }); ``` `request.user` is the user from [`useAuthentication()`](/core-concept/authentication), so the entry says who refunded the order, even when the refund was refused (`status: 403`). ## Plugins that need other plugins If a plugin needs another one to register first, name it in `dependsOn`. Megh registers plugins in dependency order, and `createApplication()` throws when one isn't installed: ```ts definePlugin({ name: '@acme/megh-rate-counter', dependsOn: ['@acme/megh-redis'], register(ctx) { // @acme/megh-redis has registered, so app.useRedis exists. }, }); ``` ## Testing a plugin Pass the plugin explicitly, turn off discovery so other installed plugins stay out, and send requests with [`MeghTest.from`](/advanced/testing): ```ts [tests/maintenance.test.ts] import { Megh, MeghTest } from '@meghjs/core'; import { maintenancePlugin } from '../src/plugins/maintenance.plugin'; import { OrdersController } from '../src/controllers/orders.controller'; it('answers 503 during maintenance, except /health', async () => { const app = Megh.createApplication({ plugins: [maintenancePlugin], autoloadPlugins: false, }); app.useMaintenance({ enabled: true }); app.useControllers([OrdersController]); const http = MeghTest.from(app); expect((await http.get('/orders')).statusCode).toBe(503); expect((await http.get('/health')).statusCode).not.toBe(503); }); ``` For a plugin that connects to something, test it against the real service in a container, or pass a fake through its options (like the audit `sink`). ## Guidelines - **Name it after its npm package**, such as `@acme/megh-redis`. Names have to be unique among an app's plugins. - **Keep `register` synchronous and quiet.** Add methods and hooks there, and wait for `app.use*()` before doing anything. Connect in `onInit`, never at import time. - **Close what you open** in `onClose`, so tests and graceful shutdown don't hang. - **Don't throw while handling a request** for something that isn't the request's fault, such as a failed audit write. Log it with `ctx.logger`. - **Answer errors with Megh's body**, `{ code, status: "Error", message }`. - **Type your methods** with `declare module '@meghjs/core'`, and return `this`. - **Use `@meghjs/core` as a peer dependency** that matches the Megh versions you support, such as `^0.8.0`. ## Registering plugins explicitly Discovery reads the app's `package.json`, which a bundled app doesn't have at runtime. Pass plugins yourself in that case, for plugins that live in the app, and in tests: ```ts import redis from '@acme/megh-redis/plugin'; import { maintenancePlugin } from './plugins/maintenance.plugin'; const app = Megh.createApplication({ plugins: [redis, maintenancePlugin], autoloadPlugins: false, // optional: skip discovery }); ``` An explicit plugin replaces a discovered one with the same name. --- # API Reference Source: https://meghjs.github.io/reference/api This page lists the public exports of `@meghjs/core`, grouped by area. Each group links to the guide that explains it in depth. Everything here is imported from the package root: ```ts import { Megh, Controller, Get, Results } from "@meghjs/core"; ``` The command-line tool, `@meghjs/cli`, is documented separately under [CLI](/cli/basic). Signatures are shown as TypeScript. Optional parameters end in `?`, and `Constructor` means a class that builds a `T`. ## Application Guides: [Usage](/getting-started/usage), [Application](/getting-started/application). ### Creating an application | Export | Kind | Description | | --- | --- | --- | | `Megh` | class | Entry point. `Megh.createApplication(options?)` returns the application; `Megh.createTestApplication(options)` returns a test client. | | `MeghApplication` | class | The application object returned by `Megh.createApplication()`. Its methods are listed below. | ```ts Megh.createApplication(options?: MeghApplicationOptions): MeghApplication Megh.createTestApplication(options: TestAppOptions): TestApplication ``` `Megh.createApplication()` returns the same instance every time it's called in a process. `MeghApplicationOptions` fields: | Option | Type | Description | | --- | --- | --- | | `server` | `FastifyServerOptions` | Options passed to the Fastify instance. | | `requestId` | `RequestIdOptions` | Request ID header and generator, or `false` to turn request IDs off. | | `experimental` | `ExperimentalOptions` | `{ compiledValidation?: boolean }`. Defaults to the `MEGH_COMPILED_VALIDATION` environment variable. | | `plugins` | `MeghPlugin[]` | Plugins to register explicitly. | | `autoloadPlugins` | `boolean` | Find plugins among the app's dependencies. Defaults to `true`. | ### MeghApplication methods Every `use*`, `on*` and `addHealthCheck` method returns the application, so calls chain. #### Features | Method | Description | | --- | --- | | `useControllers(controllers: Constructor[] \| { auto: true; path?: string })` | Register controller classes, or scan a directory for them. | | `useCors(options: CorsOptions)` | Enable CORS through `@fastify/cors`. | | `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). | | `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). | | `useMultipart(options?: MultipartOptions)` | Enable multipart bodies through `@fastify/multipart`. Defaults: `attachFieldsToBody: true`, 10 MB file size limit. | | `useStaticFiles(options: StaticFileOptions)` | Serve static files through `@fastify/static`: `{ root, prefix?, ... }`. | | `useCompression(options?: CompressionOptions)` | Compress responses through `@fastify/compress`. | | `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). | | `setGlobalPrefix(prefix: string, options?: { exclude?: (string \| RegExp)[] })` | Serve controller and inline routes under `prefix`. | | `useVersioning(options: VersioningOptions)` | Version controller routes by URI (`/v1/...`) or header. | | `useEnvSchema(schema: Constructor)` | Validate environment variables against a DTO class at boot. | | `useOpenApi(options?: OpenApiUiOptions \| Constructor>)` | Generate the OpenAPI document and serve the docs page. | | `useMiddlewares(middlewares: Constructor[])` | Register global middleware, run before every route. | | `useAuthentication(authentication: Constructor)` | Register the authentication handler that sets `request.user`. | | `useAuthorization(authorization: AuthorizationHandlers, 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). | | `useExceptionFilters(filters: ExceptionFilterLike \| ExceptionFilterLike[])` | Register global exception filters, run in order before the default error response. | | `useErrorHandler(handler: ErrorHandlerFunction)` | Register a function filter that sees every error. | | `useErrorLogger(logger: ErrorLogger \| false)` | Replace how default error responses are logged, or turn logging off. | | `useHealth(options?: HealthOptions)` | Serve `GET /health` (liveness) and `GET /ready` (readiness). | | `addHealthCheck(name: string, check: HealthCheck)` | Add a readiness check reported by `GET /ready`. | | `useCache(options?: CacheOptions)` | Configure `CacheManager` and register it in the container. | | `useScheduler(tasks: Constructor[] \| { path: string })` | Register `@ScheduledTask` classes, or scan a directory for them. | | `useWorker(workers: Constructor[])` | Resolve and start `@Queue` and `@MeghWorker` classes. They close on shutdown. | | `useMessaging(config?: MessagingConfig)` | Configure the messaging transport over `MEGH_MESSAGING_TRANSPORT` / `MEGH_MESSAGING_URL`, add a `messaging` readiness check, start the outbox relay when `outbox` is set, and close the transport on shutdown. See [Messaging](/advanced/messaging). | | `useMail(options?: MailConfig \| Constructor>)` | 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). | | `useSocketIo(options?: SocketIoOptions)` | Enable Socket.IO through `fastify-socket.io`. | | `useGlobal(options: GlobalOptions)` | Call several `use*` methods from one object (`cors`, `openApi`, `controllers`, `middlewares`, `authorization`, `multipart`, `staticFiles`, `securityHeaders`, `rateLimit`). | | `useMeghORM(options?: DatabaseOptions \| MeghConfigClass)` | Connect Megh ORM. Added by the built-in ORM plugin. See [ORM](/advanced/orm). | | `useDatabase(db: Kysely)` | Deprecated. Use an existing Kysely instance as the ORM connection. Use `useMeghORM()` instead. | #### Functional routes | Method | Description | | --- | --- | | `mapGet(path: string, fn): InlineRoute` | Register a `GET` route handled by a function. | | `mapPost(path: string, fn)` | Register a `POST` route handled by a function. | | `mapPut(path: string, fn)` | Register a `PUT` route handled by a function. | | `mapPatch(path: string, fn)` | Register a `PATCH` route handled by a function. | | `mapDelete(path: string, fn)` | Register a `DELETE` route handled by a function. | Each `map*` method returns a route builder with three chainable methods: `useMiddleware(middleware | middleware[])`, `authorized(options?: string | { name?: string })` and `useOpenApi(options: OpenApiOptions)`. #### Lifecycle | Method | Description | | --- | --- | | `run(port?: number, options?: RunOptions \| CallableFunction): Promise` | Start the server. `port` defaults to `4000`. A function as the second argument is called once the server is listening. | | `close(): Promise` | Stop the server, scheduled tasks and workers, then run the `onClose` hooks. Calling it again returns the same promise. | | `onInit(hook: LifecycleHook)` | Run `hook` during `run()`, after the database connects and before the server listens. | | `onReady(hook: LifecycleHook)` | Run `hook` once the server is listening. | | `onClose(hook: LifecycleHook)` | Run `hook` on shutdown (`close()`, SIGTERM or SIGINT), in reverse registration order. | `RunOptions`: | Option | Type | Description | | --- | --- | --- | | `host` | `string` | Interface to listen on. Defaults to `process.env.HOST`, else `0.0.0.0`. | | `onListen` | `CallableFunction` | Called once the server is listening. | | `shutdownTimeout` | `number` | Milliseconds to wait for a graceful shutdown before exiting with code 1. Defaults to `10000`. | #### Other members | Member | Description | | --- | --- | | `app: FastifyInstance` | The underlying Fastify instance. | | `getPlugins(): readonly string[]` | Names of the registered plugins, in registration order. | | `isDevelopment(): boolean` | `true` only when `NODE_ENV` is exactly `"development"`. | | `installErrorHandling()` | Internal. Installs the error and not-found handlers. `run()` calls it. | | `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. | | `MeghApplication.getInternalApp(options?)` | Static, deprecated, internal. Creates a new, unshared instance. | ### Application types | Export | Kind | Description | | --- | --- | --- | | `MeghApplicationOptions` | type | Options for `Megh.createApplication()`. | | `IMeghApplication` | interface | The core method set of `MeghApplication`. | | `RunOptions` | type | Options for `app.run()`. | | `LifecycleHook` | type | `() => void \| Promise`. | | `ExperimentalOptions` | type | `{ compiledValidation?: boolean }`. | | `CorsOptions` | type | Options for `useCors()`. | | `GlobalOptions` | type | Options for `useGlobal()`. | | `MultipartOptions`, `StaticFileOptions`, `SocketIoOptions` | types | Options for `useMultipart()`, `useStaticFiles()` and `useSocketIo()`, passed to the Fastify plugin. The common fields are typed; others pass through. | | `AuthorizationHandlers` | type | `Constructor \| Record>`, for `useAuthorization()`. | | `InlineRoute`, `RouteHandler` | types | What `mapGet()` and friends return (chain `.useMiddleware()`, `.authorized()`, `.public()`, `.rateLimit()`, `.useOpenApi()`), and the handler they take. | | `AutoControllerOptions` | type | `{ auto: true; path?: string }` for `useControllers()`. | | `CacheOptions` | type | `{ provider: "memory" \| "redis"; redis?: RedisConnectionOptions }` for `useCache()`. Megh opens and closes the connection. | ## Controllers and routing Guide: [Controllers](/core-concept/controller). ### Decorators | Export | Kind | Signature | Description | | --- | --- | --- | --- | | `Controller` | decorator | `@Controller`, `@Controller(path: string, options?: ControllerOptions)`, `@Controller(options: ControllerOptions)` | Mark a class as a controller and register it for DI. Path defaults to `/`. | | `Get` | decorator | `@Get(pathOrOptions?: string \| RouteMethodOptions, options?: RouteMethodOptions)` | Handle `GET` requests. Path defaults to `/`. | | `Post` | decorator | same as `Get` | Handle `POST` requests. | | `Put` | decorator | same as `Get` | Handle `PUT` requests. | | `Patch` | decorator | same as `Get` | Handle `PATCH` requests. | | `Delete` | decorator | same as `Get` | Handle `DELETE` requests. | | `Options` | decorator | same as `Get` | Handle `OPTIONS` requests. | | `All` | decorator | same as `Get` | Handle every HTTP method Fastify supports. | | `Route` | decorator | `@Route(method: RouteMethods, pathOrOptions?, options?)` | Generic form of the method decorators above. | | `HttpCode` | decorator | `@HttpCode(statusCode: number)` | Status code for a successful response. A returned `Results.*` or `HttpResponse.*` status wins. Throws for codes outside 100–599. | | `Redirect` | decorator | `@Redirect(url: string, statusCode = 302)` | Redirect instead of sending the return value. Returning `{ url, statusCode }` overrides both. Throws for non-3xx codes. | | `ResponseHeader` | decorator | `@ResponseHeader(name: string, value: string)` | Set a response header on the route. Stackable. | | `Version` | decorator | `@Version(version: string \| string[])` | API version(s) of a controller or route, with `useVersioning()`. | | `VersioningOptions` | type | `{ type: 'uri'; prefix?; defaultVersion? } \| { type: 'header'; header?; defaultVersion? }` | Options for `useVersioning()`. | ### Types | Export | Kind | Description | | --- | --- | --- | | `ControllerOptions` | type | `{ name?: string; path?: string }`. `name` is the OpenAPI tag; it defaults to the class name without `Controller`. | | `RouteMethodOptions` | type | `{ method?: RouteMethods; path?: string; openapi?: OpenApiOptions; name?: string }`. | | `RouteMethods` | type | `"GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE" \| "OPTIONS" \| "ALL"`. | ## Parameters Guide: [Controllers](/core-concept/controller). The parameter decorators take an optional key and an optional options object, in either order of presence: ```ts (key?: string | ParameterOptions, options?: ParameterOptions) => ParameterDecorator // ParameterOptions: { required?: boolean; validate?: boolean; type?: any } ``` `required` and `validate` default to `true`. `type` is only needed when the compiler doesn't emit decorator metadata (tsx, esbuild, SWC). | Export | Kind | Description | | --- | --- | --- | | `Param` | decorator | A route parameter (`@Param("id")`), or all of them with no key. | | `Query` | decorator | A query string value, or the whole query (often a DTO) with no key. | | `Body` | decorator | The request body, usually a DTO, or one field with a key. | | `Header` | decorator | A request header, or all headers with no key. | | `AuthUser` | decorator | `request.user`, as set by the authentication handler. | | `MeghRequest` | decorator | `@MeghRequest()`. The request object itself. | | `UploadFile` | decorator | `@UploadFile(fieldName: string)`. One uploaded file from a multipart field. | | `UploadFiles` | decorator | `@UploadFiles(fieldName?: string)`. Uploaded files from a field, or from every field with no name. | ## Responses Guide: [Controllers](/core-concept/controller). ### Results | Export | Kind | Description | | --- | --- | --- | | `Results` | class | Static factories for route results (below). | | `HttpResult` | abstract class | Base class for values that control status, headers and body. Has `header(name, value)` and `withHeaders(headers)`, which return the result. | | `Ok` | class | `200 { data }`. | | `Created` | class | `201 { data }`. | | `Accepted` | class | `202 { data }`, or an empty body without data. | | `NoContent` | class | `204` with an empty body. | | `NotFound` | class | `404 { code, status, message }`. | | `ErrorResult` | class | Any 4xx or 5xx with the error handler's body; made by `Results.BadRequest`, `Results.Error` and the others. | | `ErrorBody` | type | `{ code: number; status: "Error"; message: string; errors?: unknown; data?: D }`. | | `JsonResult` | class | Any JSON value with any status, no `{ data }` wrapper. | | `ContentResult` | class | A string with its own content type; made by `Results.Text` and `Results.Html`. | | `StatusResult` | class | A status code with no body. | | `FileResult` | class | A file from a path, Buffer or stream; made by `Results.File` and `Results.Download`. A missing path answers 404. | | `FileResultOptions` | type | `{ filename?: string; contentType?: string; inline?: boolean }`. | | `OkStream` | class | `200` with a stream body. | | `RedirectResult` | class | A 3xx with `Location`; made by `Results.Redirect(url, statusCode?)`. | | `OkStreamOptions` | type | `{ contentType?: string; filename?: string }`. With `filename`, the stream is sent as an attachment. | | `RouteResult` | type | `typeof Results.Ok`. | ```ts Results.Ok(data: T): Ok Results.Created(data: T, location?: string): Created Results.Accepted(data?: T): Accepted Results.NoContent(): NoContent Results.NotFound(message: T = "Not Found"): NotFound Results.BadRequest(message = "Bad Request", errors?: unknown): ErrorResult Results.Unauthorized(message = "Unauthorized"): ErrorResult Results.Forbidden(message = "Forbidden"): ErrorResult Results.Conflict(message = "Conflict"): ErrorResult Results.UnprocessableEntity(message = "Unprocessable Entity", errors?: unknown): ErrorResult Results.TooManyRequests(message = "Too Many Requests", retryAfter?: number): ErrorResult Results.Error(statusCode: number, message: string, data?: D): ErrorResult Results.Json(body: T, statusCode = 200): JsonResult Results.Text(text: string, statusCode = 200): ContentResult Results.Html(html: string, statusCode = 200): ContentResult Results.Status(statusCode: number): StatusResult Results.File(source: string | Buffer | Uint8Array | Readable, options?: FileResultOptions): FileResult Results.Download(source: string | Buffer | Uint8Array | Readable, filename?: string, options?: { contentType?: string }): FileResult Results.Redirect(url: string, statusCode = 302): RedirectResult Results.OkStream(stream: Readable, options?: OkStreamOptions): OkStream Results.View(name: string, data?: object, statusCode?: number): ViewResult Results.Inertia(component: string, props?: InertiaProps): InertiaResult ``` ### HttpResponse | Export | Kind | Description | | --- | --- | --- | | `HttpResponse` | class | Static factories that return `{ message, data }` bodies. | | `IHttpResponse` | interface | `{ message: string; data: T \| null }`. | | `withStatus` | function | `withStatus(body, statusCode)`. Attach a status code to a plain object without changing its JSON. | | `HTTP_STATUS_KEY` | const | Symbol `withStatus` uses to store the status. | ```ts HttpResponse.Ok(obj: any, dto?: ClassConstructor): IHttpResponse // 200 HttpResponse.Created(obj: any, dto?: ClassConstructor): IHttpResponse // 201 HttpResponse.NoContent(): IHttpResponse // 204 ``` With a DTO class, `Ok` and `Created` keep only the DTO's `@Expose`d fields (`excludeExtraneousValues`), converted to their declared types. Classes decorated only with class-transformer's `@Expose` are shaped by class-transformer, if it is installed. ### Pagination and collections | Export | Kind | Description | | --- | --- | --- | | `paginated` | function | `paginated(data: T[], total, page, perPage): Paginated`. Wrap a page of data with its `meta`. | | `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))`. | | `PaginationMeta` | interface | `{ total, page, perPage, lastPage, next, prev }`. | | `PageRequest` | interface | `{ page?, perPage? }`, plus the deprecated `limit`, `take` and `skip`. | | `normalizePageRequest` | function | Resolve a `PageRequest` into `{ page, perPage, offset }`. | | `buildPaginationMeta` | function | `buildPaginationMeta(total, page, perPage): PaginationMeta`. | | `DEFAULT_PER_PAGE` | const | `10`. | | `PAGINATED_ITEM` | const | Symbol used by `Paginated(Item)`. | | `PaginationResult` | type | Deprecated alias of `Paginated`. | | `List` | class | Small in-memory list with async `Find` and `FindOne`. `List.from(items)`. | | `IList` | interface | The `List` surface. | | `Collection` | class | In-memory collection: `Collection.from(items)` with `find`, `findOne`, their async forms and `clear`. | | `BasicCollection` | interface | The `Collection` surface. | | `IFindOneOptions` | interface | `{ where }` argument for `Collection.findOne`. | ## Exceptions and error handling Guide: [Error handling](/core-concept/error-handling). ### HTTP exceptions Every exception takes `(message?: any, options?: HttpExceptionOptions)`. A string message is sent as `message`; an object is sent as `data`. `HttpExceptionOptions` is `{ cause?: unknown; headers?: Record }`. | Export | Kind | Status | | --- | --- | --- | | `BaseHttpException` | abstract class | Base class. `code`, `statusCode`, `payload`, `headers`. | | `HttpException` | class | Any status: `new HttpException(status: number, message?, options?)`. | | `BadRequestException` | class | 400 | | `ValidationErrorException` | class | 400. `new ValidationErrorException(message?, errors?: unknown[], options?)`; `errors` is sent in the response. | | `UnauthorizedException` | class | 401 | | `ForbiddenException` | class | 403 | | `NotFoundException` | class | 404 | | `MethodNotAllowedException` | class | 405 | | `NotAcceptableException` | class | 406 | | `RequestTimeoutException` | class | 408 | | `ConflictException` | class | 409 | | `GoneException` | class | 410 | | `PayloadTooLargeException` | class | 413 | | `UnsupportedMediaTypeException` | class | 415 | | `UnprocessableEntityException` | class | 422 | | `TooManyRequestsException` | class | 429 | | `InternalErrorException` | class | 500 | | `NotImplementedException` | class | 501 | | `BadGatewayException` | class | 502 | | `ServiceUnavailableException` | class | 503 | | `GatewayTimeoutException` | class | 504 | | `HttpExceptions` | const | Factory shortcuts, such as `HttpExceptions.notFound("User not found")` and `HttpExceptions.status(402, "Payment required")`. One per exception above: `badRequest`, `validationError(message?, errors?)`, `unauthorized`, `forbidden`, `notFound`, `methodNotAllowed`, `notAcceptable`, `requestTimeout`, `conflict`, `gone`, `payloadTooLarge`, `unsupportedMediaType`, `unprocessableEntity`, `tooManyRequests`, `internalError`, `notImplemented`, `badGateway`, `serviceUnavailable`, `gatewayTimeout`, plus `status(status, message?, options?)`. | | `HttpExceptionOptions` | interface | `{ cause?, headers? }`. | | `HttpExceptionTypes` | type | Union of the not-found, bad-request, unauthorized, internal-error and forbidden exceptions. | ### Exception filters | Export | Kind | Signature / description | | --- | --- | --- | | `Catch` | decorator | `@Catch(...types: ErrorClass[])`. Limit a filter class to these error classes and register it for DI. | | `UseFilters` | decorator | `@UseFilters(...filters: ExceptionFilterLike[])`. Apply filters to a controller or route. They run before the global filters. | | `ExceptionFilter` | interface | `{ catch(error: E, ctx: ErrorContext): unknown }`. | | `ErrorHandlerFunction` | type | `(error: E, ctx: ErrorContext) => unknown`. | | `ExceptionFilterLike` | type | A filter class, a filter instance or an `ErrorHandlerFunction`. | | `ErrorContext` | interface | `{ request, reply, isDevelopment, response }`. | | `ErrorResponse` | interface | `{ statusCode, headers?, body }`. | | `ErrorResponseBody` | interface | The default JSON error body: `{ code, status, message, data?, errors?, error?, stack? }`. | | `ErrorLogger` | type | `(error, request, response) => void`, for `useErrorLogger()`. | | `ErrorHandlerOptions` | interface | `{ isDevelopment?: () => boolean; logger?: ErrorLogger \| false }`. | | `defaultErrorResponse` | function | `defaultErrorResponse(error, isDevelopment): ErrorResponse`. The response Megh sends when no filter handles an error. | | `defaultErrorLogger` | const | The default `ErrorLogger`: 4xx as warnings, others as errors with the stack. | | `MeghErrorHandler` | class | Megh's request error handler. The application creates one; you don't normally construct it. | ## Validation Guide: [Validation](/core-concept/validation). ### Validation decorators Every decorator takes an optional last argument, `options?: ValidationOptions` (`message`, `each`, `groups`, and so on, as in class-validator). | Export | Kind | Signature | | --- | --- | --- | | `IsOptional` | decorator | `@IsOptional(options?)` | | `ValidateIf` | decorator | `@ValidateIf(condition: (object, value) => boolean, options?)` | | `Allow` | decorator | `@Allow(options?)` | | `ValidateNested` | decorator | `@ValidateNested(options?)` | | `IsDefined` | decorator | `@IsDefined(options?)` | | `IsNotEmpty` | decorator | `@IsNotEmpty(options?)` | | `IsEmpty` | decorator | `@IsEmpty(options?)` | | `IsIn` | decorator | `@IsIn(values: readonly any[], options?)` | | `IsNotIn` | decorator | `@IsNotIn(values: readonly any[], options?)` | | `IsString` | decorator | `@IsString(options?)` | | `IsNumber` | decorator | `@IsNumber(numberOptions?: IsNumberOptions, options?)` | | `IsInt` | decorator | `@IsInt(options?)` | | `IsBoolean` | decorator | `@IsBoolean(options?)` | | `IsDate` | decorator | `@IsDate(options?)` | | `IsArray` | decorator | `@IsArray(options?)` | | `IsObject` | decorator | `@IsObject(options?)` | | `IsEnum` | decorator | `@IsEnum(entity: object, options?)` | | `Min` | decorator | `@Min(minValue: number, options?)` | | `Max` | decorator | `@Max(maxValue: number, options?)` | | `IsPositive` | decorator | `@IsPositive(options?)` | | `IsNegative` | decorator | `@IsNegative(options?)` | | `MinLength` | decorator | `@MinLength(min: number, options?)` | | `MaxLength` | decorator | `@MaxLength(max: number, options?)` | | `Length` | decorator | `@Length(min: number, max?: number, options?)` | | `Matches` | decorator | `@Matches(pattern: RegExp, options?)` or `@Matches(pattern: string \| RegExp, modifiers?: string, options?)` | | `IsEmail` | decorator | `@IsEmail(emailOptions?: object, options?)` | | `IsUUID` | decorator | `@IsUUID(version?, options?)` | | `IsUrl` | decorator | `@IsUrl(urlOptions?: object, options?)` | | `ArrayMinSize` | decorator | `@ArrayMinSize(min: number, options?)` | | `ArrayMaxSize` | decorator | `@ArrayMaxSize(max: number, options?)` | | `ArrayNotEmpty` | decorator | `@ArrayNotEmpty(options?)` | | `ArrayUnique` | decorator | `@ArrayUnique(identifier?: (item) => any, options?)` | | `ArrayContains` | decorator | `@ArrayContains(values: any[], options?)` | | `ArrayNotContains` | decorator | `@ArrayNotContains(values: any[], options?)` | | `Equals` | decorator | `@Equals(comparison, options?)` | | `NotEquals` | decorator | `@NotEquals(comparison, options?)` | | `IsNotEmptyObject` | decorator | `@IsNotEmptyObject(objectOptions?: { nullable?: boolean }, options?)` | | `IsInstance` | decorator | `@IsInstance(targetType: Function, options?)` | | `MinDate` | decorator | `@MinDate(date: Date \| (() => Date), options?)` | | `MaxDate` | decorator | `@MaxDate(date: Date \| (() => Date), options?)` | | `IsDivisibleBy` | decorator | `@IsDivisibleBy(num: number, options?)`. Needs `validator`. | | `IsTimeZone` | decorator | `@IsTimeZone(options?)` | | `IsPhoneNumber` | decorator | `@IsPhoneNumber(region?: string, options?)`. Needs `libphonenumber-js`. | | `IsNumberString`, `IsBooleanString`, `IsDateString`, `IsISO8601`, `IsAlpha`, `IsAlphanumeric`, `IsAscii`, `IsLowercase`, `IsUppercase`, `Contains`, `NotContains`, `IsJSON`, `IsJWT`, `IsHexColor`, `IsHexadecimal`, `IsMongoId`, `IsIP`, `IsBase64`, `IsCreditCard`, `IsCurrency`, `IsDecimal`, `IsFQDN`, `IsLatLong`, `IsPostalCode`, `IsSemVer`, `IsMobilePhone`, `IsStrongPassword` | decorator | String formats, with class-validator's signatures. Need `validator`. | ### Custom validators | Export | Kind | Signature / description | | --- | --- | --- | | `ValidatorConstraint` | decorator | `@ValidatorConstraint(options?: { name?: string; async?: boolean })`. Marks a class with `validate(value, args)` (and optionally `defaultMessage(args)`) as a validator. | | `Validate` | decorator | `@Validate(constraintClass, constraints?: any[], options?)` | | `registerDecorator` | function | `registerDecorator({ name, target, propertyName, constraints?, options?, async?, validator })`. Build a validation decorator. | | `ValidateBy` | function | `ValidateBy({ name, constraints?, validator, async? }, options?)`. A property decorator from a validator. | | `buildMessage` | function | `buildMessage((eachPrefix, args) => string, options?)`. A `defaultMessage` with the `each value in ` prefix. | | `ValidatorConstraintInterface` | type | `{ validate(value, args?): boolean \| Promise; defaultMessage?(args?): string }` | ### Transformation | Export | Kind | Signature / description | | --- | --- | --- | | `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. | | `Transform` | decorator | `@Transform(transformFn: (params: TransformFnParams) => any, options?: TransformDecoratorOptions)`. Change a property's value while the body becomes the DTO. | | `Expose` | decorator | `@Expose(options?: ExposeOptions)`, on a property or a class. `options.name` is the key in plain objects; `toClassOnly` / `toPlainOnly` limit the direction. | | `Exclude` | decorator | `@Exclude(options?: ExcludeOptions)`, on a property or a class. | | `plainToInstance` | function | `plainToInstance(cls, plain, options?: ClassTransformOptions)`. Convert a plain object (or an array) into instances with Megh's decorators. | | `instanceToPlain` | function | `instanceToPlain(object, options?: ClassTransformOptions)`. Convert an instance (or an array) into a plain object. | | `ClassTransformOptions` | type | `{ excludeExtraneousValues?, enableImplicitConversion?, exposeUnsetFields? }` | | `TransformationType` | enum | The direction passed to a `@Transform` function, as in class-transformer. | ### Mapped types | Export | Kind | Signature | | --- | --- | --- | | `PartialType` | function | `PartialType(Base: Constructor): Constructor>` | | `PickType` | function | `PickType(Base: Constructor, keys: K[]): Constructor>` | | `OmitType` | function | `OmitType(Base: Constructor, keys: K[]): Constructor>` | ### Running validation yourself | Export | Kind | Description | | --- | --- | --- | | `validateDto` | function | `validateDto(target, value): DtoValidationResult`. Convert and validate a value with Megh's decorators. Throws for a DTO with async validators. | | `validateDtoAsync` | function | `validateDtoAsync(target, value): Promise>`. The same, waiting for async validators. | | `transformAndValidate` | function | `transformAndValidate(target, value, options?): Promise>`. The same for any DTO: Megh's validator for Megh DTOs, class-validator and class-transformer for theirs. | | `Validator` | class | Rule-based validator for plain objects: `new Validator(rules: ValidationProps, options?).validate(obj)` returns `[issues, obj]`. | | `validateOrThrow` | function | `validateOrThrow(obj, rules: ValidationProps, options?)`. Validate with `Validator` and throw `BadRequestException` on failure. | | `isMeghValidatorClass` | function | Whether a class uses Megh's validation decorators. | ### Validation types | Export | Kind | Description | | --- | --- | --- | | `ValidationOptions` | type | Options every validation decorator takes. | | `ValidationArguments` | type | What a message function receives. | | `IsNumberOptions` | type | `{ allowNaN?, allowInfinity?, maxDecimalPlaces? }`. | | `TypeOptions` | type | Options for `@Type`. `discriminator` isn't supported yet. | | `TypeHelpOptions` | type | What a `@Type` function receives. | | `TransformFnParams` | type | What a `@Transform` function receives. | | `TransformDecoratorOptions` | type | Options for `@Transform`. | | `ValidationIssue` | type | One issue from `validateDto`. | | `DtoValidationResult` | type | Result of `validateDto`. | | `RequestValidationIssue` | type | One issue from `transformAndValidate`. | | `RequestValidationResult` | type | Result of `transformAndValidate`. | | `ValidationRule` | type | A `Validator` rule: `{ type: "string" \| "number" \| "boolean", required?, optional?, message?, min?, max?, exact? }`. | | `ValidationProps` | type | `Record`. | | `ValidateOptions` | type | `{ location?: "header" \| "queryparam" \| "param" \| "body" \| "custom" }`, for `Validator`. | | `ValidatorIssue` | type | One issue from `Validator`. | ## Dependency injection Guide: [Dependency injection](/core-concept/dependency-injection). | Export | Kind | Signature / description | | --- | --- | --- | | `Injectable` | decorator | `@Injectable()`. Make a class resolvable by the container. Constructor parameters are injected from their types. | | `AppService` | decorator | `@AppService` or `@AppService()`. Same as `@Injectable()`, for service classes. | | `inject` | function | `inject(id: ServiceIdentifier, options?: InjectOptions): T`. Resolve a dependency, usually in a field initializer. With `{ optional: true }` it returns `undefined` when nothing is registered. | | `Inject` | decorator | `@Inject(id, options?: InjectOptions)`. Inject a token, string or class into a constructor parameter or property, for interface, union and primitive types. | | `Optional` | decorator | `@Optional()`. Inject `undefined` into a constructor parameter that can't be resolved, instead of failing. | | `createInjectDecorator` | function | `createInjectDecorator(factory: () => unknown)`. Build a property or parameter decorator that injects `factory()`. | | `MeghContainer` | const | The container: `get(id)`, `set(id, value)`, `has(id)`, `reset(options?)`. | | `Token` | class | `new Token(name?: string)`. A typed identifier for values that aren't classes. | | `ContainerError` | class | Thrown when the container can't resolve or construct a service. | | `ContainerApi` | interface | The `MeghContainer` surface. | | `ServiceIdentifier` | type | A class, abstract class, `Token` or string. | | `Constructable` | type | `new (...args: any[]) => T`. | | `InjectOptions` | type | `{ optional?: boolean }`. | ## Middleware Guide: [Middleware](/core-concept/middleware). | Export | Kind | Signature / description | | --- | --- | --- | | `MeghMiddleware` | abstract class | `invoke(req: IRequest, res?: IResponse): Promise`. | | `AppMiddleware` | decorator | `@AppMiddleware`. Register a middleware class for DI. Throws if it has no `invoke` method. | | `UseMiddleware` | decorator | `@UseMiddleware(middleware \| middleware[])`. Apply middleware classes or instances to a controller or route. | Global middleware is registered with `app.useMiddlewares([...])`. ## Authentication and authorization Guide: [Authentication](/core-concept/authentication). | Export | Kind | Signature / description | | --- | --- | --- | | `MeghAuthentication` | abstract class | `authenticate(request: IRequest): TUser \| null \| undefined \| Promise<...>`. The return value becomes `request.user`. Register with `app.useAuthentication()`. | | `CanAuthorize` | decorator | `@CanAuthorize`. Mark a class with an `authorize(req, options?)` method as an authorization handler and register it for DI. | | `Public` | decorator | `@Public()`. Leave a controller or route out of the `useAuthorization` default. Inline routes use `.public()`. | | `UseAuthorizationOptions`, `AuthorizationDefault` | types | `{ default?: 'authenticated' \| true \| AuthorizedOptions }` for `useAuthorization()`. | | `Authorized` | decorator | `@Authorized()`, `@Authorized(name: string)` or `@Authorized({ name?, ...options })`. Require authorization on a controller or route. Extra options are passed to `authorize()`. | | `AuthorizeClass` | interface | `{ authorize(req: IRequest, options?: any): unknown }`. Return `false` or throw to deny with 403. | | `AuthorizedOptions` | type | `string \| { name?: string; [key: string]: any }`. | ## Security headers and rate limiting Guide: [Security Hardening](/production/security#add-security-headers). | Export | Kind | Signature / description | | --- | --- | --- | | `SecurityHeadersOptions` | type | `{ contentSecurityPolicy?, strictTransportSecurity?, frameOptions?, referrerPolicy?, crossOriginOpenerPolicy?, crossOriginResourcePolicy?, crossOriginEmbedderPolicy?, headers? }` for `useSecurityHeaders()`. `false` leaves a header out. | | `ContentSecurityPolicyOptions` | type | `{ directives?: Record; useDefaults?: boolean; reportOnly?: boolean }`. | | `CspDirectiveValue` | type | `string \| string[] \| boolean`. `true` is a bare directive, `false` removes it. | | `StrictTransportSecurityOptions` | type | `{ maxAge?: number; includeSubDomains?: boolean; preload?: boolean }`. | | `ReferrerPolicy` | type | A `Referrer-Policy` token, such as `"no-referrer"`. | | `RateLimit` | decorator | `@RateLimit(options: RouteRateLimitOptions \| false)`. A controller's or route's own limit and counter, or `false` for none. Works without `useRateLimit()`. | | `RateLimitOptions` | type | `{ max?, window?, key?, ipv6Subnet?, skip?, store?, redis?, headers?, message?, failOpen?, global? }` for `useRateLimit()`. `redis` takes `RedisConnectionOptions`. `ipv6Subnet` (default 64) groups IPv6 clients by prefix with the default key. | | `RouteRateLimitOptions` | type | `{ max?: number; window?: RateLimitWindow; key?: (req) => string \| Promise }`. | | `RateLimitWindow` | type | `number \| string`. Milliseconds, or a duration such as `'30s'`, `'15m'`, `'1 hour'`. | | `RateLimitStore` | interface | `{ hit(key, windowMs): RateLimitHit \| Promise; reset?(key); close?() }`. Where counts live. | | `RateLimitHit` | type | `{ count: number; resetAt: number }`. `resetAt` is epoch milliseconds. | | `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. | | `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. | | `RedisRateLimitStore` | class | `new RedisRateLimitStore(connection?: RedisConnectionOptions, { prefix? })`. Counts in Redis, shared by replicas. Connects on first use; `close()` closes it. `prefix` defaults to `"megh:rate-limit:"`. | ## Configuration and environment Guide: [Configuration](/core-concept/configuration). | Export | Kind | Signature / description | | --- | --- | --- | | `MeghConfig` | abstract class | `config(env: Environment): T`. Base class for a config class. | | `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. | | `AppConfigOptions` | type | `{ schema?: Constructor }`. | | `validateEnv` | function | `validateEnv(EnvDto, source?)` validates environment variables against a DTO class and returns them converted. | | `ConfigValidationError` | class | Thrown for an invalid environment or config; `source` and `issues` say what failed. | | `GetConfig` | function | `GetConfig(ConfigClass)` returns the class's `config()` result; `GetConfig(token: string \| symbol)` returns the value registered for the token. | | `MeghConfigClass` | type | A `MeghConfig` subclass. | | `Environment` | class | Reads `.env` merged with `process.env` (which wins): `get(key)`, `getOrThrow(key)`, `getAll()`, and static `reload()` to re-read `.env`. | | `EnvironmentVariableNotFound` | class | Error thrown by `getOrThrow()` for a missing variable; the name is in `key`. | ## ORM Guides: [ORM](/advanced/orm), [Models](/advanced/orm/models), [Queries](/advanced/orm/queries), [Relations](/advanced/orm/relations), [Migrations](/advanced/orm/migrations), [Seeding](/advanced/orm/seeding), [Query builder](/advanced/orm/query-builder). The ORM ships inside `@meghjs/core` as a built-in plugin. Connect it with `app.useMeghORM()`. ### Models | Export | Kind | Description | | --- | --- | --- | | `Model` | abstract class | Base class for models. Static query methods (`query`, `find`, `findOrFail`, `where`, `with`, `create`, `createMany`, `insert`, `upsert`, `firstOrNew`, `firstOrCreate`, `updateOrCreate`, `paginate`, `transaction`, `on`, `withoutGlobalScope`, …), instance methods (`save`, `fill`, `delete`, `restore`, `refresh`, `fresh`, `touch`, `replicate`, `increment`, `makeVisible`, `related`, …) and settings (`hidden`, `visible`, `appends`, `globalScopes`, `morphType`, …). | | `ModelQuery` | class | A query on a model. Nothing runs until `get()`, `first()`, `count()`, `pluck()`, `paginate()`, `chunk()`, `lazy()`, `stream()`, `update()` or `delete()`. | | `HasRelation` | class | A `hasMany` / `hasOne` / `morphMany` / `morphOne` relation of one model instance: `user.related("posts")`. | | `PivotRelation` | class | The pivot rows of a `belongsToMany` relation: `user.related("roles").attach([1, 2])`. | | `ORM_CONNECTION` | const | `Token>` holding the ORM's root Kysely instance. | | `modelSchema` | function | `modelSchema(cls): SchemaObject \| undefined`. JSON schema for a model's columns. | | `getModelMetadata` | function | `getModelMetadata(cls): ModelMetadata \| undefined`. Column and table metadata from the decorators. | ### Model decorators | Export | Kind | Signature | | --- | --- | --- | | `Table` | decorator | `@Table(name?: string)`. Defaults to the plural snake_case class name. | | `Column` | decorator | `@Column(typeOrOptions?: ColumnType \| ColumnOptions, options?: ColumnOptions)` | | `PrimaryKey` | decorator | `@PrimaryKey(options?: ColumnOptions)` | | `AutoIncrement` | decorator | `@AutoIncrement()`. A generated integer column. | | `Identity` | decorator | Alias of `AutoIncrement`. | | `CreatedAt` | decorator | Set to the current time on insert. | | `UpdatedAt` | decorator | Set to the current time on every insert and update. | | `DeletedAt` | decorator | Soft deletes: `delete()` sets this column instead of removing the row. | | `HasMany` | decorator and type | `@HasMany(related: () => C, options?: HasOptions)`. As a type, the field type of a one-to-many relation. | | `HasOne` | decorator and type | `@HasOne(related: () => C, options?: HasOptions)`. | | `BelongsTo` | decorator and type | `@BelongsTo(related: () => C, options?: BelongsToOptions)`. | | `BelongsToMany` | decorator and type | `@BelongsToMany(related: () => C, options?: BelongsToManyDecoratorOptions)`. | | `HasManyThrough` | decorator and type | `@HasManyThrough(related: () => C, through: () => T, options?: ThroughOptions)`. | | `HasOneThrough` | decorator and type | `@HasOneThrough(related: () => C, through: () => T, options?: ThroughOptions)`. | | `MorphMany` | decorator and type | `@MorphMany(related: () => C, name: string, options?: MorphOptions)`. | | `MorphOne` | decorator and type | `@MorphOne(related: () => C, name: string, options?: MorphOptions)`. | | `MorphTo` | decorator and type | `@MorphTo(targets: () => C[], name?: string)`. | ### Relation functions For models that declare relations as fields instead of decorators. | Export | Kind | Signature | | --- | --- | --- | | `hasMany` | function | `hasMany(related: () => C, foreignKey?: string, localKey?: string)` | | `hasOne` | function | `hasOne(related: () => C, foreignKey?: string, localKey?: string)` | | `belongsTo` | function | `belongsTo(related: () => C, foreignKey?: string, ownerKey?: string)` | | `belongsToMany` | function | `belongsToMany(related: () => C, options?: BelongsToManyOptions)` | | `hasManyThrough` | function | `hasManyThrough(related: () => C, through: () => T, options?: ThroughOptions)` | | `hasOneThrough` | function | `hasOneThrough(related: () => C, through: () => T, options?: ThroughOptions)` | | `morphMany` | function | `morphMany(related: () => C, name: string, localKey?: string)` | | `morphOne` | function | `morphOne(related: () => C, name: string, localKey?: string)` | | `morphTo` | function | `morphTo(targets: () => C[], name?: string)`. `name` defaults to the field name. | | `morphTypeOf` | function | `morphTypeOf(cls): string`. The value `_type` columns store for a model: `static morphType`, or its table. | ### Connection and configuration | Export | Kind | Description | | --- | --- | --- | | `createDatabase` | function | `createDatabase(options: ResolvedDatabaseOptions): Kysely`. | | `resolveDatabaseOptions` | function | `resolveDatabaseOptions(options?, env?)`. Apply environment variables and the URL to database options. | | `DatabaseConfigError` | class | Thrown for invalid database settings. | | `ormPlugin` | const | The ORM as a Megh plugin. Registered automatically. | | `setNamingStrategy` | function | `setNamingStrategy("preserve" \| "snake_case")`. | | `getNamingStrategy` | function | The current naming strategy. | | `DatabaseOptions` | interface | Settings for `useMeghORM()`. | | `ResolvedDatabaseOptions` | interface | Settings after the environment and URL are applied. | | `Dialect` | type | `"postgres" \| "mysql" \| "sqlite" \| "mssql"`. | | `PoolOptions` | interface | Connection pool settings. | | `NamingStrategy` | type | `"preserve" \| "snake_case"`. | ### Query builder | Export | Kind | Description | | --- | --- | --- | | `DB` | const | Table queries without models: `DB.table(name)`, `DB.transaction(fn)`. | | `TableQuery` | class | A query on one table, built with `DB.table()`. | | `WhereClauses` | class | `where` conditions shared by queries and groups. | | `WhereGroup` | class | The conditions inside `where((q) => …)`. | | `Operator` | type | Comparison operators accepted by `TableQuery`. | ### Schema and migrations | Export | Kind | Description | | --- | --- | --- | | `Schema` | class | Creates, changes and drops tables. Migrations defined with `defineMigration` receive one. | | `Blueprint` | class | The columns and indexes of a table being created or changed. | | `ColumnDefinition` | class | A column being added. Columns are NOT NULL unless `nullable()`. | | `ForeignKeyDefinition` | class | A foreign key: `table.foreign("user_id").references("users.id")`. | | `SchemaError` | class | Thrown for invalid schema operations. | | `Migrations` | class | `new Migrations(db, options)`. Runs and rolls back migrations. | | `MigrationError` | class | Thrown when a migration fails. Carries the migration name and those completed. | | `defineMigration` | function | `defineMigration({ up, down? })`. A migration written with the schema builder. | | `createMessagingTables`, `dropMessagingTables` | functions | `(schema: Schema) => Promise`. Create or drop `megh_outbox`, `megh_locks` and `megh_dedupe`. `megh make:messaging` writes a migration that calls them. | | `readMigrationFolder` | function | `readMigrationFolder(folder): Promise>`. | | `Migration` | interface | A migration as the runner calls it. | | `SchemaMigration` | interface | A migration written with the schema builder. | | `MigrationsOptions` | interface | Options for `Migrations`. | | `MigrationStatus` | interface | One migration's status. | | `ReferentialAction` | type | `ON DELETE` / `ON UPDATE` actions. | | `SchemaDialect` | type | `"postgres" \| "mysql" \| "sqlite" \| "mssql"`. | ### Seeders and factories | Export | Kind | Description | | --- | --- | --- | | `Seeders` | class | `new Seeders(db, options?)`. Runs seeders. | | `SeedError` | class | Thrown when a seeder fails. | | `defineSeeder` | function | Identity helper that type-checks a seeder. | | `readSeederFolder` | function | `readSeederFolder(folder): Promise>`. | | `seederName` | function | A seeder's name from its file name. | | `ENTRY_SEEDER` | const | `"database"`, the seeder `run()` starts from when given no name. | | `Seeder` | interface | A seeder. | | `SeedContext` | interface | What a seeder's `run()` receives. | | `SeedersOptions` | interface | Options for `Seeders`. | | `Factory` | class | Builds and creates model instances from a definition. | | `defineFactory` | function | `defineFactory(model, definition: (ctx: FactoryContext) => FactoryAttributes): Factory`. | | `useFaker` | function | `useFaker(faker)`. Set the Faker instance factories use. | | `getFaker` | function | `getFaker(): Promise`. The Faker instance, loaded from the app on first use. | | `FactoryAttributes` | type | Attributes a factory definition returns. | | `FactoryContext` | interface | What a factory definition receives. | ### ORM types | Export | Kind | Description | | --- | --- | --- | | `ColumnType` | type | Column types, which pick the SQL type and value conversion. | | `ColumnOptions` | interface | Options for `@Column`. | | `ColumnMetadata` | interface | A column's metadata. | | `ModelMetadata` | interface | A model's metadata. | | `HasOptions` | interface | Options for `@HasMany` and `@HasOne`. | | `BelongsToOptions` | interface | Options for `@BelongsTo`. | | `BelongsToManyOptions` | interface | Options for `belongsToMany()`. | | `BelongsToManyDecoratorOptions` | interface | Options for `@BelongsToMany`, including `pivotColumns`. | | `ThroughOptions` | interface | Keys of a through relation: `firstKey`, `secondKey`, `localKey`, `secondLocalKey`. | | `MorphOptions` | interface | Options for `@MorphMany` and `@MorphOne`: `localKey`. | | `ModelEvent` | type | Lifecycle events for `Model.on()`: `saving`, `creating`, `updated`, `deleted`, `restored`, … | | `Cast` | type | A column cast: a built-in name or a `CustomCast`. | | `CustomCast` | interface | `{ get, set }` conversion between database and model values. | | `Columns` | type | A model's column fields. | | `ColumnKeys` | type | Names of a model's columns. | | `RelationKeys` | type | Names of a model's relations. | | `RelationPaths` | type | Relation paths for `with()`, up to three levels. | | `BelongsToManyKeys` | type | Names of `belongsToMany` relations. | | `HasRelationKeys` | type | Names of `hasMany` / `hasOne` relations. | | `PivotOf` | type | Pivot columns of a `belongsToMany` relation. | | `TimestampKeys` | type | Timestamp columns when `timestamps = true`. | | `Row` | type | A model's row as loaded from the database. | | `EagerShape` | interface | How a `with()` constraint narrows a loaded relation: its columns, relations and counts. | | `ModelClass` | interface | The static side of a model class. | | `CreateInput` | type | `create()` input. | | `UpdateInput` | type | `update()` / `fill()` input. | | `PrimaryKeyValue` | type | Value type of a model's primary key. | | `TableOf` | type | Kysely table interface for a model. | | `DatabaseOf` | type | Kysely database interface for a set of models. | | `ComparisonOperator` | type | Operators accepted by `where`. | | `Counted` | type | The `_count` field `withCount()` adds. | | `Aggregated` | type | The `__` field `withSum()`, `withAvg()`, `withMin()` and `withMax()` add. | | `Existence` | type | The `_exists` field `withExists()` adds. | | `SubQuery` | interface | A query `whereIn()` and `whereExists()` take: a model query or a `DB.table()` query. | | `JoinOperator` | type | Operators for `join()` conditions on model queries. | | `CursorPageRequest` | interface | Request for `cursorPaginate()`. | | `CursorPaginated` | interface | Result of `cursorPaginate()`. | | `SimplePaginated` | interface | Result of `simplePaginate()` (no total). | | `ModelAt` | type | The model at the end of a relation path. | | `RelationConstraint` | type | A function that narrows a related query. | | `EagerConstraints` | type | `with({ … })` input: a constraint per relation path. | | `Scope` | type | A reusable query scope. | | `RelatedRef` | type | A related row's key, or the related model itself. | ## Events Guide: [Events](/advanced/events). | Export | Kind | Signature / description | | --- | --- | --- | | `MeghEvent` | abstract class | `new MyEvent(payload)`. Base class for events; sets `name` and `timestamp`. | | `MeghEventListener` | abstract class | `handler(event: TEvent): void \| Promise`. Base class for listeners. | | `EventDispatcher` | class | `dispatch(event: MeghEvent, option?: EventDispatchOptions): Promise`. | | `EventRegistry` | class | `EventRegistry.getInstance()`, then `register(EventClass, listener)`, `once`, `unregister`, `getListeners`, `clear`. | | `EventQueue` | class | The in-memory queue for `queue: true` dispatches. `EventQueue.getInstance()`, `getFailedJobs()`, `clearFailed()`, `whenIdle()`. | | `EventDispatchOptions` | type | `{ queue?, delay?, retry?, retryDelay?, broadcast?, outbox? }`. `delay` is ms or `"500ms"`, `"5s"`, `"2m"`, `"1h"`, `"1d"`. `outbox` applies to distributed events. | | `DistributedEvent` | decorator | `@DistributedEvent(type?: string)`. Dispatching the event publishes it on the messaging transport. `type` defaults to the class name. | | `Listener` | decorator | `@Listener(EventClass, options?: ListenerOptions)`. Register a listener class, resolved through DI and started in `app.run()`. | | `ListenerOptions` | interface | `{ group?, retry?, dedupe?, concurrency? }`. Apply to distributed events. | | `startListeners`, `stopListeners` | functions | Start or stop every `@Listener`. The application calls them in `run()` and `close()`. | | `getRegisteredListeners` | function | Every `@Listener` record, in declaration order. | | `distributedEventType` | function | `distributedEventType(eventOrClass)`. The wire type of a distributed event, or `undefined` for a local one. | | `BroadcastOption` | type | `SocketBroadcastOption \| false`. | | `SocketBroadcastOption` | type | `{ type: "socket"; channel: string; room?: string }`. | | `MeghEventInterface` | interface | `{ name: string; timestamp: number }`. | | `MeghEventListenerInterface` | interface | `{ handler(event): void \| Promise }`. | | `FailedEventJob` | interface | A listener that kept failing after its retries. | | `Broadcast` | interface | `{ to: string; private?: boolean; payload: any }`. | | `parseDelay` | function | `parseDelay(input: string \| number): number`. Parse a delay into milliseconds. | ## Queue Guide: [Queue](/advanced/queue). | Export | Kind | Signature / description | | --- | --- | --- | | `Queue` | decorator | `@Queue(config: QueueConfig)`. Register a `MeghQueue` subclass for DI and start its worker unless `worker: false`. | | `JobHandler` | decorator | `@JobHandler(name: string)`. Mark a method as the processor for a named job. | | `MeghQueue` | abstract class | Produces and consumes jobs: `add`, `delay`, `dispatch`, `getJob`, `getJobs`, `clean`, `pause`, `resume`, `close`, `raw`, `hasWorker`, `on`, `startWorker`, and the `name` and `transport` getters. `getJob`, `getJobs`, `clean`, `pause` and `resume` throw on `rabbitmq`. | | `MeghWorker` | decorator | `@MeghWorker(config: WorkerConfig)`. Register a standalone worker class. Doesn't start it. | | `MeghWorkerBase` | abstract class | `process(job: Job): Promise`. Base class for standalone workers; `start()`, `close()`, `isRunning()`. | | `QueueConfig` | interface | `{ name, transport?, sync?, redis?, worker?, handler?, defaultJobOptions? }`. | | `WorkerConfig` | interface | `{ queue, transport?, sync?, redis?, concurrency?, autoStart? }`. | | `QueueTransportOptions` | interface | `{ transport?: "memory" \| "redis" \| "rabbitmq"; sync?: boolean; redis?: RedisConnectionOptions }`. | | `Job` | interface | `{ id?, name, data, queueName, attemptsMade, timestamp, opts, updateProgress(), log() }`. `attemptsMade` is 1 on the first run. | | `JobOptions` | interface | `{ delay?, attempts?, backoff?, jobId?, priority?, removeOnComplete?, removeOnFail? }`. | | `JobState` | type | `"completed" \| "waiting" \| "active" \| "delayed" \| "failed" \| "paused"`. | | `setQueueTransport` | function | `setQueueTransport(transport: TransportName \| undefined, options?: { sync?: boolean })`. Set the transport for queues created afterwards. | | `resolveQueueTransport` | function | `resolveQueueTransport(explicit?)`. The transport in effect: explicit, then `setQueueTransport()`, then `MEGH_QUEUE_TRANSPORT`, then `MEGH_MESSAGING_TRANSPORT`, then `"memory"`. | | `waitForMemoryQueues` | function | Resolve when every in-memory queue is idle. For tests. | | `resetMemoryQueues` | function | Clear every in-memory queue. For tests. | | `MemoryJob` | class | A job in the in-memory queue. | | `MemoryJobState` | type | `"waiting" \| "delayed" \| "active" \| "completed" \| "failed"`. | | `getRegisteredWorkers` | function | Every `@MeghWorker` class, in declaration order. | | `startRegisteredWorkers` | function | Resolve and start every `@MeghWorker` whose `autoStart` isn't `false`. The application calls it at boot. | | `attachWorkerLogging` | function | `attachWorkerLogging(worker, queue)`. Log failed jobs and worker errors. | ```ts add(data: T, options?: JobOptions): Promise> add(name: string, data: T, options?: JobOptions): Promise> delay(data: T, delayMs: number, options?: JobOptions): Promise> delay(name: string, data: T, delayMs: number, options?: JobOptions): Promise> dispatch(name: string, data: T, delayMs?: number, options?: JobOptions): Promise> ``` ## Messaging Guide: [Messaging](/advanced/messaging). | Export | Kind | Signature / description | | --- | --- | --- | | `Messaging` | const | The app-wide `MessageBus`. | | `MessageBus` | class | `configure(config?)`, `publish(type, data, options?)`, `listen(type, handler, options)`, `deadLetters(limit?)`, `retryDeadLetter(id)`, `discardDeadLetter(id)`, `stats()`, `ping()`, `flushOutbox()`, `whenIdle()`, `fake()`, `restore()`, `close()`, `reset()`, and the `transport` and `isConfigured` getters. | | `MessagingConfig` | interface | `{ transport?, url?, redis?, rabbitmq?, memory?, source?, retry?, dedupe?, maxPayloadBytes?, allowInsecure?, outbox? }` for `useMessaging()`. | | `PublishMessageOptions` | interface | `{ delay?, id?, outbox? }`. | | `ListenOptions` | interface | `{ group, retry?, dedupe?, concurrency? }`. | | `MessageHandler` | type | `(data: T, envelope: MessageEnvelope) => void \| Promise`. | | `MessagingStats` | interface | `{ published, processed, retried, failed, duplicates }`. | | `RetryPolicy` | interface | `{ retries?: number; backoff?: number; maxBackoff?: number }`. Defaults 3, 1000 ms, 60000 ms. | | `DedupeOptions` | interface | `{ window?: number; store?: "auto" \| "memory" \| "redis" \| "database" }`. The window defaults to 24 hours. | | `OutboxOptions` | interface | `{ pollInterval?: number; batchSize?: number }`. Defaults 1000 ms and 100. | | `MessageEnvelope` | interface | The CloudEvents 1.0 envelope: `id`, `type`, `source`, `time`, `specversion`, `datacontenttype`, `traceparent?`, `meghrequestid?`, `meghtarget?`, `data`. | | `DeadLetter` | interface | `{ id, group, envelope, error, attempts, failedAt }`. | | `MessagingFake` | class | Returned by `Messaging.fake()`. `expectDispatched`, `expectNotDispatched`, `expectNothingDispatched`, `dispatched`, `expectPublished`, `published`, `expectQueued`, `queued`, `expectNothingQueued`, `all`, `clear`. | | `MessagingAssertionError` | class | Thrown by a failed `MessagingFake` expectation. | | `FakeRecord` | type | One recorded event, message or job. | | `TransportName` | type | `"memory" \| "redis" \| "rabbitmq"`. | | `Transport` | interface | A messaging adapter: `connect`, `publish`, `subscribe`, `ensureGroup`, `deadLetter`, `listDeadLetters`, `retryDeadLetter`, `discardDeadLetter`, `ping`, `close`, `raw`, plus `name` and `capabilities`. Pass one as `transport` to use your own broker. | | `TransportCapabilities` | interface | `{ durable, distributed, delay, replay, ordering }`. | | `MemoryTransport`, `RedisTransport`, `RabbitMqTransport` | classes | The built-in transports. | | `MemoryTransportOptions`, `RedisTransportOptions`, `RabbitMqTransportOptions` | interfaces | Their options. | | `RedisConnectionOptions` | interface | `{ url?, host?, port?, username?, password?, db?, tls?, prefix? }`. Used by messaging, queues, the cache and the rate limit store. | | `RabbitMqConnectionOptions` | interface | `{ url, exchange?, prefetch?, heartbeat? }`. | | `PublishOptions`, `SubscribeOptions`, `Subscription`, `DeliveryHandler` | types | The `Transport` contract. | | `createEnvelope`, `encodeEnvelope`, `decodeEnvelope` | functions | Build, encode (with the size limit) and decode CloudEvents envelopes. | | `OutboxRelay` | class | Publishes what `megh_outbox` holds. Started by the app when `outbox` is set. | | `MemoryDedupeStore`, `RedisDedupeStore`, `DatabaseDedupeStore` | classes | Where processed message IDs are kept. | | `DedupeStore` | interface | `claim(group, id)`, `complete(group, id)`, `release(group, id)`. | | `LockStore` | interface | `{ name; acquire(key, ttlMs, owner): Promise }`. Scheduler tick locks. | | `MemoryLockStore`, `DatabaseLockStore`, `RedisLockStore` | classes | The built-in lock stores. | | `MessagingStore`, `OutboxRecord`, `MessagingTable` | types | The database side of messaging, which Megh ORM provides. | | `setMessagingStore`, `getMessagingStore` | functions | Register or read the `MessagingStore`. Megh ORM registers one when it connects. | | `OUTBOX_TABLE`, `LOCKS_TABLE`, `DEDUPE_TABLE` | consts | `"megh_outbox"`, `"megh_locks"`, `"megh_dedupe"`. | ## Mail Guide: [Mail](/advanced/mail). | Export | Kind | Signature / description | | --- | --- | --- | | `Mailable` | abstract class | One kind of email. `envelope()`, `content()` (required), `attachments()`; each may be async. | | `Mailer` | class | Injectable. `to()`, `cc()`, `bcc()`, `send()`, `queue()`, `later(delay, mail)`, `mailer(name)`. Static: `configure()`, `fake()`, `restore()`, `close()`, `reset()`. | | `PendingMail` | class | Returned by `mailer.to()`: add recipients, then `send()`, `queue()` or `later()`. | | `MailFake` | class | Returned by `Mailer.fake()`. `assertSent`, `assertNotSent`, `assertNothingSent`, `assertSentCount`, `assertQueued`, `assertNotQueued`, `assertNothingQueued`, `sentOf`, `queuedOf`, `sent`, `queued`, `restore`. | | `SentMail` | class | A recorded message: `mailer`, `mailable`, `message`, `delay`, `hasTo()`, `hasCc()`, `hasBcc()`, `hasFrom()`. | | `MailConfig` | interface | `{ default?, from?, mailers?, queue?, allowFileAccess?, allowUrlAccess?, attachmentRoot? }` for `useMail()`. URL attachments are off unless `allowUrlAccess` is `true`. | | `MailQueueConfig` | interface | `{ name?, transport?, sync?, redis?, worker?, jobOptions? }`. | | `MailerConfig` | type | One mailer's settings: `{ transport: "smtp" \| "sendgrid" \| "mailgun" \| "postmark" \| "resend" \| "failover" \| "log" \| "array", ... }`, or a `MailTransport`. | | `MailTransport` | interface | `{ send(message: MailMessage): Promise<{ messageId?, response? } \| void>; close?() }`. Implement it for your own mailer. | | `MailMessage` | interface | A built message: `from`, `to`, `cc`, `bcc`, `replyTo`, `subject`, `html?`, `text?`, `attachments`, `headers`. | | `MailEnvelope`, `MailContent`, `MailAttachment`, `MailAddress`, `MailAddressLike` | types | What a `Mailable` returns, and address forms. | | `SentMessage`, `QueuedMessage` | types | What `send()` and `queue()`/`later()` resolve to. | | `SmtpTransport`, `SendGridTransport`, `MailgunTransport`, `PostmarkTransport`, `ResendTransport`, `FailoverTransport`, `LogTransport`, `ArrayTransport` | classes | The built-in transports. | | `MailQueue` | class | The `MeghQueue` behind `queue()` and `later()`. | | `MailError` | class | A misconfiguration, or a mailable that cannot be built. | | `MailTransportError` | class | A provider refused the message: `provider`, `status`, `body`. | | `mailConfigFromEnv`, `resolveMailConfig`, `mailerProblem` | functions | Read `MEGH_MAIL_*`, merge options over it, and check a mailer's settings. | ## Scheduler Guide: [Scheduler](/advanced/scheduler). | Export | Kind | Signature / description | | --- | --- | --- | | `ScheduledTask` | decorator | `@ScheduledTask()`. Mark a class as holding scheduled jobs and register it for DI. | | `Cron` | decorator | `@Cron(expression: string, options?: { name?, disabled?, perInstance?, timezone?, runOnInit? })`. Run the method on a cron expression (node-cron), once per tick across replicas unless `perInstance`. | | `Interval` | decorator | `@Interval(ms: number, options?: { name?, disabled?, perInstance? })`. Run the method every `ms` milliseconds, once per period across replicas unless `perInstance`. | | `Timeout` | decorator | `@Timeout(ms: number, options?: { name?, disabled? })`. Run the method once, `ms` milliseconds after start, on each instance. | | `MeghScheduler` | class | Runs the jobs of registered task classes: `addTaskClasses(tasks)`, `start()`, `stopAll()`, `setLockStore(store)`. The application creates one for `useScheduler()`. | Register task classes with `app.useScheduler([...])`. ## Cache Guide: [Caching](/advanced/caching). | Export | Kind | Signature / description | | --- | --- | --- | | `CacheManager` | class | Key/value cache with tag invalidation, backed by memory or Redis. TTLs are in seconds. | | `CacheManagerOptions` | type | `CacheOptions` fields (`provider?`, `redis?: RedisConnectionOptions`) plus `sweepIntervalMs?`. | ```ts CacheManager.configure(options?: CacheManagerOptions): void // defaults for new instances CacheManager.close(): Promise // static: close every instance get(key: string): Promise set(key: string, value: T, ttl?: number, tags?: string[]): Promise // ttl defaults to 3600 delete(key: string): Promise invalidateTags(tags: string | string[]): Promise sweep(): number close(): Promise ``` Enable it with `app.useCache(options?)`. ## Storage and uploads Guide: [File uploads](/advanced/file-uploads). | Export | Kind | Description | | --- | --- | --- | | `FileStorage` | class | Saves uploaded files under a root directory (`/public` by default) with an upload policy. Injectable. | | `UploadFileFromRequest` | function | `UploadFileFromRequest(req: IRequest, options?)`. Save the request's file. Options: `saveAs?`, `dest?`, `preserveFilename?`, `allowedExtensions?`. | | `MultipartFile` | type | An uploaded file from `@fastify/multipart`. | | `FileStorageInterface` | interface | `transform`, `save`, `saveAll`, `remove`. | | `FileStorageOptions` | interface | `UploadPolicy` plus `baseDir?`. | | `UploadPolicy` | interface | `{ allowedExtensions?, allowedMimeTypes?, maxFileSize? }`. `allowedExtensions` defaults to `DEFAULT_ALLOWED_UPLOAD_EXTENSIONS`; `maxFileSize` defaults to 50 MB. | | `DEFAULT_ALLOWED_UPLOAD_EXTENSIONS` | const | `readonly string[]`. The file extensions (with the dot) uploads accept by default: common images, documents, archives, audio and video. Spread it to extend the list. | | `SaveOptions` | interface | `UploadPolicy` plus `overwrite?`, `to?`, `transform?`. | | `SaveOptionsSingle` | interface | `SaveOptions` for `save()`. | | `SavedFileInfo` | interface | `{ filename, originalFilename, size, uploadPath, staticPath }`. | | `TransformOptions` | interface | Image transform: `{ resize?, format?, quality? }`. | ```ts configure(options: FileStorageOptions): this transform(options: TransformOptions): FileStorage save(file: MultipartFile, options?: SaveOptionsSingle): Promise saveAll(files: MultipartFile[], options?: SaveOptions): Promise remove(filepath: string): Promise getUploadFile(filePath: string) download(filepath: PathLike) downloadAs(filepath: PathLike, filename: string) ``` Upload parameters are declared with [`@UploadFile` and `@UploadFiles`](#parameters). ## Realtime Guide: [WebSocket](/microservices/websocket). | Export | Kind | Signature / description | | --- | --- | --- | | `SocketIoServer` | const | `Token`. The Socket.IO server, registered by `useSocketIo()`. | | `Subscribe` | decorator | `@Subscribe(event: string)`. Handle a Socket.IO event. | | `PrivateChannel` | decorator | `@PrivateChannel(channelResolver?: (socket) => string)`. Mark a subscriber method as private. | | `DispatchNow` | decorator | `@DispatchNow(event: string, options?: SocketDispatchOptions)`. Emit the method's return value as `event` after it runs. | | `SocketEventDispatcher` | class | `dispatch(event: string, data, options?: SocketDispatchOptions)`. Emit an event over Socket.IO. | | `SocketContextService` | class | The socket of the event being handled: `getSocket()`. | | `SocketDispatchOptions` | type | `{ room?, broadcast?, transports?, retry?, retryDelay? }`. | ## OpenAPI Guide: [OpenAPI](/microservices/openapi). ### Decorators | Export | Kind | Signature / description | | --- | --- | --- | | `OpenApi` | decorator | `@OpenApi(options: OpenApiOptions)`. Document a controller, route or property. | | `ApiResponse` | decorator | `@ApiResponse(status: number, type?: ResponseType \| ApiResponseOptions, description?: string)`. Document a response of a route or every route of a controller. | | `OpenApiProperty` | decorator | `@OpenApiProperty(options?)`. Document a DTO property (`ParamSchema` fields plus `isArray`, `items`, `nullable`, `readOnly`, …). | | `OpenApiSchema` | decorator | `@OpenApiSchema()`. Add the class to `components.schemas`. | | `OpenApiResponse` | function | Deprecated. `OpenApiResponse(code, model, description?)`. Documents a `{ code, status, data }` wrapper Megh doesn't send. Use `@ApiResponse`. | | `OpenApiOk` | function | Deprecated. `OpenApiResponse(200, model, "Success")`. | ### Functions | Export | Kind | Description | | --- | --- | --- | | `registerSchemaProvider` | function | `registerSchemaProvider(provider: SchemaProvider)`. Describe classes the DTO reader doesn't. | | `generateClassSchema` | function | `generateClassSchema(classType, options?: ClassSchemaOptions)`. JSON schema for a DTO class. | | `generateSwaggerSchema` | function | `generateSwaggerSchema(classes, extraClasses?)`. `components.schemas` for `@OpenApiSchema` classes. | | `inlineSchemaRefs` | function | Replace `#/components/schemas/*` refs with inline schemas. | | `normalizeParamsToJsonSchema` | function | `normalizeParamsToJsonSchema(params, requiredKeys?)`. Turn a `ParamsSchemaMap` into an object schema. | ### Options | Export | Kind | Description | | --- | --- | --- | | `OpenApiUiOptions` | type | Options for `useOpenApi()`: `info`, `routePrefix` (default `/swagger`), `provider` (`"default"` or `"scalar"`), `auth`, `servers`, `tags`, `security`, `components`, `uiConfig`, `scalar`, `logo`, `theme`, `openapi`, `paths`. | | `OpenApiOptions` | type | Options for `@OpenApi()` on a route: `summary`, `description`, `tags`, `params`, `query`, `headers`, `requestBody`, `response`, `exclude`, `deprecated`, `security`, … | | `OpenApiAuth` | type | `"bearer" \| "apiKey" \| SecuritySchemeObject`. | | `ApiResponseOptions` | interface | `{ type?, description?, contentType?, example? }`. | | `ResponseType` | type | A DTO class, `[Class]`, `Paginated(Class)`, a JSON schema or a `$ref`. | | `PaginatedType` | interface | What `Paginated(Class)` returns. | | `SchemaProvider` | type | `(cls) => SchemaObject \| undefined`. | | `ClassSchemaOptions` | type | `{ inline?, components? }` for `generateClassSchema`. | | `SchemaClass` | type | A DTO class. | | `ParamSchema` | type | Schema of one parameter. | | `ParamsSchemaMap` | type | `Record`. | | `RequestBodyOptions` | type | Options for `requestBody`. | | `RequestBodyMediaTypeOptions` | type | A media type whose `schema` may be a DTO class. | | `ResponseBodyOptions` | type | A response described as a JSON schema. | | `ResponsesOptions` | type | Responses keyed by status code. | | `SwaggerUiConfig` | interface | Swagger UI settings. | | `SwaggerUiLogo` | interface | Swagger UI top-bar logo. | | `SwaggerUiTheme` | interface | Swagger UI page title, CSS, scripts and favicon. | | `SwaggerUiThemeFile` | interface | A theme file. | | `SwaggerUiFavicon` | interface | A favicon file. | | `ScalarConfig` | interface | Scalar settings. | ### OpenAPI document types Types for the OpenAPI 3 document: `InfoObject`, `ContactObject`, `LicenseObject`, `ServerObject`, `ServerVariableObject`, `PathsObject`, `PathItemObject`, `OperationObject`, `ExternalDocumentationObject`, `ParameterObject`, `ParameterBaseObject`, `HeaderObject`, `SchemaObject`, `ArraySchemaObject`, `NonArraySchemaObject`, `BaseSchemaObject`, `ArraySchemaObjectType`, `NonArraySchemaObjectType`, `DiscriminatorObject`, `XMLObject`, `ReferenceObject`, `ExampleObject`, `MediaTypeObject`, `EncodingObject`, `RequestBodyObject`, `ResponsesObject`, `ResponseObject`, `LinkObject`, `CallbackObject`, `SecurityRequirementObject`, `ComponentsObject`, `SecuritySchemeObject`, `HttpSecurityScheme`, `ApiKeySecurityScheme`, `OAuth2SecurityScheme`, `OpenIdSecurityScheme` and `TagObject`. ## Logging Guide: [Logging](/advanced/logging). | Export | Kind | Signature / description | | --- | --- | --- | | `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. | | `LoggerConfig` | interface | `{ level?, pretty?, destination? }`. | | `buildLoggerOptions` | function | `buildLoggerOptions(config?, env?): pino.LoggerOptions`. The pino options Megh uses. | | `getRequestId` | function | `getRequestId(): string \| undefined`. The ID of the request being handled. | | `requestContext` | object | Per-request values: `get`, `getOrThrow`, `has`, `set`, `delete`, `user`, `getUser()`, `requestId`, `active`, `run(fn, init?)`. See [Request Context](/core-concept/request-context). | | `createContextKey` | function | `createContextKey(name): ContextKey`. A typed key for `requestContext`. | | `ContextKey`, `RequestContextInit` | types | A typed key, and `{ requestId?, user?, values? }` for `requestContext.run()`. | | `DEFAULT_REQUEST_ID_HEADER` | const | `"x-request-id"`. | | `RequestIdOptions` | type | `false \| { header?, generate? }`, for the `requestId` application option. | ```ts LoggerService.getPino(): pino.Logger // the shared instance LoggerService.configure(config?: LoggerConfig): pino.Logger // replace it LoggerService.child(bindings: pino.Bindings): pino.Logger ``` ## Health Guide: [Health checks](/advanced/health). | Export | Kind | Description | | --- | --- | --- | | `HealthCheck` | type | `() => unknown \| Promise`. Passes unless it throws, rejects or returns `false`. | | `HealthOptions` | interface | `{ path?, readyPath?, checks?, timeout? }`. Defaults: `/health`, `/ready`, 5000 ms. | | `HealthCheckResult` | interface | `{ status: "up" \| "down"; durationMs; error? }`. | | `ReadinessReport` | interface | `{ status: "ok" \| "error"; checks }`. | | `HealthRegistry` | class | Runs readiness checks and serves the health routes. The application creates one. | | `SKIP_GLOBAL_MIDDLEWARE` | const | Route config flag that makes `useMiddlewares` skip a route. | Enable with `app.useHealth(options?)` and add checks with `app.addHealthCheck(name, check)`. ## Plugins Guide: [Plugins](/advanced/plugins). | Export | Kind | Description | | --- | --- | --- | | `definePlugin` | function | `definePlugin(plugin: MeghPlugin): MeghPlugin`. Identity helper that type-checks a plugin. | | `MeghPlugin` | interface | `{ name: string; dependsOn?: string[]; register(ctx: PluginContext): void }`. | | `PluginContext` | interface | `{ app, container, http, logger, extend(name, method), onInit, onReady, onClose, addHealthCheck }`. | | `PluginOptions` | type | `{ plugins?: MeghPlugin[]; autoloadPlugins?: boolean }`, part of `MeghApplicationOptions`. | ## Testing Guide: [Testing](/advanced/testing). | Export | Kind | Description | | --- | --- | --- | | `MeghTest` | class | Static test helpers (below). | | `TestApplication` | interface | Test client: `get`, `post`, `put`, `patch`, `delete`, `options` take `(url, options?: InjectOptions)`; plus `getController(controller, deps?)`, `app`, `ready()` and `close()`. | | `TestStartOptions` | type | `{ errorDetails?: boolean; scheduler?: boolean }`: show 5xx details (default `true`), start scheduled tasks (default `false`). | | `TestAppOptions` | type | `TestStartOptions & { controllers: Constructor[] }`. | | `ContainerResetOptions` | type | `{ all?: boolean }`, for `MeghContainer.reset()` and `MeghTest.clean()`. | | `TestResponse` | type | The Fastify inject response, or a promise of it. | `Messaging.fake()` and `MessagingFake`, for asserting on events, messages and jobs, are under [Messaging](#messaging). ```ts MeghTest.createTestApplication(options: TestAppOptions): TestApplication MeghTest.from(app: MeghApplication, options?: TestStartOptions): TestApplication MeghTest.getController(controller: Constructor, deps?: any[]): T MeghTest.getProvider(service: Constructor, deps?: any[]): T MeghTest.clean(options?: ContainerResetOptions): void // reset the container ``` `from()` starts the app like `run()` without listening; calling it again for the same app shares that startup. `getController` and `getProvider` register `deps` in place of the class's constructor dependencies, in order. `Megh.createTestApplication(options)` is the same as `MeghTest.createTestApplication(options)`. ## Types | Export | Kind | Description | | --- | --- | --- | | `IRequest` | interface | The request type handlers and middleware receive: Fastify's request with Megh's additions. | | `IResponse` | interface | Fastify's reply. | | `Constructor` | type | `new (...args: any[]) => T`. | ## Other exports These are exported for plugins and other `@meghjs` packages. Prefer the APIs above. | Export | Kind | Description | | --- | --- | --- | | `loadPackageFromClient` | function | Load an optional dependency from the app's `node_modules`. | | `PackageLoader` | type | Type of `loadPackageFromClient`. | Metadata keys, registries, router metadata types and the helpers Megh uses internally are not exported. See [Upcoming changes](/getting-started/upgrading-next#internal-exports-are-removed) for the list that was removed. --- # Versioning Policy Source: https://meghjs.github.io/reference/versioning Megh follows [semantic versioning](https://semver.org): `MAJOR.MINOR.PATCH`. ## One version for every package Every `@meghjs` package (`core`, `cli`, `mcp` and `ai`) is released together and always has the same version number, even when only one of them changed. Use matching versions: ```json [package.json] { "dependencies": { "@meghjs/core": "0.8.0" }, "devDependencies": { "@meghjs/cli": "0.8.0" } } ``` `@meghjs/data` is the exception: it is no longer released and stays at 0.7.2, which works with `@meghjs/core` 0.7.2 and later 0.7 releases. ## Before 1.0 Megh is in `0.x`. Until 1.0: | Release | Can contain | |---------|-------------| | Minor (`0.6.x` → `0.7.0`) | Breaking changes, plus anything else | | Patch (`0.6.0` → `0.6.1`) | Bug fixes and new features. No breaking changes | New features ship in patch releases, so a minor release before 1.0 means something can break: read its upgrade guide first. 0.7.0 is the last minor before 1.0; see [Upgrading to 0.7](/getting-started/upgrading-0.7). Pin an exact version or use a tilde range (`~0.8.0`) so `npm install` never picks up a new minor on its own. A caret range (`^0.8.0`) on a `0.x` version already behaves like a tilde range. Fixes go into the latest release only. ## From 1.0 | Release | Can contain | |---------|-------------| | Major (`1.x` → `2.0`) | Breaking changes | | Minor (`1.2` → `1.3`) | New features and deprecations | | Patch (`1.2.0` → `1.2.1`) | Bug fixes | An API is deprecated in a minor release before it's removed in a major one. Deprecated APIs are marked `@deprecated` in their types, so your editor shows them struck through, and listed in the release notes. ## What counts as the public API The public API is: - everything exported from `@meghjs/core` (`import { … } from '@meghjs/core'`) - the `megh` CLI commands and their options - behaviour described in these docs, such as response shapes, status codes and the order of the request pipeline These are **not** part of the public API and can change in any release: - options under `experimental`, such as `experimental.compiledValidation` - members marked `@deprecated` or described as internal - the exports listed under [Other exports](/reference/api#other-exports) in the API reference. They're exported for Megh's own packages and may be hidden or removed before 1.0 - deep imports such as `@meghjs/core/dist/...`. The package's `exports` map blocks them anyway. - the exact text of log and error messages ## Breaking changes A change is breaking when a working app needs a code change to keep working after the upgrade. For example: - removing or renaming an export, method, decorator or option - changing a default value, response shape or status code - raising the minimum Node.js version (today `>=22`) - raising the major version of a peer dependency, such as `@fastify/multipart` Fixing a bug is not breaking, even when an app relied on the bug. If a fix is likely to affect many apps, the release notes call it out. ## How changes are announced Each release has: - **A changelog**, generated from the commit messages. Breaking changes are listed under a `BREAKING CHANGES` heading. See [packages/core/CHANGELOG.md](https://github.com/meghjs/megh/blob/main/packages/core/CHANGELOG.md). - **An upgrade guide** for any release with breaking changes, under *Upgrade Guides* in the sidebar, with before-and-after code. - **[Upcoming changes](/getting-started/upgrading-next)**, which lists what has landed on `main` since the last release. Read it to prepare ahead of time. ## Upgrading 1. Read the upgrade guide for each release between your version and the new one, oldest first. 2. Update `@meghjs/core` and `@meghjs/cli` to the same version. 3. Run your type checker. Most removals show up as type errors. 4. Run your tests. --- # FAQ and Troubleshooting Source: https://meghjs.github.io/reference/faq Start with `megh doctor` when something looks wrong. It checks the Node version, that `@meghjs/core` matches the CLI, that `reflect-metadata` is installed and that both decorator flags are on in `tsconfig.json`. ```bash npx megh doctor ``` ## Troubleshooting ### DTOs aren't validated, or injected services are `undefined` Megh reads TypeScript's decorator metadata (`design:paramtypes`) to find constructor dependencies and the DTO class of a `@Body()` or `@Query()` parameter. Without it, a `@Body()` or `@Query()` without `{ type }` stops startup with `@Body() (parameter 0) has no type, because decorator metadata wasn't emitted`. Constructor parameters are `undefined`, so you may also see `TypeError: Cannot read properties of undefined` in a handler. Turn both flags on: ```json [tsconfig.json] { "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } } ``` Then check the compiler. `tsc`, `megh serve` and `megh build` emit the metadata. **tsx and esbuild don't**, and SWC only does with `jsc.transform.decoratorMetadata: true`. If you must use one of them, name the types yourself: ```ts import { Controller, Post, Body, inject } from '@meghjs/core'; @Controller('/users') export class UserController { private readonly users = inject(UserService); // instead of a constructor parameter @Post('/') create(@Body({ type: CreateUserDto }) dto: CreateUserDto) { return this.users.create(dto); } } ``` ### Do I need `import 'reflect-metadata'`? Usually not. `@meghjs/core` imports it on load. Add it as the first line of your entry file only if classes decorated by other libraries (a DTO that only uses `class-validator`, say) can be loaded before anything imports `@meghjs/core`. TypeScript drops the metadata silently when `Reflect.metadata` doesn't exist yet. ```ts [src/serve.ts] import 'reflect-metadata'; import app from './app'; ``` ### ESM or CommonJS? `@meghjs/core` ships a single CommonJS build. ESM projects can import it, but the CLI (`serve`, `build`, `start`) and the scaffold assume a CommonJS app: no `"type": "module"` in `package.json`. With the scaffold's `"module": "nodenext"`, TypeScript then compiles to CommonJS. If you add `"type": "module"`, TypeScript switches to ES modules and stops at the compile step: relative imports without a `.js` extension fail with `TS2307: Cannot find module`. In older projects with `"module": "CommonJS"`, Node instead loads the compiled CommonJS files as ES modules and stops with `ReferenceError: exports is not defined in ES module scope`. Remove it, or compile and run the app yourself as real ESM. ### `megh build` fails after upgrading to TypeScript 6 Projects created with Megh 0.8.0 or earlier fail to build on TypeScript 6 with: ```text error TS5011: The common source directory of 'tsconfig.build.json' is './src'. The 'rootDir' setting must be explicitly set ... error TS5107: Option 'moduleResolution=node10' is deprecated and will stop functioning in TypeScript 7.0. ... ``` Angular 22 needs TypeScript 6, so this also shows up when you add an Angular frontend. Change these lines in `tsconfig.json`, which works on TypeScript 5.7 and later as well: ```json [tsconfig.json] { "compilerOptions": { "module": "nodenext", "moduleResolution": "nodenext", "rootDir": "./src" } } ``` Don't silence it with `"ignoreDeprecations": "6.0"`: TypeScript 5 rejects that value, and TypeScript 7 drops the old setting. ### `npm install` fails with `Cannot read properties of null (reading 'edgesOut')` On npm 10, which ships with Node 22, `npm install` crashes in projects created with Megh 0.8.0 or earlier: ```text npm error Cannot read properties of null (reading 'edgesOut') ``` npm 10 can't resolve the optional peer dependencies of Vitest 4.1 and later ([npm/cli#9787](https://github.com/npm/cli/issues/9787)). Either upgrade npm: ```sh npm install -g npm@11 ``` or pin Vitest to 4.0 in `package.json`, as new projects do: ```json [package.json] { "devDependencies": { "vitest": "~4.0.18", "@vitest/coverage-v8": "~4.0.18" } } ``` ### `Cannot access 'User' before initialization` between models This happens only in ES module builds, when two models import each other and a relation field is typed with the bare model: ```ts @BelongsTo(() => User) author?: User; // breaks in ESM when User imports Post author?: User | null; // fine author?: BelongsTo; // fine ``` Keep `| null` on `@HasOne` and `@BelongsTo` fields, or use the `HasOne<…>` / `BelongsTo<…>` types. CommonJS builds are not affected. See [Relations](/advanced/orm/relations). ### `[Megh] … is not installed` Integrations are optional peer dependencies, loaded when the app sets up the feature (for most, when you call its `use*` method). The error names the command to run: ```text [Megh] fastify-socket.io is not installed. Run: npm install fastify-socket.io socket.io ``` The same applies to `@fastify/cors`, `@fastify/multipart`, `@fastify/static`, `@fastify/swagger`, `@fastify/swagger-ui` and `@scalar/fastify-api-reference`. Database drivers fail with `The postgres connection needs "pg". Install it: npm install pg`. If it works locally but fails in production, the package is probably in `devDependencies` and was left out by `npm ci --omit=dev`. Move it to `dependencies`, or only call that `use*` method in development. ### Every `@Authorized` route answers 403 No authorization handler is registered. Megh denies those routes instead of serving them, and logs this at startup: ```text GET /users uses @Authorized but no authorization handler is registered; every request will be denied (403). Call app.useAuthorization(YourAuthorization). ``` Register one with `app.useAuthorization(AppAuthorization)`. If you have one, check that it doesn't return `false` (that is a 403 too) and that `useAuthentication` is set, so `request.user` is filled in. See [Authentication](/core-concept/authentication). ### Auto-discovered controllers aren't found `useControllers({ auto: true })` scans every `controllers/` folder under `src/` (`src/controllers/`, `src/users/controllers/`). When TypeScript runs directly (ts-node, tsx, `node --experimental-strip-types src/serve.ts`) it loads the `.ts` files from `src`. Otherwise it loads the compiled `.js` files: it reads `rootDir` and `outDir` from `tsconfig.build.json` or `tsconfig.json` (defaults `src` and `dist`) and also tries the nested `dist/src/controllers` when `rootDir` isn't set. Under `megh serve` it loads them from `.megh/build/` instead (the `MEGH_BUILD_DIR` the dev server sets). Paths are relative to the current working directory. Routes go missing when: - **The app wasn't built**, so the compiled folder doesn't exist yet. - **The tsconfig isn't in the working directory**, or `outDir` comes from a package `extends` (only relative `extends` are followed). Pass the compiled folder: `useControllers({ auto: true, path: 'build/controllers' })`. - **The app starts from another directory.** Start it from the project root. When the folder doesn't exist, Megh logs `Could not auto-register controllers` with the folder it tried. A file in it that fails to import stops startup with the file name and the error. Passing a list, `useControllers([UserController, ...])`, avoids all of this. ### `EADDRINUSE: address already in use` Another process is listening on the port, often an old dev server. Stop it, or pick another port: ```bash PORT=4001 npm run start:dev ``` Find the process with `lsof -i :4000` (macOS, Linux) or `netstat -ano | findstr :4000` (Windows). `app.run()` uses `PORT`, else `4000`, unless you pass a port. ### `.env` isn't loaded - Megh loads `.env` from the **current working directory** when `@meghjs/core` is first imported. Start the app from the project root. - Variables already in the environment win over `.env`. - `MEGH_DOTENV=false` turns loading off. - Code that reads `process.env` before importing `@meghjs/core` runs before `.env` is loaded. Read config through `Environment` or after the import. - Only `.env` is read. Megh doesn't load `.env.local` or `.env.production`. See [Configuration](/core-concept/configuration). ### Detailed errors show up in production `NODE_ENV` is `development` there, often from a `.env` file copied with the app. Set `NODE_ENV=production` in the real environment and don't ship `.env`. See [Deployment](/production/deployment#environment). ### Scheduled jobs run more than once Each replica runs the scheduler. Start it in one process only. See [Deployment](/production/deployment#scheduled-tasks-and-replicas). ## FAQ ### Is Megh production ready? Megh runs on Fastify and has the pieces production needs: graceful shutdown, health checks, structured logs and safe error responses. It is still `0.x`, so a minor release can contain breaking changes, each with an upgrade guide. Pin the version and read the guide before upgrading. See [Deployment](/production/deployment) and [Security Hardening](/production/security). ### How does Megh compare to NestJS? Both use decorators, dependency injection and controllers. Megh runs on Fastify only and has no module system: classes marked `@Injectable` or `@AppService` are available everywhere, with no provider arrays to keep in sync. It ships its own ORM, migrations, scaffolding and CLI generators. NestJS supports Express and Fastify, has a module system for large codebases and a much larger ecosystem and community. ### Can I use Fastify plugins? Yes. Register them with `registerFastifyPlugin()`: ```ts import etag from '@fastify/etag'; app.registerFastifyPlugin(etag); ``` Call it before `run()` or inside an `onInit()` hook. Some plugins attach themselves to each route as it is added; Megh loads registered plugins before it adds routes, so they see every controller and inline route. Compression is built in with `useCompression()`. Security headers and rate limits are built in: see [Security Hardening](/production/security#add-security-headers). To package your own features as `use*` methods, write a [Megh plugin](/advanced/plugins). --- # Upcoming changes Source: https://meghjs.github.io/getting-started/upgrading-next These changes are on `main` and ship in the next release. This page becomes the upgrade guide for that release. Upgrading from 0.7? See [Upgrading to 0.8](/getting-started/upgrading-0.8) first. ::: tip Upgrade with one command Commit your work, then run: ```sh npx @meghjs/cli@next upgrade --tag next ``` [`megh upgrade`](/cli/basic#upgrade) renames the exports listed under [Renamed exports](#renamed-exports), leaves a `TODO(megh-upgrade)` comment on every import of a [removed export](#internal-exports-are-removed), and adds `.megh/` to `.gitignore` ([below](#megh-serve-compiles-into-megh-build)). Add `--dry-run` to see the changes first. ::: Each item below says how to tell whether it affects you. ## `megh serve` compiles into `.megh/build` `megh serve` used to compile `src/` into the tsconfig `outDir` (`dist/`), the same folder `megh build` writes. Serving after a build replaced the production output with the dev build, and a build while the dev server ran deleted the folder it ran from. Now `megh serve` compiles into `.megh/build/`, a folder Megh owns, recreates on every start and you can delete at any time. `dist/` only holds what `megh build` produced. `megh build` and `megh start` don't change. `megh migrate` and `megh route:list` also compile into `.megh/` now (`.megh/migrate/`, `.megh/route-list/`) instead of `node_modules/.cache/megh`, so everything Megh generates is in one folder. **Affects you if** your project is in git (`.megh/` must not be committed), or something you run during development expects `megh serve` to have filled `dist/`. - Add `.megh/` to `.gitignore`, and to `.dockerignore` if you have one. `megh upgrade` adds it to `.gitignore` for you; `megh new` already does. - `"megh": { "entry": "dist/serve.js" }` keeps working: under `megh serve` it runs `.megh/build/serve.js`. - Auto-registered controllers (`useControllers({ auto: true })`) and scheduled tasks (`useScheduler()`) are loaded from `.megh/build/` under `megh serve`, which passes the folder to the app as `MEGH_BUILD_DIR`, and from `dist/` under `megh start`. - If you start the compiled app some other way during development and rely on `dist/` holding the dev build, run `megh build` first, or point `MEGH_BUILD_DIR` at the folder you compiled into. ## Renamed exports Some `@meghjs/core` exports had a typo, duplicated another export, or were named inconsistently. The old names are removed. | Before | After | | --- | --- | | `ValidateOptons` | `ValidateOptions` | | `IsArrayNotEmpty` | `ArrayNotEmpty` (see [below](#isarraynotempty-is-now-arraynotempty)) | | `Utility` | `Injectable` | | `Helper` | `Injectable` | | `GetSchema` | `generateSwaggerSchema` | | `DispatchOption` (events, `EventDispatcher.dispatch`) | `EventDispatchOptions` | | `DispatchOptions` (Socket.IO, `SocketEventDispatcher`, `@DispatchNow`) | `SocketDispatchOptions` | **Affects you if** your code imports any name in the left column. Rename the import and its uses: ```ts // Before import { Utility, GetSchema, type DispatchOption } from '@meghjs/core'; @Utility() export class Slugger {} // After import { Injectable, generateSwaggerSchema, type EventDispatchOptions } from '@meghjs/core'; @Injectable() export class Slugger {} ``` `OpenApiResponse` and `OpenApiProperty` are unchanged; they were exported twice, and now once. ### `IsArrayNotEmpty` is now `ArrayNotEmpty` `@IsArrayNotEmpty()` was the same check as `@ArrayNotEmpty()` with its own constraint key and message. With `@ArrayNotEmpty()`, a failed check reports the key `arrayNotEmpty` and the message `items should not be empty`, instead of `isArrayWithAtLeastOneElement` and `items must contain at least one item.` **Affects you if** a client or test reads that key or message. Pass `{ message }` to keep your own text. ## Internal exports are removed `@meghjs/core` exported about 60 names that Megh uses internally. They are no longer exported, so 1.0 doesn't promise them: - **Metadata keys**: `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`, `REQUEST_SESSION_META_KEY`, `DATASOURCE_META_KEY`, `AUTHORIZATION_META_KEY`, `PUBLIC_META_KEY`, `API_CONTROLLER_METADATA_KEY`, `REQUEST_METADATA_KEY`, `HTTP_CODE_META_KEY`, `REDIRECT_META_KEY`, `RESPONSE_HEADERS_META_KEY`, `CATCH_META_KEY`, `FILTERS_META_KEY`. - **Registries**: `registerController`, `getRegisteredControllers`, `isController`, `registerService`, `getRegisteredServices`, `createControllerDecorator`, `getDeclaredFilters`, `registerSocketSubscriber`, `getSocketSubscribers`, `isPrivate`, `getPrivateChannelResolver`, `EventSubscriberRegistry`. - **Compiled-validation helpers**: `checkHelpers`, `stringLength`, `isLength`. - **Router types**: `ParamMetaOptions`, `ParamMetaFilesOptions`, `MethodParamMeta`, `IRoute`, `FuncRoute`. - **Helpers**: `isConstructor`, `formatUrl`, `parsedPath`, `normalizePath`, `sleep`, `pick`, `exclude`, `autoCast`, `normalizeQueryDeep`, `transformObjectByInstanceToObject`, `jsonToJs`, `jsonToInstance`, `getDataType`, `isValidType`, `isValidJsonString`, `isClassValidatorClass`, `validateObjectByInstance`, `REQUEST_VALIDATION_OPTIONS`, `formatValidationMessage`. **Affects you if** your code imports one of them. Use the public API instead: `transformAndValidate` or `validateDto` to validate a value against a DTO, `@Controller` for controllers, `@UseFilters` for filters. For a small helper such as `sleep` or `pick`, write your own. ## `MeghTest` starts the app like `run()` `MeghTest.from(app)` and `MeghTest.createTestApplication()` now start the app through the same steps as `app.run()`, without listening on a port. Inline routes (`app.mapGet()` and friends), `onInit`/`onReady` hooks, `useControllers({ auto: true })`, OpenAPI and Socket.IO all work in tests. See [Testing](/advanced/testing). **Affects you if** your tests rely on what was skipped before: - A 5xx response under `MeghTest` now includes `message`, `error` and `stack`, as in development. Pass `MeghTest.from(app, { errorDetails: false })` to test the production response. - Scheduled tasks are registered but don't fire unless you pass `{ scheduler: true }`. - After `MeghTest.from(app)`, the app counts as started: calling `onInit()`, `onReady()` or `run()` on it throws, as it does after `run()`. ## Added - `HttpExceptions.notAcceptable()` (406), `HttpExceptions.requestTimeout()` (408), `HttpExceptions.badGateway()` (502) and `HttpExceptions.gatewayTimeout()` (504), next to the exception classes they build. - `DEFAULT_ALLOWED_UPLOAD_EXTENSIONS`, the extensions uploads accept by default, so you can extend the list: ```ts storage.configure({ allowedExtensions: [...DEFAULT_ALLOWED_UPLOAD_EXTENSIONS, '.heic'], }); ``` --- # Upgrading to 0.8 Source: https://meghjs.github.io/getting-started/upgrading-0.8 The `@meghjs` packages share one version number. Upgrade them together: ```sh npm i @meghjs/core@~0.8.0 npm i -D @meghjs/cli@~0.8.0 npm i @meghjs/ai@~0.8.0 # if you use @meghjs/ai ``` 0.8.0 has breaking changes. Read this page before upgrading, or let `megh upgrade` make most of them for you. ::: tip Upgrade with one command Commit your work, then run: ```sh npx @meghjs/cli@latest upgrade ``` [`megh upgrade`](/cli/basic#upgrade) bumps the `@meghjs` packages, removes `ioredis`, `bullmq` and `kafkajs` if your code doesn't import them, and applies the changes below that it can make exactly: queue `driver` to `transport`, `setQueueDriver()`, `QueueDriver`, `JobsOptions`, queue `adapter`/`connection` to `redis`, the cache's `redisOptions`, `new Redis(url)` passed to the cache or rate limiter, `MEGH_QUEUE_DRIVER` in `.env` files, and `@ApiController` to `@Controller`. It lists the rest as manual steps with links to the sections here. Add `--dry-run` to see the changes first. ::: 0.8.0 adds [messaging](/advanced/messaging): one transport layer (`memory`, `redis` or `rabbitmq`) for distributed events, `@Listener` classes, retries, dead letters, dedupe and a transactional outbox. Queues, the Redis cache and the Redis rate limit store move onto the same connection options, and ioredis is gone. Each item below says how to tell whether it affects you. ## `@ApiController` is now `@Controller` There is one controller decorator, `@Controller`. It takes the same arguments as `@ApiController` did, and its routes can return anything: JSON, `Results.View`, `Results.Inertia`, redirects, streams and downloads. `@ApiController` is removed. **Affects you if** any class uses `@ApiController`. Rename the decorator and its import: ```ts // Before import { ApiController, Get } from '@meghjs/core'; @ApiController('/users') export class UserController {} // After import { Controller, Get } from '@meghjs/core'; @Controller('/users') export class UserController {} ``` Search for it with `grep -rn ApiController src`. ## Dependencies BullMQ, the Redis client (`@redis/client`) and the RabbitMQ client (`amqplib`) are now dependencies of `@meghjs/core`. `bullmq`, `ioredis` and `kafkajs` are no longer peer dependencies, and Megh no longer uses ioredis. **Affects you if** you installed `bullmq` or `ioredis` for Megh. Remove them, unless your own code imports them: ```sh npm uninstall bullmq ioredis ``` ## Queues ### `driver` is now `transport` Queues run on the messaging transports. `bullmq` is now `redis`, `sync` is now an option of `memory`, and `rabbitmq` is new. | Before | After | |--------|-------| | `driver: 'bullmq'` | `transport: 'redis'` | | `driver: 'memory'` | `transport: 'memory'` | | `driver: 'sync'` | `transport: 'memory', sync: true` | | `MEGH_QUEUE_DRIVER=bullmq` | `MEGH_QUEUE_TRANSPORT=redis` | | `setQueueDriver('sync')` | `setQueueTransport('memory', { sync: true })` | | `resolveQueueDriver()` | `resolveQueueTransport()` | | `QueueDriver` type | `TransportName` | **Affects you if** you set `driver`, `MEGH_QUEUE_DRIVER` or call `setQueueDriver()`: ```ts // before @Queue({ name: 'email', driver: 'bullmq' }) beforeAll(() => setQueueDriver('sync')); // after @Queue({ name: 'email', transport: 'redis' }) beforeAll(() => setQueueTransport('memory', { sync: true })); ``` `MEGH_QUEUE_DRIVER` is ignored now. Without `MEGH_QUEUE_TRANSPORT`, queues follow `MEGH_MESSAGING_TRANSPORT`. ### The default is memory, and production refuses it Queues used to default to BullMQ on Redis. They now default to `memory`, so `npm run start:dev` needs no Redis. With `NODE_ENV=production`, a queue refuses to start on a memory transport it didn't ask for, instead of losing jobs on restart. **Affects you if** your production app relied on the BullMQ default. Set the transport in its environment: ```sh MEGH_QUEUE_TRANSPORT=redis MEGH_REDIS_URL=rediss://default:secret@redis.internal:6379 ``` ### `adapter` and `connection` are now `redis` Queues take Megh's Redis connection options instead of BullMQ's. `@Queue`'s `adapter` and `@MeghWorker`'s `connection` and `options` are gone. **Affects you if** you pass any of them: ```ts // before @Queue({ name: 'email', adapter: { connection: { host: '10.0.0.5', port: 6379 } } }) @MeghWorker({ queue: 'report', connection: { host: '10.0.0.5', port: 6379 } }) // after @Queue({ name: 'email', redis: { host: '10.0.0.5', port: 6379 } }) @MeghWorker({ queue: 'report', redis: { url: process.env.REDIS_URL } }) ``` `redis` takes `{ url?, host?, port?, username?, password?, db?, tls?, prefix? }`. Left out, it comes from `MEGH_REDIS_URL`, then `MEGH_MESSAGING_URL` when messaging runs on Redis, then `127.0.0.1:6379`. Jobs keep BullMQ's default `bull:` key prefix, so jobs already waiting in Redis are still processed after the upgrade. With `redis.prefix` set, keys go under `:bull:` instead. In production a queue's Redis connection follows the same TLS rule as messaging: a `redis://` URL (or `host`) to a remote server is refused. Use `rediss://` or `tls: true`, or set `MEGH_ALLOW_INSECURE_BROKER=true` on a private network you trust. A subclass that calls the `MeghQueue` constructor with arguments passes an options object now: ```ts // before super('email', { connection }, { concurrency: 5 }, 'bullmq'); // after super('email', { transport: 'redis', redis: { url }, worker: { concurrency: 5 } }); ``` ### Megh's own job types `Job` and `JobOptions` are Megh types now, the same on every transport. BullMQ types are no longer exported. **Affects you if** you import `JobsOptions`, or use BullMQ-only fields of a job: ```ts // before import type { Job, JobsOptions } from '@meghjs/core'; // after import type { Job, JobOptions } from '@meghjs/core'; ``` `JobOptions` has `delay`, `attempts`, `backoff`, `jobId`, `priority`, `removeOnComplete` and `removeOnFail`. A job has `id`, `name`, `data`, `queueName`, `attemptsMade`, `timestamp`, `opts`, `updateProgress()` and `log()`. For anything else, use `raw()` (below). ### `getQueue()` and `getWorker()` are gone | Before | After | |--------|-------| | `queue.getQueue()` | `queue.raw()` | | `queue.getWorker()` (to check it started) | `queue.hasWorker()` | | `worker.getWorker()` on a `MeghWorkerBase` | `worker.isRunning()` | | `this.worker` in a `MeghWorkerBase` subclass | no replacement | **Affects you if** you call them. `raw()` returns BullMQ's `Queue` on Redis, but it is outside Megh's compatibility promise. ### `attemptsMade` counts the current attempt On Redis, `job.attemptsMade` was `0` during the first run. It is now `1`, as on the memory and RabbitMQ transports. **Affects you if** a handler compares `attemptsMade`, for example to give up on the last try: ```ts // before if (job.attemptsMade + 1 >= (job.opts.attempts ?? 1)) { /* last try */ } // after if (job.attemptsMade >= (job.opts.attempts ?? 1)) { /* last try */ } ``` ### Mail queue options `useMail({ queue })` takes the same `transport`, `sync` and `redis` as a queue. `adapter` and `driver` are gone. **Affects you if** you set them: ```ts // before app.useMail({ queue: { adapter: { connection: { host: '127.0.0.1', port: 6379 } }, driver: 'bullmq' }, }); // after app.useMail({ queue: { transport: 'redis', redis: { host: '127.0.0.1', port: 6379 } }, }); ``` ## Cache: `redisOptions` is now `redis` `useCache()` takes Redis connection options as `redis`. Megh opens the connection and closes it on shutdown. Passing an ioredis client is no longer possible. **Affects you if** you use the Redis cache: ```ts // before app.useCache({ provider: 'redis', redisOptions: { host: '127.0.0.1', port: 6379 } }); new CacheManager({ provider: 'redis', redis: new Redis() }); // after app.useCache({ provider: 'redis', redis: { host: '127.0.0.1', port: 6379 } }); new CacheManager({ provider: 'redis', redis: { url: process.env.REDIS_URL } }); ``` ## Rate limits: `redis` takes connection options `useRateLimit({ redis })` and `RedisRateLimitStore` take connection options instead of an ioredis client. Megh opens the connection, and closes it on shutdown for a store it created. `RedisEvalClient` is gone. **Affects you if** you count rate limits in Redis: ```ts // before import Redis from 'ioredis'; app.useRateLimit({ redis: new Redis(process.env.REDIS_URL!) }); app.useRateLimit({ store: new RedisRateLimitStore(new Redis(), { prefix: 'rl:' }) }); // after app.useRateLimit({ redis: { url: process.env.REDIS_URL } }); app.useRateLimit({ store: new RedisRateLimitStore({ url: process.env.REDIS_URL }, { prefix: 'rl:' }) }); ``` A store you build yourself has `close()`. ## Scheduler jobs run once across replicas `@Cron` and `@Interval` jobs used to run in every replica. They now run once per tick across all of them. The replicas agree through a lock in Redis (with the redis messaging transport) or in the `megh_locks` table (with Megh ORM and `megh make:messaging`). `@Timeout` still runs on each instance. **Affects you if** you run several replicas: - If you worked around it with a `RUN_SCHEDULER` flag or your own lock, you can drop that once a lock store is set up. - A job meant to run in each replica, such as clearing a local cache, needs `perInstance: true`: ```ts // before @Interval(60_000) // after @Interval(60_000, { perInstance: true }) ``` - With neither Redis messaging nor the `megh_locks` table, every replica still runs every job, and Megh logs a warning in production. Replicas recognise a job by its `name`, or `ClassName#method`. See [Scheduler: Multiple replicas](/advanced/scheduler#multiple-replicas). ## Events: Kafka and RabbitMQ broadcast `dispatch(event, { broadcast: { type: 'kafka' } })` and `type: 'rabbitmq'` still throw: broadcast is only for Socket.IO. To send events to other services, mark them with `@DistributedEvent` and use the `rabbitmq` (or `redis`) [messaging](/advanced/messaging) transport. Kafka is not supported. **Affects you if** you planned on broadcast for this. Nothing changes for existing code. ## `scaffold:auth` hashes passwords with `Hash` `megh scaffold:auth` no longer writes `src/auth/password.ts`. The generated `AuthService` injects [`Hash`](/core-concept/hashing) from `@meghjs/core` instead, and rehashes a password at sign-in when `hash.needsRehash()` says so. New hashes use scrypt with stronger settings (N = 2^17), in the format `scrypt$$$

$$`. **Affects you if** you ran `scaffold:auth` before 0.8.0. Nothing breaks: your `password.ts` keeps working, and `Hash.check()` reads the hashes it wrote (`scrypt$$`). To move over, replace `hashPassword()` and `verifyPassword()` with `Hash`, then delete `src/auth/password.ts`: ```ts // before import { hashPassword, verifyPassword } from '../auth/password'; const valid = await verifyPassword(input.password, user.password); // after import { Hash } from '@meghjs/core'; constructor(private readonly hash: Hash) {} const valid = !!user.password && (await this.hash.check(input.password, user.password)); ``` Existing users' hashes are upgraded the next time they sign in if you add the `needsRehash()` check; see [Upgrading old hashes](/core-concept/hashing#upgrading-old-hashes). ## New in 0.8.0 - **More `Results`.** `Accepted`, `Created(data, location)`, error results with the error handler's body (`BadRequest`, `Unauthorized`, `Forbidden`, `Conflict`, `UnprocessableEntity`, `TooManyRequests`, `Error(status, ...)`), raw bodies (`Json`, `Text`, `Html`, `Status`), and files (`File` shows one in the browser, `Download` downloads it, from a path, Buffer or stream). Every result takes `.header(name, value)`. See [Returning responses](/getting-started/usage#returning-responses). - **Hashing.** `Hash` (injectable, or `Hash.make()` / `hash.make()`) hashes and checks passwords with scrypt (the default, no install), bcrypt or argon2id. `app.useHashing({ driver: 'argon2' })` picks the driver, and `check()` reads every driver's hashes. `megh make:hash` prints or checks a hash from the command line. See [Hashing](/core-concept/hashing). - **Notifications.** Extend `Notification`, pick channels in `via()` (`mail`, `broadcast`), and send with `notifier.send(user, notification)`. `Notifier.fake()` records them in tests. See [Notifications](/advanced/notifications). - **Tracing.** `app.useTracing()` creates an OpenTelemetry span per request, named after the route and continuing an incoming `traceparent`. Needs `@opentelemetry/api`. See [Tracing](/advanced/tracing). - **Monitoring.** `app.useMonitor()` plus `megh monit` opens a live dashboard: metrics charts, a log stream, routes, services and health. See [Monitoring](/advanced/monitoring). - **Messaging.** `app.useMessaging()`, or `MEGH_MESSAGING_TRANSPORT` and `MEGH_MESSAGING_URL`, picks `memory`, `redis` (Redis Streams) or `rabbitmq`. Messages travel as CloudEvents 1.0. See [Messaging](/advanced/messaging). - **Distributed events.** `@DistributedEvent('order.placed')` makes `dispatch()` publish the event, and `@Listener(OrderPlaced, { group })` classes handle it on one replica per group, with retries, dead letters and dedupe. - **`@Listener` for local events** registers a DI-resolved listener class at `app.run()`, without calling `EventRegistry` by hand. - **Transactional outbox.** With `useMessaging({ outbox: true })` and Megh ORM, events dispatched in a transaction are published after it commits. - **Jobs on RabbitMQ.** `transport: 'rabbitmq'` runs queue jobs through the broker. - **`Messaging.fake()`** records events, messages and jobs for tests: `expectDispatched`, `expectPublished`, `expectQueued` and more. See [Testing](/advanced/testing#events-messages-and-jobs). - **CLI.** `megh make:messaging` writes the migration for `megh_outbox`, `megh_locks` and `megh_dedupe`. `megh messaging:failed` lists, retries and discards dead letters. - **Storage disks.** `app.useStorage()` sets up named disks: `local`, `s3` (and S3-compatible services such as R2, MinIO, Spaces, B2 and Wasabi), `azure` and `gcs`, each with `put`, `get`, `list`, `url`, `temporaryUrl` and more. Inject `Storage` or `@InjectDisk('s3')`, and use `Storage.fake()` in tests. `FileStorage.save()` takes a `disk` option, and its result now also has `path` and `disk`. Once you call `useStorage()`, uploads that name no disk go to the default disk instead of `/public`, unless `configure({ baseDir })` was called. See [Storage](/advanced/storage). - **Secure defaults.** In production, Megh refuses non-TLS URLs to remote brokers (unless `allowInsecure`), the memory transport for distributed listeners, and messages over 256 KiB. --- # Upgrading to 0.7 Source: https://meghjs.github.io/getting-started/upgrading-0.7 The `@meghjs` packages share one version number. Upgrade them together: ```sh npm i @meghjs/core@~0.7.3 npm i -D @meghjs/cli@~0.7.3 npm i @meghjs/ai@~0.7.3 # optional: LLM tools and an MCP server for your app ``` 0.7.3 adds [sessions](/advanced/sessions) for server-rendered apps, with a login redirect, gates and the `@auth`, `@guest`, `@can` and `@session` view directives, and [editor support](/advanced/views#editor-setup) for `.megh.html` templates in VS Code, Neovim and other LSP editors. See [New in 0.7.3](#new-in-0-7-3). It has one breaking change: `app.app`, the Fastify instance, is no longer public. Read [Breaking in 0.7.3](#breaking-in-0-7-3) if your code uses it. `@meghjs/data` is not part of 0.7.3. It stays at 0.7.2, which works with `@meghjs/core` 0.7.3. Coming from 0.7.1? 0.7.2 adds [`@meghjs/ai`](/ai/tools), which turns routes into LLM tools and serves them over MCP, and gives coding agents an `AGENTS.md` in new projects and [`/llms.txt`](https://meghjs.github.io/llms.txt) for the docs. It has no breaking changes. See [New in 0.7.2](#new-in-0-7-2). Coming from 0.7.0? 0.7.1 makes class-validator and class-transformer optional and fills out the [ORM](/advanced/orm). It has a few breaking changes, which is unusual for a patch release: read [Breaking in 0.7.1](#breaking-in-0-7-1) before upgrading. Each item says how to tell whether it affects you. Coming from 0.6.x? Read [Breaking in 0.7.0](#breaking-in-0-7-0) too. 0.7 is the last minor release before 1.0. See the [versioning policy](/reference/versioning). ## Breaking in 0.7.3 ### The Fastify instance is no longer public `app.app` is gone. Megh keeps the Fastify instance to itself, so an app can't change routing, hooks or error handling behind Megh's back. **Affects you if** your code or tests use `app.app`. Replace each use: | Before | After | | --------------------------------- | ----------------------------------------- | | `app.app.register(plugin, opts)` | `app.registerFastifyPlugin(plugin, opts)` | | `app.app.inject({ method, url })` | `app.inject({ method, url })` | | `app.app.server.address()` | `app.address()` | | `app.app.close()` | `app.close()` | `registerFastifyPlugin()` works before `run()` and inside `onInit()` hooks. Megh loads the plugins before it adds routes, so plugins that hook into routes see all of them. It throws once routes are mapped. Megh [plugins](/advanced/plugins) still get the instance as `ctx.http`. See [Fastify plugins](/getting-started/application#fastify-plugins). ## New in 0.7.3 ### Sessions [`app.useSession()`](/advanced/sessions) adds cookie sessions. The cookie holds a random ID, signed with HMAC-SHA256, and the data stays on the server: in memory, in Redis (`redis: new Redis()`), or in your own `SessionStore`. - Inject the session with `@Session()`, or read it with `currentSession()`. Views get it as `session`. - `flash()` keeps a value for the next request only, for messages after a redirect. - Call `regenerate()` on login and `destroy()` on logout. - `secret` defaults to `SESSION_SECRET` and must be at least 32 characters. An array of secrets rotates keys. There are no new dependencies. ### Login redirect With `useSession({ loginPath: "/login" })`, a browser that hits a route needing a logged-in user is redirected to the login page instead of getting a 401. A GET remembers its URL, and `session.intended("/")` sends the user back there after login. JSON and XHR requests keep the 401. See [Protecting pages](/advanced/sessions#protecting-pages). ### Gates `app.defineGate(name, check)` defines a permission check for the logged-in user. Use it in code with `gate.allows()`, `gate.denies()` and `gate.authorize()` (401 for a guest, 403 when denied), and in views with `@can`. See [Gates](/advanced/sessions#gates). ### View directives - `@auth` … `@endauth` and `@guest` … `@endguest`: logged in or not, from `useAuthentication()`. - `@can('edit-post', post)` … `@endcan` and `@cannot(...)` … `@endcannot`: gate checks. - `@session('status')` … `{{ value }}` … `@endsession`: a session value, such as a flashed message. All of them except `@session` take `@else`. See [Views](/advanced/views#syntax). ### Editor support for templates [Editor setup](/advanced/views#editor-setup) covers the VS Code extension, the new Neovim plugin ([`megh.nvim`](https://github.com/meghjs/megh.nvim)), and the Megh language server for other LSP editors. They give highlighting, completion, hover, formatting and validation for `.megh.html` files. Typing `@` now completes directives, and block directives are inserted with their closing tag. ### Other changes - `app.inject()` sends a request to the app in-process, for tests. `app.address()` returns the address the server listens on, for example after `run(0)`. - `megh new --pm pnpm` writes a `pnpm-workspace.yaml` that approves the build scripts the project needs (`@swc/core`, and `better-sqlite3` for an ORM app on SQLite). Without it, pnpm 10 skips building `better-sqlite3` and the app crashes on its first query, and pnpm 12 fails the install. ## New in 0.7.2 ### LLM tools and an MCP server: `@meghjs/ai` [`@meghjs/ai`](/ai/tools) is a new plugin. Install it to use it; nothing changes for apps that don't. - `@Tool()` exposes a route to LLMs as a tool. Its input schema comes from the route's path parameters, `@Query()` and `@Body()` DTO, and each call goes through the route's authentication, `@Authorized`, validation and rate limits. - `app.tools()`, or an injected `ToolSet`, gives the tools in Anthropic, OpenAI or MCP format, and runs a model's tool calls as the signed-in user. `confirm: true` tools need a person's approval. - `app.useMcp()` serves the tools as an MCP server over Streamable HTTP, so assistants such as Claude or Cursor can use your app with the permissions of the user who connects them. It needs `@modelcontextprotocol/sdk`. ### Docs for coding agents - `megh new` writes an `AGENTS.md` with the project's commands, layout and the Megh rules TypeScript can't check, and a `CLAUDE.md` that imports it. Add them to an existing project with `npx megh make:agents`. See [Application](/cli/basic#application). - The docs site publishes [`/llms.txt`](https://meghjs.github.io/llms.txt), an index of every page for agents, and [`/llms-full.txt`](https://meghjs.github.io/llms-full.txt), every page in one file. Each page is also available as markdown: add `.md` to its URL. ### Other changes - `megh route:list` shows a **TOOL** column when the app has `@Tool` routes, and `--json` adds a `tool` field to those routes. - `@meghjs/mcp` adds `megh_list_ai_tools`, which lists the app's tools with safety warnings, and the `megh-add-ai-tools` prompt. - Plugins can read each controller route's handler and input schema in Fastify's `onRoute` hook with `getRouteDescriptor(route)` from `@meghjs/core`. - A route handler that sends the reply itself (for example after `reply.hijack()`) no longer logs "Reply was already sent". ## Breaking in 0.7.1 ### Model method names are reserved `Model` has new instance methods: `refresh`, `fresh`, `touch`, `replicate`, `increment`, `decrement`, `makeVisible` and `makeHidden`. **Affects you if** a model declares a column, getter or method with one of these names. Rename it, or map the column to another property with `@Column({ name })`. See [Reserved names](/advanced/orm/models#instance-helpers). ### `Model.create()` goes through `save()` `Model.create(values)` now builds an instance and calls `save()`, so it fires the `saving`, `creating`, `created` and `saved` [events](/advanced/orm/models#events). **Affects you if** you register model event handlers and expect them not to run on `create()`. Query-level writes (`insert()`, `upsert()`, `where(…).update()`) still fire no events. ### `IsArrayNotEmpty` is a Megh decorator It used to register a class-validator rule. A class-validator DTO that uses it now fails at startup, because it mixes the two libraries. **Affects you if** a DTO imports other decorators from `class-validator` and uses `IsArrayNotEmpty`. Replace it with class-validator's `ArrayNotEmpty`, or switch the whole DTO to `@meghjs/core`. Its constraint key (`isArrayWithAtLeastOneElement`) and message are unchanged. ## New in 0.7.1 ### class-validator and class-transformer are optional `@meghjs/core` no longer loads class-validator or class-transformer when it starts. Both are now optional peers: an app whose DTOs use Megh's decorators runs without them, and `megh new` no longer adds them to new projects. Apps with class-validator DTOs keep working unchanged while the two packages are installed. A class-validator DTO validated without class-transformer installed fails with an error naming the package to install. To drop them, switch each DTO's imports to `@meghjs/core` (see [Switching from class-validator](/core-concept/validation#switching-from-class-validator)), then run `npm uninstall class-validator class-transformer`. ### Everything a DTO needed class-validator for These now come from `@meghjs/core`, with class-validator's and class-transformer's names, options, constraint keys and messages: - custom validators: `@ValidatorConstraint`, `@Validate`, `registerDecorator`, `ValidateBy`, `buildMessage`, including async validators ([guide](/core-concept/validation#custom-validators)). Request validation waits for them; `validateDtoAsync` validates by hand. - `@Expose` and `@Exclude`, on properties and classes, and `plainToInstance` / `instanceToPlain` ([guide](/core-concept/validation#shaping-responses)) - `@Type` with a `discriminator` (it used to throw) - `ArrayUnique`, `ArrayContains`, `ArrayNotContains`, `Equals`, `NotEquals`, `IsNotEmptyObject`, `IsInstance`, `MinDate`, `MaxDate`, `IsDivisibleBy`, `IsTimeZone`, `IsPhoneNumber` and the string-format checks (`IsDateString`, `IsNumberString`, `IsAlpha`, `IsMongoId`, `IsIP`, …). See the [table](/core-concept/validation#decorators). `@IsUUID()` no longer needs the `validator` package. ### A fuller ORM - **Constrained eager loading:** `Todo.with('user', (q) => q.select('name'))`, with `where`, `orderBy` and a per-parent `limit()`. Unselected columns are a type error. See [Constraining eager loads](/advanced/orm/relations#constraining-eager-loads). - **New relations:** [has many through](/advanced/orm/relations#has-many-through) and [polymorphic relations](/advanced/orm/relations#polymorphic-relations). - **Model queries match `DB.table()`:** more conditions, [subqueries](/advanced/orm/queries#subqueries), [global scopes](/advanced/orm/queries#global-scopes), [streaming large results](/advanced/orm/queries#large-results), [cancelling](/advanced/orm/queries#cancelling-queries) and [row locks](/advanced/orm/queries#locking-rows). - **Writes:** `firstOrNew`, `firstOrCreate`, `updateOrCreate`, `createMany`, bulk `insert` and `upsert` on every dialect. See [Finding or creating](/advanced/orm/queries#finding-or-creating) and [Many rows](/advanced/orm/queries#many-rows). - **Models:** [hidden and visible columns](/advanced/orm/models#hiding-columns-from-json) (also left out of OpenAPI schemas), [events](/advanced/orm/models#events) and [instance helpers](/advanced/orm/models#instance-helpers). - **`DB.table()`:** upsert, CTEs, unions, locks and streaming. See the [query builder](/advanced/orm/query-builder). ### Other changes - **`HttpResponse.Ok(data, Class)` and `Created(data, Class)`** shape the data with Megh's conversion unless `Class` uses only class-transformer decorators, which keep using class-transformer. Results are the same; a response class that mixes Megh and class-transformer decorators now follows Megh's. - **`transformAndValidate`** validates DTOs that use Megh's decorators with Megh's validator, as the router already did. Results are the same. - **Generated code** (`megh new`, `make:dto`, `make:resource`, `scaffold:auth`) imports its decorators from `@meghjs/core`, and the test that `make:dto` writes uses `validateDto`. - **`toJSON()`** on a model leaves out `hidden` columns, including those of loaded relations, and returns relations as plain objects. ## Breaking in 0.7.0 ### Unresolvable constructor parameters throw A constructor parameter typed as an interface, a union or a primitive has no runtime type, so it used to be injected as `undefined`. The service then failed later, far from the cause. Now the class fails when it is first built, with a `ContainerError` that names the class and the parameter: ``` Cannot resolve parameter 0 of OrderService: its type is an interface, union or primitive (emitted as Object). Use @Inject(TOKEN) on the parameter or inject(TOKEN) in a field, type it as a class, or mark it @Optional(). ``` **Affects you if** the app now fails at boot with this error. Fix the parameter it names in one of these ways: ```ts constructor( @Inject(PAYMENT_GATEWAY) private readonly gateway: PaymentGateway, // a token @Optional() private readonly tracer?: Tracer, // undefined on purpose ) {} ``` `@Inject(token, { optional: true })` injects `undefined` when the token isn't registered. Overrides and inject handlers still take precedence. See [Dependency Injection: Errors](/core-concept/dependency-injection#errors). ### Mail addresses must be single addresses A string such as `'ann@example.com, bob@example.com'` used to pass as one address. The HTTP mailers (SendGrid, Mailgun, Postmark and Resend) sent it on as is, so it reached every address in it. If the string came from user input, an attacker could add themselves. Each address must now be a single `local@domain` with no spaces, `,`, `;`, `<`, `>` or quotes. A display name that contains a comma must be quoted: `'"Lee, Ann" '`. **Affects you if** you pass several recipients in one string. Pass an array instead: ```ts await mailer.to(['ann@example.com', 'bob@example.com']).send(new InvoiceMail()); ``` ### Attachment URLs are refused by default Every mailer now checks attachment `path`s when the message is built. Local files are allowed. `http(s)://` URLs are refused unless you turn them on, because a URL built from input could fetch cloud metadata or internal services and mail the response out. **Affects you if** an attachment's `path` is a URL. Allow URLs only if every URL is yours, and consider confining local files to one folder: ```ts app.useMail({ allowUrlAccess: true, // default false attachmentRoot: 'storage/invoices', // optional: only read files in here }); ``` See [Mail: Attachment paths](/advanced/mail#attachment-paths). ### Rate limits are stricter - **One counter per route across URI versions.** A route served at `/v1/...` and `/v2/...` by `@Version(['1', '2'])` used to get a separate limit per version. Now the versions share one counter. - **IPv6 clients are grouped by `/64`.** A client rotating addresses within its `/64` used to get a fresh counter for every address. Change the prefix with `useRateLimit({ ipv6Subnet })`. IPv4-mapped IPv6 addresses count as IPv4. - **The memory store holds at most 100,000 keys** and drops the oldest windows first, so random keys can't grow the heap without limit. Change it with `new MemoryRateLimitStore({ maxKeys })`. **Affects you if** you rely on per-version limits, or many of your users share an IPv6 `/64`. See [Security: Add rate limits](/production/security#add-rate-limits). ### `transports` only accepts `'socket'` `SocketEventDispatcher.dispatch(event, data, { transports })` accepted `'kafka'` and `'rabbitmq'` but ignored them. Any value other than `'socket'` now throws before the event is sent. **Affects you if** you pass `transports`. Remove the option, or use `['socket']`. See [WebSocket: Emitting to clients](/microservices/websocket#emitting-to-clients). ### `megh -v` prints only the version `megh -v` and `megh --version` print just the number, for example `0.7.0`. In 0.6.5 they printed the logo and `Megh v`. The logo now appears only with `megh --info`, which also has a short form, `megh -i`. **Affects you if** a script parses `megh -v`. Read the whole output as the version. ## New in 0.7.0 ### Views Megh renders HTML on the server with a Blade-style template engine: `{{ }}` echoes, `@if` / `@foreach`, layouts with `@extends` and `@section`, `@include`, stacks, and `` tags with slots. Templates compile to JavaScript once and are cached. ```ts app.useViews(); // views/**/*.megh.html @Get('/') home() { return Results.View('pages.home', { user }); } ``` - **`@react` islands** mount a React component in the browser from inside a view. Compiling JSX needs `@swc/core`. - **`app.useMethodOverride()`** lets HTML forms reach `PUT`, `PATCH` and `DELETE` routes with `@method('DELETE')`, and parses urlencoded bodies for `@Body()`. See [Views](/advanced/views). ### MCP server for AI assistants [`@meghjs/mcp`](/ai/mcp) is a new package: a Model Context Protocol server that lets assistants such as Claude Code, Cursor and VS Code read the Megh docs, inspect your project (routes, structure, migrations, type errors) and run the `megh` generators. In Claude Code: ```sh claude mcp add megh -- npx -y @meghjs/mcp ``` It has a `--read-only` mode, and it refuses to run migrations against a production project. See [MCP Server](/ai/mcp). ### Deny-by-default authorization A route without `@Authorized` is public, so forgetting it on one handler leaves that endpoint open. You can now protect every route by default and mark the open ones with `@Public()`: ```ts app.useAuthorization(JwtAuthorization, { default: 'authenticated' }); ``` It's off unless you set `default`, so existing apps behave as before. `megh route:list` shows each route's protection in a new `AUTH` column. See [Deny by default](/core-concept/authentication#deny-by-default). ### Request context `requestContext` holds values for the current request, so code deep in a service can read the current user or tenant without passing it through every call: ```ts import { requestContext } from '@meghjs/core'; const user = requestContext.getUser(); ``` Authentication sets `requestContext.user`. `requestContext.run(fn, init)` gives workers, scripts and tests a context of their own. See [Request Context](/core-concept/request-context). ### CLI - **`megh new --mvc`** creates a server-rendered app: `useViews()` and `useMethodOverride()` in `src/app.ts`, a layout, a home page, and a controller that renders it. See [CLI: Application](/cli/basic#application). - **`megh make:view `** (`m:v`) writes `views/.megh.html`. Pages extend `layouts.app` when it exists; `--layout` picks another layout, `--no-layout` writes a standalone page, and `-c` writes an `` component. See [Generators: View](/cli/generators#view). - **A new logo** for `megh --info`, and `megh -i` as its short form. ## Fixes - **Rate limiting warns when `trustProxy: true`.** With it, the client controls `X-Forwarded-For` and can get a fresh counter on every request. Use the number of proxy hops or the proxy's address instead. See [Terminate HTTPS at a proxy](/production/security#terminate-https-at-a-proxy). - `rateLimitIpKey()` and `MemoryRateLimitStoreOptions` are exported. - `setGlobalPrefix(prefix, { exclude })` matches inline routes whose path has no leading slash. - In-memory queued events run in the request context they were dispatched in. They used to all run in the context of the first one. ## Coming from older versions On 0.5.x or earlier, read [Upgrading to 0.6](/getting-started/upgrading-0.6) first. --- # Upgrading to 0.6 Source: https://meghjs.github.io/getting-started/upgrading-0.6 0.6.0 removes APIs that did nothing, makes `app.run()` read `PORT`, and sends framework messages through the logger. Most apps only need to delete a call or two. Read [Breaking in 0.6.0](#breaking-in-0-6-0) before upgrading. 0.6.1 and 0.6.3 add features and fixes with no breaking changes. See [New in 0.6.3](#new-in-0-6-3) and [New in 0.6.1](#new-in-0-6-1). 0.6.2 was tagged but never published to npm; its changes ship in 0.6.3. 0.6.5 adds features and fixes, and changes some CLI generator flags (`make:model` writes a plain class unless you pass `--orm`). Apps don't need code changes. See [New in 0.6.5](#new-in-0-6-5). A `0.x` minor release can contain breaking changes; patch releases such as 0.6.1 don't. See the [versioning policy](/reference/versioning). ```sh npm i @meghjs/core@^0.6.5 npm i -D @meghjs/cli@^0.6.5 ``` ## New in 0.6.5 There is no 0.6.4: the changes on `main` after 0.6.3 ship in 0.6.5. ### Changes to the CLI generators 0.6.5 changes what some generator flags mean. Your app's code is not affected, only what the `make:*` commands write from now on. Check any scripts that run them: - **`make:model` writes a plain class by default.** For a Megh ORM model (columns read from its migration), add `--orm`: `megh make:model user --orm`. `--template` and `--fields` still build a Megh ORM model without it. - **`--orm` now means Megh ORM; TypeORM is `--typeorm`.** On `make:model`, `make:controller -m` and `make:service -m`, replace `--orm` with `--typeorm` where you generate TypeORM entities or repository services. With `-m`, Megh ORM stays the default. - **A resource can't be built on a plain class.** `make:resource`, `make:controller -m` and `make:factory` stop with a message if the model file is a plain class; regenerate it with `make:model --orm --force`. - **`megh -v` prints the logo, then `Megh v`**, instead of the bare version. A script that reads it should match `v(\d+\.\d+\.\d+)` on the last line, or use `npm ls @meghjs/cli`. `megh --help` and `megh new` no longer print the logo. (0.7.0 changes this again: `megh -v` prints only the version. See [Upgrading to 0.7](/getting-started/upgrading-0.7#megh-v-prints-only-the-version).) ### New - **Generators write unit tests.** `make:service user` also writes `src/services/user.service.spec.ts`, and so do the other generators except `make:model` and the database ones. `make:resource` tests every service method and route without a database. Pass `--notest` (or `-nt`) to skip them. See [CLI: Tests](/cli/generators#tests). - **`make:test` (`m:t`)** writes a test for a file you already have: `megh make:test user.service`. - **`make:class` (`m:cls`)** writes a plain class in `src/classes/`. - **`megh --info`** prints the CLI, Node.js and OS versions and the project's Megh packages, for bug reports. See [Version and info](/cli/basic#version-and-info). - **Compression.** `app.useCompression()`, over `@fastify/compress`. See [Compression](/getting-started/application#compression). - **Global prefix and versioning.** `app.setGlobalPrefix('api', { exclude })` and `app.useVersioning({ type: 'uri' | 'header' })` with `@Version()`. See [Global prefix and versioning](/core-concept/controller#global-prefix-and-versioning). - **Redirects and response headers.** `@Redirect(url, status)`, `Results.Redirect(url, status)` and `@ResponseHeader(name, value)`. See [Redirects and headers](/getting-started/usage#redirects-and-headers). - **Validated environment and config.** `app.useEnvSchema(EnvDto)` and `@AppConfig({ schema })` check values at boot and list every problem in a `ConfigValidationError`. See [Validating at boot](/core-concept/configuration#validating-at-boot). - **Socket.IO authentication.** The `useAuthentication` handler runs on the handshake and sets `socket.data.user`. See [WebSocket: Authentication](/microservices/websocket#authentication). - **`megh migrate --compiled`** (and `db:seed --compiled`) runs the built `.js` migrations, for production images without `src/`. It is picked automatically when there is no `src/` folder. See [Database Commands](/cli/database). ### Fixes - The CLI's generated files load when a name matches a Megh decorator: `make:config app` (`AppConfig`) and a `Post`, `Get` or `Query` model in `make:resource`. - `MeghTest.getController` / `getProvider` stand-ins are no longer written to the shared container, and requests wait for the routes to be mapped. See [Testing](/advanced/testing#replacing-dependencies). - `PartialType`, `PickType` and `OmitType` copy class-validator, class-transformer, Megh and OpenAPI metadata. - `MEGH_DOTENV=false` stops `Environment` from reading `.env`; `GetConfig` passes on errors from `config()` and caches until `Environment.reload()`. - Controller auto-discovery reads the tsconfig `rootDir`/`outDir`, detects tsx and other TypeScript runtimes, and fails on a file it can't import. - Scheduler: tasks stop when startup fails, `close()` waits for running jobs, and `useScheduler({})` scans `src/tasks`. - `useControllers()` adds to earlier lists; a clear boot error for `@Body()` / `@Query()` without decorator metadata; Scalar serves the generated spec; `FileStorage` confines saves after following symlinks; the error logger logs the path without the query string. - `megh doctor` requires Node.js 22, like the packages. ## New in 0.6.3 - **Generators for events, queues and scheduled tasks.** `make:event`, `make:listener` (`--event` to type it), `make:queue`, `make:worker` and `make:task` (`--cron`, `--interval`). See [Events](/advanced/events), [Queue](/advanced/queue) and [Scheduler](/advanced/scheduler). - **`make:*` puts the module folder first.** `megh make:model users/user` now writes `src/users/models/user.model.ts`, not `src/models/users/user.model.ts`. The same goes for controllers, services, DTOs, middleware, config and mail. Existing files stay where they are, and `make:resource`, `make:factory` and `sync:model` still find models in the old place. See [Folders](/cli/generators#folders). - **Auto-discovered controllers.** `useControllers({ auto: true })` without a `path` now scans every `controllers/` folder under `src/`, so module controllers are found. With a `path`, nothing changes. - **`megh new` offers OpenAPI, CORS and MeghORM only.** Mail, Scalar UI, TypeORM and Knex are no longer set up by `megh new`; asking for them with `--features` prints how to add them. Existing projects are not affected. See [Mail: Setting it up](/advanced/mail#setting-it-up). - **Generated models put each decorator on its own line**, with a blank line between columns. `sync:model` still reads models in the one-line style, and keeps hand-written fields as they are. - **`update:model` is now `sync:model`** (alias `s:m`). The old name and `u:m` still work. - **Generators review changes to existing files.** `sync:model` and any `make:*` run with `-f` show a diff of each file they would change, the files that import it and the lines that use removed or retyped members, then ask before writing. Declining puts everything back. Pass `-y` to skip the question; scripts and CI aren't asked. See [Reviewing changes](/cli/generators#reviewing-changes). - **A smaller Megh logo** above `megh --help`. ## New in 0.6.1 No code changes needed. Everything here is opt-in. - **Mail.** Inject `Mailer` and send `Mailable` classes over SMTP, or over SendGrid, Mailgun, Postmark or Resend's HTTP APIs. A failover mailer tries each in turn. `queue()` and `later()` send through the queue. Turn it on with `app.useMail()`, configured from `MEGH_MAIL_*` in `.env`; options passed to `useMail()` override them. See [Mail](/advanced/mail). - **Security headers.** `app.useSecurityHeaders()` sends a Content Security Policy, HSTS, `X-Frame-Options`, `nosniff` and the other usual headers. It is built in, so `@fastify/helmet` is no longer needed. See [Security Hardening](/production/security#add-security-headers). - **Rate limiting.** `app.useRateLimit()` limits requests per client and answers 429. `@RateLimit()` gives a route its own limit, and `RedisRateLimitStore` shares counts between replicas. It is built in, so `@fastify/rate-limit` is no longer needed. See [Security Hardening](/production/security#add-rate-limits). - **CLI:** - `megh make:mail ` creates a Mailable. - `megh new` offers a Mail feature. - `megh new` runs `git init` (skip it with `--skip-git` or `MEGH_SKIP_GIT=1`). - Generated resource services have JSDoc. - **Fixes:** - `megh new` now installs the OpenAPI packages when you pick OpenAPI or Scalar, so the generated app starts. - The "No mailer is set" error lists every configured mailer. If you registered `@fastify/helmet` or `@fastify/rate-limit` yourself in an `onInit` hook, as the 0.6.0 docs suggested, that keeps working. To switch, remove the `app.app.register(...)` calls, uninstall the two packages, and call `app.useSecurityHeaders()` and `app.useRateLimit()` instead. ## Breaking in 0.6.0 ### Removed APIs These did nothing, or were a second name for another API. Delete the calls, or switch to the replacement: | Removed | Use instead | |---------|-------------| | `app.useHttps()` | Nothing: it was a no-op. For HTTPS, pass `server: { https: { key, cert } }` to `Megh.createApplication()`, or terminate TLS at a proxy | | `app.useSerialization()` | Nothing: it was a no-op | | `app.mapFeatures()` | Nothing: it was a no-op | | `MeghSocketIo` | Get the server with `MeghContainer.get(SocketIoServer)`. See [WebSocket](/microservices/websocket) | | `DuplicateRouteException` | Nothing. Fastify already refuses duplicate routes at startup | | `MeghRouter.mapRoute()`, `MeghRouter.registerMiddleware()` | `app.mapGet()` and the other `map*` methods, and `app.useMiddlewares()` | | `CreateSwaggerObjectSchema`, `GetObjectSchema` | `generateClassSchema` | Your type checker finds every call that needs changing. ### `app.run()` reads `PORT` `app.run()` without a port now listens on the `PORT` environment variable, like it already read `HOST`, and falls back to `4000`. A port passed to `run()` still wins: ```ts app.run(); // PORT, else 4000 app.run(3000); // 3000, whatever PORT says ``` An app that calls `app.run()` without a port and has `PORT` set to something else, for example by the hosting platform, now listens on `PORT`. That's usually what you want. To keep the old behaviour, pass the port explicitly. An invalid `PORT`, such as `abc`, now stops startup with an error. Apps created by the CLI read `PORT` themselves in `serve.ts` and keep working. You can simplify `serve.ts` to `app.run()`. ### Framework logs go through the logger Framework messages that went to `console` now go through the [logger](/advanced/logging). That includes the startup line `Application running on

`, and warnings such as a route using `@Authorized` with no authorization handler registered. In production they're JSON lines like every other log entry. If a test spied on `console.warn` or `console.error` to check one of these messages, spy on the logger instead. See [Testing](/advanced/testing). ## Other changes - **New projects leave `NODE_ENV` out of `.env`.** `megh serve` already runs the app in development and `megh start` in production. The old line turned on development mode, with error details in responses, when a project's `.env` was deployed and the app started with `node dist/serve.js`. In an existing project, remove `NODE_ENV=development` from `.env` if you deploy that file. See [Deployment](/production/deployment#environment). - **`MeghScheduler` is exported**, for running scheduled tasks in a process without the HTTP app. See [Scheduler](/advanced/scheduler). - **New docs:** [Application](/getting-started/application), [Configuration](/core-concept/configuration), [Scheduler](/advanced/scheduler), [Testing](/advanced/testing), [Deployment](/production/deployment), [Security Hardening](/production/security), [API Reference](/reference/api), [Versioning Policy](/reference/versioning) and [FAQ](/reference/faq). - **Doc fixes:** `useStaticFiles` takes `root`, not `path`. `useMultipart` limits files to 10 MB unless you pass `limits`, on top of `FileStorage`'s 50 MB. ## Coming from older versions On 0.5.0 to 0.5.4, read [Upgrading to 0.5.5](/getting-started/upgrading-0.5) first. --- # Upgrading to 0.5.5 Source: https://meghjs.github.io/getting-started/upgrading-0.5 0.5.1 to 0.5.4 need no code changes: apps written for 0.5.0 keep working. 0.5.1 brings Megh's own ORM setup and DI container, and deprecates `app.useDatabase()`. 0.5.2 is a bug-fix release. 0.5.3 adds seeders, factories and documented responses, and fixes the ORM on SQL Server. 0.5.4 adds scaffolding to the CLI and documents `@Query()` parameters. 0.5.5 adds Megh's own validation decorators, exception filters, health checks and request IDs, and fixes a batch of runtime bugs. Most apps need no code changes, but read [Breaking in 0.5.5](#breaking-in-0-5-5) first: the middleware order changed, and some routes now send the status they declare. ```sh npm i @meghjs/core@^0.5.5 npm i -D @meghjs/cli@^0.5.5 ``` ## Breaking in 0.5.5 - **`@UseMiddleware` runs before authentication.** The pipeline is now middleware → authentication → `@Authorized` → validation → handler, for global, controller and route middleware alike. Before, `@UseMiddleware` ran after `@Authorized` and could read `request.user`. Move logic that needs the user into the authorization handler or the route, or read the user in a later middleware of your own. See [Pipeline order](/core-concept/middleware#pipeline-order). - **`app.run()` listens on `0.0.0.0` by default** instead of localhost, so the app is reachable inside containers. Keep local-only with `app.run(port, { host: '127.0.0.1' })` or `HOST=127.0.0.1`. - **Status codes are honoured.** `@HttpCode`, `Results.Created`, `Results.NoContent`, `Results.NotFound` and `HttpResponse.Created` now send their status instead of 200. Clients that checked for 200 on these routes need updating. - **Unknown routes** answer `{ code: 404, status: "Error", message }` instead of Fastify's default 404 body. - **`MeghTest`** uses the production error handler, so tests see redacted 5xx responses (`Internal Server Error`) unless `NODE_ENV=development`. ## New in 0.5.5 - [Validation decorators](/core-concept/validation) in `@meghjs/core`: `IsString`, `MinLength`, `ValidateNested`, `Type`, `Transform` and more, with class-validator's names, options and messages. Each DTO is compiled once, so validating a request is several times faster. Switching a DTO is a change of import; class-validator DTOs keep working. Also `validateDto()`. - `experimental.compiledValidation` (or `MEGH_COMPILED_VALIDATION=1`) speeds up class-validator DTOs with the same results. - `validator` is an optional peer dependency, needed only for `@IsUUID`, `@IsUrl` and `@IsEmail` with options. - [Error handling](/core-concept/error-handling): exception filters, `@Catch`, `@UseFilters`, `app.useErrorHandler()`, `app.useErrorLogger()` and more HTTP exception classes. - Inline routes get `mapPatch`, the authentication handler, and `.authorized()`, and they send `Results` with their status. - `app.run(port, { host, onListen, shutdownTimeout })`. - `MEGH_DOTENV=false` skips loading `.env` on import. - [Health checks](/advanced/health): `app.useHealth()` serves `/health` and `/ready`; Megh ORM registers a `database` check. - [Request IDs](/advanced/logging#request-ids): an `x-request-id` on every response, `reqId` on every log line, and `getRequestId()`. ## Fixes in 0.5.5 - `useScheduler({ path })` no longer crashes `run()`. - `@UploadFile` and `@UploadFiles` receive the saved files. - `@All()` registers every method instead of crashing. - Framework errors keep their status (400 bad JSON, 413, 415, 429). - A failing socket listener is logged instead of crashing the process. - Two controllers with the same class name no longer share route metadata. - Shutdown closes the cache, exits with code 1 on failure, and gives up after `shutdownTimeout`. - `.env` is parsed once instead of on every `Environment.get()`. - Inline route middleware classes are called with `this` bound. ## New in 0.5.4 - **Tables and models from templates.** `npx megh make:model Product --template ecommerce/product` (or `make:resource`) writes the create-table migration and the model (or the whole REST resource). Tables its foreign keys point to are created too. `--fields "title,price:money,status:in(draft|live)"` describes a table on the command line, with presets such as `slug`, `price` and `address`. See [Templates and Fields](/cli/scaffold/templates). - **Business domains.** `npx megh scaffold:domain ecommerce` (`sc:domain`) scaffolds a domain's tables at once. There are 11 domains: common, e-commerce, POS, medical, construction, marketing, real estate, HR, CRM, education and logistics. Add your own in `.megh/templates/`. See [Domains](/cli/scaffold/domains). - **Auth.** `npx megh scaffold:auth` (`sc:auth`) adds sign-up and sign-in with JWTs, API keys or both, and optionally roles and permissions: the tables, password hashing, `AppAuthentication`, `AppAuthorization`, an `AuthController` and a roles seeder, registered in `src/app.ts`. See [Auth](/cli/scaffold/auth). - **RBAC.** `npx megh scaffold:rbac` (`sc:rbac`) adds roles (one or many per user) and permissions, checked with `@Authorized({ roles })` and `@Authorized({ permissions })`. See [RBAC](/cli/scaffold/rbac). - **`megh template:list`** (`templates`) lists the templates. - **SQL Server-safe foreign keys.** On SQL Server, scaffolded migrations avoid the "may cause cycles or multiple cascade paths" error and write `restrict` as `NO ACTION`. See [SQL Server](/cli/scaffold/templates#sql-server). ## Fixes in 0.5.4 - **`@Query()` parameters are documented.** A `@Query()` DTO and `@Query('key')` parameters were missing from the OpenAPI document. Each DTO property and each key is now a query parameter, with its type and constraints. See [Query parameters](/microservices/openapi#query-parameters). ## New in 0.5.3 - **Seeders.** `npx megh make:seeder users` writes a seeder, and `npx megh db:seed` (or `megh migrate --seed`) runs them in one transaction, so a failing seeder saves nothing. See [Seeding and Factories](/advanced/orm/seeding). - **Factories with Faker.** `defineFactory(User, ({ faker }) => ({ … }))` builds rows with fake values, and `npx megh make:factory user` writes one from the model's columns. Install Faker to use them: `npm i -D @faker-js/faker`. See [Factories](/advanced/orm/seeding#factories). - **`megh update:model`.** After an alter-table migration, it brings a model's column fields up to date and keeps relations and methods. See [Updating a model](/cli/generators#updating-a-model). - **Relation fields typed with the model.** Write `@BelongsTo(() => Role) role?: Role | null` and `posts?: Post[]` instead of `BelongsTo` and `HasMany`, which still work. See [Relations](/advanced/orm/relations). - **Documented responses.** `@ApiResponse(200, User)` documents a response with a model or DTO, `Paginated(User)` a page, and Megh adds the `400`, `401` and `403` a route can return. `make:resource` writes them. See [Responses](/microservices/openapi#responses). - **Typed OpenAPI options.** `OpenApiUiOptions` types every option, including Swagger UI's settings, and `auth: 'bearer'` marks `@Authorized` routes. See [Securing routes](/microservices/openapi#securing-routes). ## Fixes in 0.5.3 - **Creating rows works on SQL Server.** `create()`, `save()` and `insertGetId()` saved the row, then failed with `Validation failed for parameter '1'. Invalid number.` They now return the row with `OUTPUT inserted.*`. - **SQL Server shows the real error.** A failing migration or transaction could report `The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION` instead of what went wrong, for example a foreign key to a table that doesn't exist. - **`dropColumn()` works on SQL Server** for columns with a default. - **Optional relation fields are relations.** A field such as `role?: BelongsTo` was treated as a column, so `create()` accepted it and `with('role')` didn't type-check. - **The route decorators' `openapi` option is read.** `@Get('/', { openapi: { … } })` was ignored. ## Changes to note in 0.5.3 - `make:model` writes the column type on nullable columns (`@Column({ nullable: true, type: "string" })`), so OpenAPI can document them. Running `update:model` adds it to fields it generated before. - Migrations' `table.string("name", 20)` is read as `varchar(20)`, so `make:resource` DTOs now get `@MaxLength(20)`. - `OpenApiResponse()` is deprecated: it documents a `{ code, status, data }` wrapper that Megh doesn't send. Use `@ApiResponse()`. - Code that passed a relation to `create()` or `fill()` through an optional marker field now fails to compile, as it should. ## Fixes in 0.5.2 - **`@UseMiddleware(SomeClass)` works.** Passing a middleware class to `@UseMiddleware` on a controller or route crashed `app.run()` with `Function is not registered`. Classes are now resolved through the DI container, so they can use constructor injection. The `@UseMiddleware(new SomeClass())` workaround still works. See [Middleware](/core-concept/middleware#controller-scoped). - **Paging works on SQL Server.** `limit()`, `offset()`, `first()`, `find()`, `exists()`, `paginate()`, `simplePaginate()` and `forPage()` failed with `Incorrect syntax near 'limit'`. Queries now use `top(n)` and `offset … fetch next … rows only` on SQL Server. See [Paging on SQL Server](/advanced/orm/queries#paging-on-sql-server). ## Changes in 0.5.1 ### Connect with `useMeghORM()` Megh now creates the database connection itself. Kysely ships with `@meghjs/core`, so an app only installs the driver for its database. ```ts [src/app.ts] // Before (0.5.0) import { db } from "./database/connection"; app.useDatabase(db); // After (0.5.1+) app.useMeghORM(); // reads DATABASE_URL, or pass { dialect, host, ... } ``` 1. Put the connection in `.env`, for example `DATABASE_URL=postgres://app:secret@localhost:5432/app`. [Connecting](/advanced/orm#connecting) lists every option and variable. 2. Replace `app.useDatabase(db)` with `app.useMeghORM()`. 3. Delete `src/database/connection.ts`, and a `"database"` path under `"megh"` in `package.json` if you set one. While that file exists, `megh migrate` keeps using it; once it's gone, migrations connect from `DATABASE_URL` too. 4. Uninstall `kysely` unless your own code imports it. `app.useDatabase(db)` still works in 0.5.x and logs a deprecation warning. ### Models with decorators Models can describe their table with decorators. Models written with `static table` and `hasMany(() => Post)` keep working, so move them over when it suits you. ```ts @Table("users") export class User extends Model { @PrimaryKey() @AutoIncrement() id?: number; @Column({ unique: true }) email!: string; @Column({ name: "display_name" }) displayName!: string; @CreatedAt() createdAt?: Date; @HasMany(() => Post) posts!: HasMany; } ``` - Fields marked `?` are optional in `create()`. - `@Column({ name })`, or `useMeghORM({ naming: 'snake_case' })`, maps camelCase properties to other column names. See [Column names](/advanced/orm/models#column-names). - `npx megh make:model` now writes decorator models. ### Migrations with the schema builder `npx megh make:migration` now writes migrations with Megh's schema builder, which picks the right SQL type for each database: ```ts export default defineMigration({ async up(schema) { await schema.create("users", (table) => { table.id(); table.string("email").unique(); table.timestamps(); }); }, async down(schema) { await schema.dropIfExists("users"); }, }); ``` Existing Kysely migrations (`export async function up(db)`) still run, in order with the new ones. ### The `DB` query builder For queries that don't need a model: ```ts import { DB } from "@meghjs/core"; const ids = await DB.table("users").where("active", true).pluck("id"); await DB.transaction(async () => { /* ... */ }); ``` See [Query builder](/advanced/orm/query-builder). ### Megh's own DI container `typedi` is no longer a dependency. `MeghContainer`, `@Injectable()`, `Token` and `inject()` keep their API, and `inject()` now also works in field initializers: ```ts @Injectable() class UserService { private readonly users = inject(UserRepository); private readonly mailer = inject(Mailer, { optional: true }); } ``` If your app imported `typedi` directly, switch to `MeghContainer` or add `typedi` to your own dependencies. Missing services and dependency cycles now fail with the full constructor chain in the error. See [Dependency Injection](/core-concept/dependency-injection). ### `megh new` New projects can include the ORM: pick **MeghORM** from the features, or pass `--database postgres|mysql|sqlite|mssql`. --- # Moving from Avleon to Megh Source: https://meghjs.github.io/getting-started/upgrading-megh Avleon has been renamed to **Megh** (মেঘ, Bengali for "cloud"). The framework is the same: only the names change. The `@avleon/*` packages are deprecated and get no new releases; new versions are published as `@meghjs/*`. The rename shipped in **0.5.0**: Avleon 0.4.1 is the last `@avleon/*` release, and `@meghjs/*` starts at 0.5.0 with the same features. | Before | After | |---|---| | `@avleon/core` | `@meghjs/core` | | `@avleon/cli` | `@meghjs/cli` | | `@avleon/data` | `@meghjs/data` | | github.com/avleonjs/avleon | [github.com/meghjs/megh](https://github.com/meghjs/megh) | | avleonjs.github.io | [meghjs.github.io](https://meghjs.github.io) | If you are on 0.3 or earlier, upgrade to Avleon 0.4 first ([Upgrading to 0.4](/getting-started/upgrading-0.4)), then follow this page. ## 1. Swap the packages ```sh npm uninstall @avleon/core @avleon/cli @avleon/data npm i @meghjs/core npm i -D @meghjs/cli npm i @meghjs/data # only if you used @avleon/data ``` ## 2. Rename the imports and APIs Every export that started with `Avleon` now starts with `Megh`, and every `AVLEON_` constant starts with `MEGH_`: | Before | After | |---|---| | `Avleon.createApplication()` | `Megh.createApplication()` | | `AvleonApplication`, `AvleonContainer`, `AvleonConfig`, `AvleonTest`, ... | `MeghApplication`, `MeghContainer`, `MeghConfig`, `MeghTest`, ... | | `@AvleonWorker`, `AvleonEvent`, `AvleonRepository`, ... | `@MeghWorker`, `MeghEvent`, `MeghRepository`, ... | | `AVLEON_KNEX_DB` | `MEGH_KNEX_DB` | On macOS or Linux, this rewrites a typical project in one pass. Commit first, then review the diff: ```sh grep -rlE 'avleon|Avleon|AVLEON' src test package.json tsconfig.json *.d.ts 2>/dev/null \ | xargs sed -i.bak -e 's#@avleon/#@meghjs/#g' -e 's/AVLEON/MEGH/g' \ -e 's/Avleon/Megh/g' -e 's/avleon/megh/g' find . -name '*.bak' -not -path './node_modules/*' -delete ``` ## 3. The CLI command is `megh` ```sh npx megh serve # was: npx avleon serve npx megh make:controller users npx megh migrate ``` Update the `scripts` in `package.json` (`avleon serve` → `megh serve`, and so on). ## 4. Configuration and generated files | Before | After | |---|---| | `"avleon": { "entry", "database", "migrations" }` in `package.json` | `"megh": { ... }` | | `avleon-env.d.ts` | `megh-env.d.ts`, with `@meghjs/data` in place of `@avleon/data`. Rename the file and update `tsconfig.json`'s `include`. | | `AVLEON_QUEUE_DRIVER` env variable | `MEGH_QUEUE_DRIVER` | | `AVLEON_SKIP_INSTALL` env variable | `MEGH_SKIP_INSTALL` | ## 5. For plugin authors Plugins declare their entry under a `megh` key in `package.json`: ```json { "megh": { "plugin": "./dist/plugin.js" } } ``` Packages that still use the `avleon` key are not discovered. Rename the key and import `MeghPlugin` from `@meghjs/core`. ## 6. OpenAPI Request body metadata in the generated spec uses the `x-megh-request-body` extension instead of `x-avleon-request-body`. This only matters if you post-process the spec and look for that key. --- # Upgrading to 0.4 Source: https://meghjs.github.io/getting-started/upgrading-0.4 ::: info Avleon is now Megh This guide predates the rename and uses the old `@avleon/*` names. After upgrading, follow [Moving from Avleon to Megh](/getting-started/upgrading-megh). ::: 0.4 moves the database integrations into their own package, adds plugins and lifecycle hooks, and fixes security issues in optional dependencies. `@avleon/core`, `@avleon/cli` and the new `@avleon/data` are released together and share a version, so upgrade them together: ```sh npm i @avleon/core@^0.4.1 @avleon/cli@^0.4.1 ``` ## 1. TypeORM and Knex moved to `@avleon/data` If your app uses `useTypeORM`, `useKnex` or any database helper, install the new package: ```sh npm i @avleon/data@^0.4.0 ``` `app.useTypeORM()` and `app.useKnex()` keep their signatures. They are added by the `@avleon/data` [plugin](/advanced/plugins), which the app finds among its dependencies, so there is nothing to import or register. For TypeScript to see the methods, add this file and include it in `tsconfig.json`: ```ts [avleon-env.d.ts] /// ``` ```json [tsconfig.json] { "include": ["avleon-env.d.ts", "src/**/*"] } ``` Import the database APIs from `@avleon/data` instead of `@avleon/core`: ```ts // Before import { InjectRepository, KnexDB, AvleonRepository, Like } from '@avleon/core'; // After import { InjectRepository, KnexDB, AvleonRepository, Like } from '@avleon/data'; ``` That covers `InjectRepository`, `PaginatedRepository`, `AvleonRepository`, `Repository`, the query operators (`Like`, `ILike`, `In`, `Not`, `Between`, …), `KnexDB`, `AVLEON_KNEX_DB`, `paginateKnex`, `registerDataSource`, `getDataSource` and `DATASOURCE_TOKEN`. `Collection`, `List` and the pagination helpers stay in `@avleon/core`. Also changed: - `Collection.fromRepository(Entity)` is now `paginatedRepository(Entity)` from `@avleon/data`. - `useDatasource()`, the `dataSourceOptions` application option and the `dataSource` option of `createTestApplication` are removed. Use `await app.useTypeORM(options)`. - The connection opened by `useTypeORM` or `useKnex` is now closed when the app shuts down. ## 2. Upgrade `@fastify/static` and `@fastify/swagger-ui` Every 8.x and 9.x release of `@fastify/static` is vulnerable to path traversal, so core now requires patched versions of these optional peers. If you use `useStaticFiles` or Swagger UI: ```sh npm i @fastify/static@^10.1.2 @fastify/swagger-ui@^6.1.2 ``` ## 3. `MockDB` is removed `MockDB` called the global `jest.fn()` and only worked under Jest. Mock your data layer with your test framework instead. ## 4. Dependency injection Avleon now has its own container API. Use it rather than importing `typedi`, which may be replaced: | Use | For | |-----|-----| | `AvleonContainer.get / set / has / reset` | Resolving and registering values | | `@Injectable()` | Classes the container constructs (as `@AppService` does) | | `new Token('name')` | Values that are not classes | `AvleonContainer` no longer exposes the rest of typedi's API, and `@Utility()` / `@Helper()` no longer take typedi options. `AvleonContainer.reset()` no longer calls `destroy()` on the instances it discards. ## 5. New projects use Vitest `avleon new` now scaffolds Vitest instead of Jest, with SWC for decorator metadata. Existing projects are not changed. ## What's new - [Lifecycle hooks](/getting-started/application#lifecycle-hooks): `app.onInit`, `app.onReady`, `app.onClose`, and `app.close()` for a clean shutdown. - [Plugins](/advanced/plugins): packages can add `app.use*` methods, services and hooks, and are found automatically once installed. ### 0.4.1 - [MeghORM](/advanced/orm): type-safe models built on Kysely, with relations and eager loading, timestamps, soft deletes, casts and transactions. Connect them with `app.useDatabase(db)`. - [Migrations](/advanced/orm/migrations): `avleon make:migration` and the `migrate`, `migrate:status`, `migrate:rollback`, `migrate:reset` and `migrate:refresh` [commands](/cli/database#migrations). - The generated [OpenAPI](/microservices/openapi) spec now documents request bodies. The full list of changes is in the [changelog](https://github.com/avleonjs/avleon/blob/main/packages/core/CHANGELOG.md). --- # Upgrading to 0.3 Source: https://meghjs.github.io/getting-started/upgrading ::: info Avleon is now Megh This guide predates the rename and uses the old `@avleon/*` names. After upgrading, follow [Moving from Avleon to Megh](/getting-started/upgrading-megh). ::: `@avleon/core` 0.3 closes several security holes and unifies APIs that were inconsistent in 0.2. Most apps need a few changes, listed below. ## 1. Install the peer dependencies you use Integrations moved from `dependencies` to optional peer dependencies. Install `class-validator` and `class-transformer` in every project, plus whichever of these you use: ```sh npm i @fastify/cors # useCors npm i @fastify/multipart # useMultipart, @UploadFile npm i @fastify/static # useStaticFiles npm i @fastify/swagger @fastify/swagger-ui # useOpenApi (Swagger UI) npm i @fastify/swagger @scalar/fastify-api-reference # useOpenApi (Scalar) npm i socket.io fastify-socket.io # useSocketIo npm i -D pino-pretty # pretty dev logs ``` The package is CommonJS only, with an `exports` map. Imports from `@avleon/core/dist/...` no longer resolve; import from `@avleon/core`. The license is now MIT. ## 2. Set `NODE_ENV=development` locally `app.isDevelopment()` is now true only when `NODE_ENV=development`. An unset `NODE_ENV` counts as production, which: - turns off anything behind `if (app.isDevelopment())`, such as OpenAPI docs, - hides the message and data of 5xx errors, - switches logs to JSON. ## 3. Authorization denies by default - A route with `@Authorized` returns **403** if no authorizer is registered. - An authorizer that returns `false` now denies with 403. Throwing still works. - `AuthorizeMiddleware`, `AppAuthorization`, `AuthHandler` and `AuthReturnTypes` were removed. Write a plain class with an `authorize()` method: ```ts // before @CanAuthorize class JwtAuthorization extends AuthorizeMiddleware { ... } // after @CanAuthorize class JwtAuthorization { async authorize(req: IRequest, options?: { roles?: string[] }) { if (!req.user) return false; } } ``` See [Authentication](/core-concept/authentication). ## 4. Validation is stricter - Properties not declared on a `@Body()`/`@Query()` DTO are rejected with 400. - The handler receives the DTO instance, not the plain object. - The 400 response body changed: ```json // before { "code": 400, "error": "ValidationError", "errors": [ ... ] } // after { "code": 400, "status": "Error", "message": "msg1; msg2", "errors": [ ... ] } ``` ## 5. One pagination shape Every paginator now takes `{ page, perPage }` and returns `{ data, meta: { total, page, perPage, lastPage, next, prev } }`. The old shapes (`{ total, totalPage, next, data }` and `{ data, total, page, limit, totalPages, hasNext, hasPrev }`) are gone. `take`, `skip` and `limit` are still accepted but deprecated. See [Pagination](/advanced/database#pagination). ## 6. File storage is safe by default - Saved files get random UUID names. Use `saveAs` (formerly `as`) or `preserveFilename: true` to choose the name. - `overwrite` defaults to `false`. - An extension allowlist and a 50 MB size limit apply. - `download`, `downloadAs` and `getUploadFile` resolve paths relative to the storage `baseDir` and reject anything outside it. - `save` returns `{ filename, originalFilename, size, uploadPath, staticPath }`. - `UploadFileFromRequest`'s `dest` is now a directory path string. See [File Uploads](/advanced/file-uploads). ## 7. Events, queues and cache - `EventDispatcher.dispatch` takes an `AvleonEvent` instance, not a string. - Kafka and RabbitMQ broadcast throw "not implemented". Socket broadcast requires `app.useSocketIo()`. - `EventRegistry.getListeners` takes a class or event, and `flushOnce` was removed. - `@AvleonWorker` no longer starts on import. Register workers with `app.useWorker([...])`. - The in-memory cache enforces TTLs, and each `new CacheManager()` has its own store. ## 8. Removed exports `registerKnex`, `FEATURE_KEY`, `uuid`, `getLineNumber`, `MatchLocation`, `extrctParamFromUrl`, `findDuplicates`, `isClassValidator`, `validateRequestBody`, `OkOptions`, `Results.code`, `KafkaBroadcastOption`, `RabbitMqBroadcastOption`, and the `ControllerOptions` fields `version`, `since` and `meta`. `Results.Ok(x)` now serializes as `{ headers, data, statusCode }`. ## Known issues in 0.3.0 These are expected to be fixed in a patch release: | Issue | Workaround | |-------|------------| | `@UseMiddleware(SomeClass)` crashes `app.run()` | Fixed in 0.5.2. On older versions, pass an instance: `@UseMiddleware(new SomeClass())` | | `@Repository` and `@Queue` classes without a constructor break under DI | Add `constructor() { super(); }` | | `Results.Created`/`NoContent`/`NotFound`, `HttpResponse.Created` and `@HttpCode` respond with 200 | Fixed in 0.5.5. On older versions, throw `HttpExceptions` for error statuses | | `@Body()`/`@Query()` DTOs are missing from the OpenAPI document | Describe them with `@OpenApi({ requestBody, query })` | | `@All()` crashes `app.run()` | Fixed in 0.5.5. On older versions, register each method separately | | Upload policy violations return 500 instead of 400/413 | None | | `app.run()` has no `host` option and binds to localhost | Fixed in 0.5.5: `app.run(port, { host })`, defaulting to `HOST` or `0.0.0.0` |