# 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