@meghjs/mcp 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +141 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +37 -0
- package/dist/docs/advanced/caching.md +72 -0
- package/dist/docs/advanced/database.md +328 -0
- package/dist/docs/advanced/events.md +169 -0
- package/dist/docs/advanced/file-uploads.md +141 -0
- package/dist/docs/advanced/health.md +81 -0
- package/dist/docs/advanced/logging.md +96 -0
- package/dist/docs/advanced/mail.md +439 -0
- package/dist/docs/advanced/orm/migrations.md +210 -0
- package/dist/docs/advanced/orm/models.md +291 -0
- package/dist/docs/advanced/orm/queries.md +169 -0
- package/dist/docs/advanced/orm/query-builder.md +120 -0
- package/dist/docs/advanced/orm/relations.md +179 -0
- package/dist/docs/advanced/orm/seeding.md +129 -0
- package/dist/docs/advanced/orm.md +145 -0
- package/dist/docs/advanced/plugins.md +90 -0
- package/dist/docs/advanced/queue.md +217 -0
- package/dist/docs/advanced/scheduler.md +253 -0
- package/dist/docs/advanced/testing.md +257 -0
- package/dist/docs/advanced/views.md +335 -0
- package/dist/docs/ai/mcp.md +162 -0
- package/dist/docs/cli/basic.md +133 -0
- package/dist/docs/cli/database.md +112 -0
- package/dist/docs/cli/generators.md +605 -0
- package/dist/docs/cli/scaffold/auth.md +172 -0
- package/dist/docs/cli/scaffold/domains.md +224 -0
- package/dist/docs/cli/scaffold/index.md +77 -0
- package/dist/docs/cli/scaffold/rbac.md +118 -0
- package/dist/docs/cli/scaffold/templates.md +235 -0
- package/dist/docs/core-concept/authentication.md +162 -0
- package/dist/docs/core-concept/configuration.md +268 -0
- package/dist/docs/core-concept/controller.md +350 -0
- package/dist/docs/core-concept/dependency-injection.md +213 -0
- package/dist/docs/core-concept/error-handling.md +185 -0
- package/dist/docs/core-concept/middleware.md +143 -0
- package/dist/docs/core-concept/request-context.md +110 -0
- package/dist/docs/core-concept/validation.md +355 -0
- package/dist/docs/getting-started/application.md +233 -0
- package/dist/docs/getting-started/installation.md +166 -0
- package/dist/docs/getting-started/introduction.md +136 -0
- package/dist/docs/getting-started/upgrading-0.4.md +125 -0
- package/dist/docs/getting-started/upgrading-0.5.md +293 -0
- package/dist/docs/getting-started/upgrading-0.6.md +251 -0
- package/dist/docs/getting-started/upgrading-0.7.md +225 -0
- package/dist/docs/getting-started/upgrading-megh.md +91 -0
- package/dist/docs/getting-started/upgrading-next.md +12 -0
- package/dist/docs/getting-started/upgrading.md +137 -0
- package/dist/docs/getting-started/usage.md +194 -0
- package/dist/docs/index.md +58 -0
- package/dist/docs/microservices/openapi.md +387 -0
- package/dist/docs/microservices/websocket.md +165 -0
- package/dist/docs/production/deployment.md +256 -0
- package/dist/docs/production/security.md +307 -0
- package/dist/docs/reference/api.md +999 -0
- package/dist/docs/reference/faq.md +227 -0
- package/dist/docs/reference/versioning.md +105 -0
- package/dist/docs.d.ts +30 -0
- package/dist/docs.js +126 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +22 -0
- package/dist/megh.d.ts +59 -0
- package/dist/megh.js +207 -0
- package/dist/prompts.d.ts +3 -0
- package/dist/prompts.js +47 -0
- package/dist/result.d.ts +18 -0
- package/dist/result.js +48 -0
- package/dist/server.d.ts +17 -0
- package/dist/server.js +40 -0
- package/dist/tools/context.d.ts +11 -0
- package/dist/tools/context.js +2 -0
- package/dist/tools/database.d.ts +8 -0
- package/dist/tools/database.js +58 -0
- package/dist/tools/docs.d.ts +3 -0
- package/dist/tools/docs.js +63 -0
- package/dist/tools/generate.d.ts +10 -0
- package/dist/tools/generate.js +177 -0
- package/dist/tools/project.d.ts +3 -0
- package/dist/tools/project.js +84 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +10 -0
- package/package.json +58 -4
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Templates and Fields
|
|
3
|
+
description: Create tables and models from templates and field specs with make:model --template and --fields.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Templates and Fields
|
|
7
|
+
|
|
8
|
+
## From a Template
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npx megh make:model Product --template ecommerce/product
|
|
12
|
+
npx megh make:resource Product --template ecommerce/product # + DTOs, service, controller
|
|
13
|
+
npx megh m:m Product --template # pick a domain, then a template
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
A template is named `<domain>/<name>`. A bare name works when only one
|
|
17
|
+
domain has it, and a `common` template wins (`--template category` is
|
|
18
|
+
`common/category`). See every template on the [Domains](/cli/scaffold/domains)
|
|
19
|
+
page, or list them:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npx megh template:list # domains and templates
|
|
23
|
+
npx megh templates ecommerce # one domain, with each template's columns
|
|
24
|
+
npx megh templates --json
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
For `make:model Product --template ecommerce/product`:
|
|
28
|
+
|
|
29
|
+
```ts [src/database/migrations/20261110093000_create_products_table.ts]
|
|
30
|
+
import { defineMigration } from "@meghjs/core";
|
|
31
|
+
|
|
32
|
+
export default defineMigration({
|
|
33
|
+
async up(schema) {
|
|
34
|
+
await schema.create("products", (table) => {
|
|
35
|
+
table.id();
|
|
36
|
+
table.foreignId("category_id").constrained("categories").nullOnDelete();
|
|
37
|
+
table.foreignId("brand_id").constrained("brands").nullOnDelete();
|
|
38
|
+
table.string("name");
|
|
39
|
+
table.string("slug").unique();
|
|
40
|
+
table.string("sku", 64).unique();
|
|
41
|
+
table.text("description").nullable();
|
|
42
|
+
table.decimal("price", 12, 2);
|
|
43
|
+
table.decimal("compare_at_price", 12, 2).nullable();
|
|
44
|
+
table.decimal("cost", 12, 2).nullable();
|
|
45
|
+
table.integer("stock").default(0);
|
|
46
|
+
table.decimal("weight", 10, 3).nullable();
|
|
47
|
+
table.string("status", 32).default("draft"); // draft | active | archived
|
|
48
|
+
table.boolean("is_featured").default(false);
|
|
49
|
+
table.timestamps();
|
|
50
|
+
table.softDeletes();
|
|
51
|
+
table.index("status");
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
async down(schema) {
|
|
56
|
+
await schema.drop("products");
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Since no migration creates `categories` or `brands`, their migrations
|
|
62
|
+
(`common/category`, `ecommerce/brand`) and models are written first. You are
|
|
63
|
+
asked before they are added; `--no-deps` leaves them out (create those
|
|
64
|
+
tables yourself before migrating).
|
|
65
|
+
|
|
66
|
+
The model's name sets the table: `make:model Item --template ecommerce/product`
|
|
67
|
+
creates `items` with the product columns. Pass `--table <name>` to choose it.
|
|
68
|
+
|
|
69
|
+
### Options
|
|
70
|
+
|
|
71
|
+
| Option | Description |
|
|
72
|
+
|---|---|
|
|
73
|
+
| `--template [ref]` | The template; without a value, pick one |
|
|
74
|
+
| `--fields <list>` | Columns to add to the template, or to replace its columns of the same name |
|
|
75
|
+
| `--table <name>` | Table name (default: from the model name) |
|
|
76
|
+
| `--factory` | Also write a [factory](/advanced/orm/seeding) for each model |
|
|
77
|
+
| `--no-deps` | Don't create the tables foreign keys point to |
|
|
78
|
+
| `-f`, `--force` | Overwrite the model (or the resource's files) if they exist |
|
|
79
|
+
| `-y`, `--yes` | Don't prompt |
|
|
80
|
+
|
|
81
|
+
## From Fields
|
|
82
|
+
|
|
83
|
+
Describe the table on the command line, with or without a template:
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
npx megh make:resource Ticket --fields "title,body,priority,status:in(open|pending|closed),user_id:cascade"
|
|
87
|
+
npx megh make:model Product --template ecommerce/product --fields "barcode?:string(64):unique,weight:decimal(8,2)"
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Every table gets an `id` and timestamps. Foreign keys to tables no migration
|
|
91
|
+
creates are handled as with templates (`user_id` above brings in `users`).
|
|
92
|
+
|
|
93
|
+
## Field Spec
|
|
94
|
+
|
|
95
|
+
A field is written `name[?][:type[(args)]][:modifier]...`, and a list is
|
|
96
|
+
separated by commas:
|
|
97
|
+
|
|
98
|
+
| Spec | Column |
|
|
99
|
+
|---|---|
|
|
100
|
+
| `title` | The `title` preset: `string(255)` |
|
|
101
|
+
| `slug` | The `slug` preset: `string(255)`, unique |
|
|
102
|
+
| `email:unique` | The `email` preset, unique |
|
|
103
|
+
| `phone?` | The `phone` preset, nullable (`?`) |
|
|
104
|
+
| `address?` | The `address` group: six columns, all nullable |
|
|
105
|
+
| `nickname?:string(50)` | `string(50)`, nullable |
|
|
106
|
+
| `price:money` | `decimal(12,2)` |
|
|
107
|
+
| `hours:decimal(5,1):default(0)` | `decimal(5,1)` with a default |
|
|
108
|
+
| `status:in(draft\|published)` | `string(32)` that defaults to `draft`, the allowed values in a comment |
|
|
109
|
+
| `kind:in(a\|b)` | `string(32)`, required |
|
|
110
|
+
| `category_id` | A foreign key to `categories`, from the name |
|
|
111
|
+
| `owner_id:foreign(users):cascade` | A foreign key to `users`, deleted with the user |
|
|
112
|
+
|
|
113
|
+
Field names are snake_case. `key`, `save`, `fill`, `delete`, `restore` and
|
|
114
|
+
`related` can't be used: they are `Model` methods.
|
|
115
|
+
|
|
116
|
+
### Types
|
|
117
|
+
|
|
118
|
+
| Type | Column |
|
|
119
|
+
|---|---|
|
|
120
|
+
| `string(n)` | `VARCHAR(n)`, 255 by default |
|
|
121
|
+
| `text` | Long text |
|
|
122
|
+
| `integer` / `int`, `bigInteger` / `bigint` | Integers |
|
|
123
|
+
| `decimal(p,s)` | Exact number, `(8,2)` by default |
|
|
124
|
+
| `money` | `decimal(12,2)` |
|
|
125
|
+
| `percent` | `decimal(5,2)` |
|
|
126
|
+
| `float`, `double` | Floating point |
|
|
127
|
+
| `boolean` / `bool` | Boolean |
|
|
128
|
+
| `date`, `datetime`, `timestamp`, `time` | Dates and times |
|
|
129
|
+
| `json` | JSON (`JSONB` on PostgreSQL) |
|
|
130
|
+
| `uuid` | UUID |
|
|
131
|
+
| `email` | `string(255)` |
|
|
132
|
+
| `phone` | `string(32)` |
|
|
133
|
+
| `url` | `string(2048)` |
|
|
134
|
+
| `foreign(table)` / `foreignId` | Integer foreign key with its constraint |
|
|
135
|
+
|
|
136
|
+
### Modifiers
|
|
137
|
+
|
|
138
|
+
| Modifier | Effect |
|
|
139
|
+
|---|---|
|
|
140
|
+
| `nullable` (or `?` after the name) | Allow NULL |
|
|
141
|
+
| `unique` | Unique index |
|
|
142
|
+
| `index` | Index |
|
|
143
|
+
| `default(value)` | Default value: a number, `true` / `false`, or text |
|
|
144
|
+
| `in(a\|b\|c)` | Allowed values. `status` defaults to the first one unless `default()` is given |
|
|
145
|
+
| `cascade` | Foreign key: delete the row with the referenced row |
|
|
146
|
+
| `nullOnDelete` | Foreign key: set it to NULL (makes it nullable) |
|
|
147
|
+
| `restrict` | Foreign key: refuse to delete the referenced row |
|
|
148
|
+
|
|
149
|
+
### SQL Server
|
|
150
|
+
|
|
151
|
+
SQL Server refuses a foreign key whose `ON DELETE` action (`CASCADE` or
|
|
152
|
+
`SET NULL`) would form a cycle, including a table that references itself,
|
|
153
|
+
or a second cascade path between two tables. When the project's database is
|
|
154
|
+
SQL Server (from `megh.database`, `DB_DIALECT` or the `DATABASE_URL` scheme),
|
|
155
|
+
the generated migrations account for the foreign keys already in your
|
|
156
|
+
migrations: `CASCADE` is kept first, and a foreign key that would break the
|
|
157
|
+
rule gets no `ON DELETE` action, with a comment in the migration and a line
|
|
158
|
+
in the output:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
table.foreignId("parent_id").nullable().constrained("categories"); // no ON DELETE action: SQL Server allows one cascade path between tables
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Deleting the referenced row then fails while rows point to it; clear or
|
|
165
|
+
reassign them first. `restrict` is written as `onDelete("no action")`, since
|
|
166
|
+
SQL Server has no `RESTRICT`. Other databases get the actions as given.
|
|
167
|
+
|
|
168
|
+
Allowed values are written as a comment next to the column; the
|
|
169
|
+
generated DTO doesn't check them. Add `@IsIn([...])` to the DTO to
|
|
170
|
+
validate them.
|
|
171
|
+
|
|
172
|
+
### Presets
|
|
173
|
+
|
|
174
|
+
A bare name that isn't a type picks a preset, the columns shared across
|
|
175
|
+
models. Add modifiers to change one (`email:unique`, `price?`).
|
|
176
|
+
|
|
177
|
+
| Group | Presets |
|
|
178
|
+
|---|---|
|
|
179
|
+
| 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) |
|
|
180
|
+
| Contact | `email`, `phone`, `mobile`, `website`, `url`, `image`, `avatar`, `logo` |
|
|
181
|
+
| Auth | `password`, `remember_token`, `email_verified_at`, `last_login_at` |
|
|
182
|
+
| State | `status` (default `active`, indexed), `type` (indexed), `priority` (`low` … `urgent`), `is_active` (default true), `is_featured`, `sort_order`, `color`, `rating` |
|
|
183
|
+
| Money and quantities | `price`, `cost`, `amount`, `subtotal`, `discount`, `tax`, `total`, `balance` (all `money`), `tax_rate`, `currency` (default `USD`), `quantity`, `stock`, `weight` |
|
|
184
|
+
| People | `gender`, `date_of_birth`, `national_id` |
|
|
185
|
+
| Dates | `date`, `due_date`, `starts_at`, `ends_at`, `published_at`, `paid_at` |
|
|
186
|
+
| Other | `uuid`, `ip_address`, `metadata`, `settings` (json) |
|
|
187
|
+
| Column groups | `address` (`address_line1`, `address_line2`, `city`, `state`, `postal_code`, `country`), `geo` (`latitude`, `longitude`), `person` (`first_name`, `last_name`) |
|
|
188
|
+
|
|
189
|
+
Optional-sounding presets (`description`, `phone`, `image`, dates such as
|
|
190
|
+
`due_date`, …) are nullable. A name ending in `_id` without a type is a
|
|
191
|
+
foreign key.
|
|
192
|
+
|
|
193
|
+
## Your Own Templates
|
|
194
|
+
|
|
195
|
+
Put templates in `.megh/templates/<domain>.json`, one file per domain:
|
|
196
|
+
|
|
197
|
+
```json [.megh/templates/helpdesk.json]
|
|
198
|
+
{
|
|
199
|
+
"title": "Helpdesk",
|
|
200
|
+
"description": "Support tickets",
|
|
201
|
+
"templates": [
|
|
202
|
+
{
|
|
203
|
+
"name": "ticket",
|
|
204
|
+
"description": "A support request",
|
|
205
|
+
"fields": ["user_id:cascade", "title", "body", "priority", "status:in(open|pending|closed)"],
|
|
206
|
+
"softDeletes": true
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
"name": "ticket_tag",
|
|
210
|
+
"fields": ["ticket_id:cascade", "tag_id:cascade"],
|
|
211
|
+
"pivot": true
|
|
212
|
+
}
|
|
213
|
+
]
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
```sh
|
|
218
|
+
npx megh make:resource Ticket --template helpdesk/ticket
|
|
219
|
+
npx megh sc:domain helpdesk
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
| Key | Description |
|
|
223
|
+
|---|---|
|
|
224
|
+
| `domain` | Domain name (default: the file name) |
|
|
225
|
+
| `title`, `description` | Shown by `template:list` and the prompts |
|
|
226
|
+
| `templates[].name` | snake_case singular name |
|
|
227
|
+
| `templates[].fields` | Field specs, as for `--fields` |
|
|
228
|
+
| `templates[].table` | Table name (default: the plural name) |
|
|
229
|
+
| `templates[].timestamps` | `created_at` / `updated_at` (default `true`; `false` for a join table) |
|
|
230
|
+
| `templates[].softDeletes` | `deleted_at` (default `false`) |
|
|
231
|
+
| `templates[].pivot` | A join table: no `id`, the first two foreign keys are the primary key, and no model is generated |
|
|
232
|
+
| `templates[].unique` | Composite unique keys, e.g. `[["customer_id", "product_id"]]` |
|
|
233
|
+
|
|
234
|
+
A file named after a built-in domain adds templates to it, and a template
|
|
235
|
+
with the same name as a built-in one replaces it.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Authentication
|
|
3
|
+
description: Identifying callers and protecting routes.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Authentication
|
|
7
|
+
|
|
8
|
+
Megh splits access control into two steps:
|
|
9
|
+
|
|
10
|
+
- **Authentication** works out *who* the caller is and sets `request.user`.
|
|
11
|
+
- **Authorization** decides whether that caller may use a route marked
|
|
12
|
+
`@Authorized`.
|
|
13
|
+
|
|
14
|
+
## Authentication
|
|
15
|
+
|
|
16
|
+
Extend `MeghAuthentication` and return the user, or `null` for an anonymous
|
|
17
|
+
request. Whatever you return becomes `request.user`:
|
|
18
|
+
|
|
19
|
+
```ts [auth/jwt.authentication.ts]
|
|
20
|
+
import { MeghAuthentication, AppService, IRequest } from '@meghjs/core';
|
|
21
|
+
|
|
22
|
+
@AppService
|
|
23
|
+
export class JwtAuthentication extends MeghAuthentication<User> {
|
|
24
|
+
async authenticate(request: IRequest) {
|
|
25
|
+
const header = request.headers.authorization;
|
|
26
|
+
if (!header?.startsWith('Bearer ')) return null;
|
|
27
|
+
return verifyToken(header.slice(7));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Register it once:
|
|
33
|
+
|
|
34
|
+
```ts [app.ts]
|
|
35
|
+
app.useAuthentication(JwtAuthentication);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Read the user in a handler with `@AuthUser()`:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
@ApiController('/me')
|
|
42
|
+
export class MeController {
|
|
43
|
+
@Get()
|
|
44
|
+
whoami(@AuthUser() user: User) {
|
|
45
|
+
return user;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Authentication never rejects a request by itself. Use authorization for that.
|
|
51
|
+
|
|
52
|
+
## Authorization
|
|
53
|
+
|
|
54
|
+
Authorization is **deny-by-default**. Write a class with an `authorize` method
|
|
55
|
+
and mark it `@CanAuthorize`:
|
|
56
|
+
|
|
57
|
+
```ts [auth/jwt.authorization.ts]
|
|
58
|
+
import { CanAuthorize, IRequest, HttpExceptions } from '@meghjs/core';
|
|
59
|
+
|
|
60
|
+
@CanAuthorize
|
|
61
|
+
export class JwtAuthorization {
|
|
62
|
+
async authorize(req: IRequest, options?: { roles?: string[] }) {
|
|
63
|
+
if (!req.user) throw HttpExceptions.unauthorized('Login required'); // 401
|
|
64
|
+
if (options?.roles && !options.roles.includes(req.user.role)) {
|
|
65
|
+
return false; // 403
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
| `authorize` result | Response |
|
|
72
|
+
|--------------------|----------|
|
|
73
|
+
| returns `false` | 403 |
|
|
74
|
+
| throws an `HttpExceptions` error | that error's status |
|
|
75
|
+
| returns anything else (including nothing) | request continues |
|
|
76
|
+
|
|
77
|
+
Register it:
|
|
78
|
+
|
|
79
|
+
```ts [app.ts]
|
|
80
|
+
app.useAuthorization(JwtAuthorization);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Protecting routes
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
// every route in the controller
|
|
87
|
+
@Authorized()
|
|
88
|
+
@ApiController('/admin')
|
|
89
|
+
export class AdminController {
|
|
90
|
+
@Get()
|
|
91
|
+
dashboard(@AuthUser() user: User) {
|
|
92
|
+
return user;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// one route, with options passed to authorize()
|
|
97
|
+
@ApiController('/reports')
|
|
98
|
+
export class ReportsController {
|
|
99
|
+
@Authorized({ roles: ['admin'] })
|
|
100
|
+
@Get('/stats')
|
|
101
|
+
stats() {}
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
::: warning
|
|
106
|
+
If no authorizer is registered, Megh logs a warning at boot and every
|
|
107
|
+
`@Authorized` route answers **403**.
|
|
108
|
+
:::
|
|
109
|
+
|
|
110
|
+
### Multiple strategies
|
|
111
|
+
|
|
112
|
+
Register several authorizers by name and choose one per route:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
app.useAuthorization({ jwt: JwtAuthorization, apiKey: ApiKeyAuthorization });
|
|
116
|
+
|
|
117
|
+
@Authorized('apiKey') // by name
|
|
118
|
+
@Authorized({ name: 'jwt', roles: ['admin'] }) // by name, with options
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`@Authorized()` with no name uses the first registered handler. Naming a
|
|
122
|
+
handler that is not registered makes `app.run()` fail at boot.
|
|
123
|
+
|
|
124
|
+
### Deny by default
|
|
125
|
+
|
|
126
|
+
A route without `@Authorized` is public, so forgetting it on one handler
|
|
127
|
+
leaves that endpoint open. To flip this, set a default with
|
|
128
|
+
`useAuthorization`, and mark the routes that stay open with `@Public()`:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
app.useAuthentication(JwtAuthentication);
|
|
132
|
+
app.useAuthorization(JwtAuthorization, { default: 'authenticated' });
|
|
133
|
+
|
|
134
|
+
@Public()
|
|
135
|
+
@ApiController('/auth')
|
|
136
|
+
export class AuthController {
|
|
137
|
+
@Post('/login')
|
|
138
|
+
login() {}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
app.mapGet('/status', () => ({ ok: true })).public();
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
| `default` | Every route without `@Authorized` or `@Public` needs |
|
|
145
|
+
|---|---|
|
|
146
|
+
| `'authenticated'` | A user from `useAuthentication()`, else **401** |
|
|
147
|
+
| `true` | The default authorizer, like a bare `@Authorized()` |
|
|
148
|
+
| `'jwt'`, `{ name: 'jwt', roles: ['user'] }` | That authorizer and options, like `@Authorized('jwt')` |
|
|
149
|
+
|
|
150
|
+
- An explicit `@Authorized` on a route or its controller always wins over the
|
|
151
|
+
default, and over `@Public`. A route marked with both logs a warning at boot.
|
|
152
|
+
- `@Public()` works on a controller or a route. Inline routes use `.public()`.
|
|
153
|
+
- Health probes (`useHealth()`), the OpenAPI UI and static files aren't routes
|
|
154
|
+
Megh authorizes, so they stay public.
|
|
155
|
+
- The default is off unless you set it. `megh route:list` shows each route as
|
|
156
|
+
`authorized`, `public` or `default` (protected only when a default is set).
|
|
157
|
+
|
|
158
|
+
## Order of checks
|
|
159
|
+
|
|
160
|
+
Middleware runs first (global, then `@UseMiddleware`), then authentication,
|
|
161
|
+
then the class and method `@Authorized` checks, then validation. See
|
|
162
|
+
[Middleware](/core-concept/middleware#pipeline-order).
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Configuration and Environment
|
|
3
|
+
description: Reading environment variables, loading .env, and typed config classes with @AppConfig and GetConfig.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Configuration and Environment
|
|
7
|
+
|
|
8
|
+
Megh reads settings from environment variables and a `.env` file. Read them
|
|
9
|
+
directly with `Environment`, or group them into typed config classes.
|
|
10
|
+
|
|
11
|
+
## The `.env` file
|
|
12
|
+
|
|
13
|
+
Megh loads `.env` from the current working directory (`process.cwd()`) into
|
|
14
|
+
`process.env` when `@meghjs/core` is first imported. Module-level code can
|
|
15
|
+
read `process.env` straight away.
|
|
16
|
+
|
|
17
|
+
```sh [.env]
|
|
18
|
+
PORT=4000
|
|
19
|
+
MAIL_HOST=smtp.example.com
|
|
20
|
+
MAIL_PORT=587
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
- Only `.env` is read. There is no `.env.local` or `.env.production`.
|
|
24
|
+
- A missing `.env` is fine. Nothing is loaded and no error is raised.
|
|
25
|
+
- Real environment variables win. A variable already set in the shell, in
|
|
26
|
+
Docker or by your host is never overwritten by `.env`.
|
|
27
|
+
- Run the app from the project root, or the file won't be found.
|
|
28
|
+
|
|
29
|
+
### `MEGH_DOTENV`
|
|
30
|
+
|
|
31
|
+
Set `MEGH_DOTENV=false` to stop Megh loading `.env` into `process.env`, for
|
|
32
|
+
example when your platform injects the environment itself:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
MEGH_DOTENV=false node dist/serve.js
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
It is checked before `.env` is read, so set it in the real environment, not in
|
|
39
|
+
`.env`.
|
|
40
|
+
|
|
41
|
+
With `MEGH_DOTENV=false`, `Environment` doesn't read `.env` either: `get()`,
|
|
42
|
+
`getOrThrow()` and `getAll()` only see `process.env`. It is checked on every
|
|
43
|
+
read.
|
|
44
|
+
|
|
45
|
+
## `Environment`
|
|
46
|
+
|
|
47
|
+
`Environment` is an injectable service for reading variables:
|
|
48
|
+
|
|
49
|
+
```ts [src/services/mailer.service.ts]
|
|
50
|
+
import { AppService, Environment, inject } from '@meghjs/core';
|
|
51
|
+
|
|
52
|
+
@AppService
|
|
53
|
+
export class MailerService {
|
|
54
|
+
private readonly env = inject(Environment);
|
|
55
|
+
|
|
56
|
+
host() {
|
|
57
|
+
return this.env.get<string>('MAIL_HOST') ?? 'localhost';
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
| Method | Returns |
|
|
63
|
+
|--------|---------|
|
|
64
|
+
| `get<T>(key)` | The value, or `undefined` when it isn't set |
|
|
65
|
+
| `getOrThrow<T>(key)` | The value. Throws `EnvironmentVariableNotFound` (`"<KEY> not found in environment variables."`, with the name in `error.key`) when it isn't set |
|
|
66
|
+
| `getAll<T>()` | Every variable, `.env` merged with `process.env` |
|
|
67
|
+
| `Environment.reload()` | Static. Forget the cached `.env` so the next read loads it again |
|
|
68
|
+
|
|
69
|
+
Values from `process.env` take precedence over the `.env` file in all three
|
|
70
|
+
methods.
|
|
71
|
+
|
|
72
|
+
::: tip Values are strings
|
|
73
|
+
The type parameter is only a cast. `env.get<number>('PORT')` still returns the
|
|
74
|
+
string `"4000"`. Convert it yourself: `Number(env.get('PORT'))`.
|
|
75
|
+
:::
|
|
76
|
+
|
|
77
|
+
`getOrThrow` treats an empty value (`KEY=`) as set and returns `""`.
|
|
78
|
+
|
|
79
|
+
### Caching
|
|
80
|
+
|
|
81
|
+
`Environment` parses `.env` once and keeps the result. `process.env` is read on
|
|
82
|
+
every call, so changes to it at runtime show up straight away. Edits to the
|
|
83
|
+
`.env` file do not, until you call `Environment.reload()` or restart.
|
|
84
|
+
|
|
85
|
+
If `.env` exists but can't be read, the error is logged and `Environment`
|
|
86
|
+
returns only the `process.env` values until `Environment.reload()`.
|
|
87
|
+
|
|
88
|
+
### Outside classes
|
|
89
|
+
|
|
90
|
+
`inject()` works anywhere, for example in the startup script:
|
|
91
|
+
|
|
92
|
+
```ts [src/serve.ts]
|
|
93
|
+
import { Environment, inject } from '@meghjs/core';
|
|
94
|
+
import app from './app';
|
|
95
|
+
|
|
96
|
+
async function serve() {
|
|
97
|
+
const env = inject(Environment);
|
|
98
|
+
if (env.get('MAINTENANCE') === 'true') return;
|
|
99
|
+
await app.run();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
serve();
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Config classes
|
|
106
|
+
|
|
107
|
+
A config class turns variables into one typed settings object. Extend
|
|
108
|
+
`MeghConfig<T>`, implement `config(env)`, and mark the class with
|
|
109
|
+
`@AppConfig`:
|
|
110
|
+
|
|
111
|
+
```ts [src/config/mail.config.ts]
|
|
112
|
+
import { AppConfig, Environment, MeghConfig } from '@meghjs/core';
|
|
113
|
+
|
|
114
|
+
export type MailSettings = {
|
|
115
|
+
host: string;
|
|
116
|
+
port: number;
|
|
117
|
+
secure: boolean;
|
|
118
|
+
from: string;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
@AppConfig
|
|
122
|
+
export class MailConfig extends MeghConfig<MailSettings> {
|
|
123
|
+
config(env: Environment): MailSettings {
|
|
124
|
+
return {
|
|
125
|
+
host: env.get('MAIL_HOST') ?? 'localhost',
|
|
126
|
+
port: Number(env.get('MAIL_PORT')) || 1025,
|
|
127
|
+
secure: env.get('MAIL_SECURE') === 'true',
|
|
128
|
+
from: env.getOrThrow('MAIL_FROM'),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`npx megh make:config mail` generates this file for you.
|
|
135
|
+
|
|
136
|
+
`@AppConfig` registers the class with [dependency injection](/core-concept/dependency-injection).
|
|
137
|
+
It takes no arguments, so write `@AppConfig`, not `@AppConfig()`.
|
|
138
|
+
|
|
139
|
+
### Reading a config with `GetConfig`
|
|
140
|
+
|
|
141
|
+
`GetConfig(ConfigClass)` returns the object built by `config()`, typed from the
|
|
142
|
+
class:
|
|
143
|
+
|
|
144
|
+
```ts [src/services/mailer.service.ts]
|
|
145
|
+
import { AppService, GetConfig } from '@meghjs/core';
|
|
146
|
+
import { MailConfig } from '../config/mail.config';
|
|
147
|
+
|
|
148
|
+
@AppService
|
|
149
|
+
export class MailerService {
|
|
150
|
+
private readonly mail = GetConfig(MailConfig); // MailSettings
|
|
151
|
+
|
|
152
|
+
connect() {
|
|
153
|
+
return createTransport({ host: this.mail.host, port: this.mail.port });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
`config()` runs on the first `GetConfig` call and the result is cached, so
|
|
159
|
+
later calls return the same object. `Environment.reload()` clears the cache,
|
|
160
|
+
and the next `GetConfig` call runs `config()` again.
|
|
161
|
+
|
|
162
|
+
If the class isn't registered, `GetConfig` throws
|
|
163
|
+
`Config class "MailConfig" is not registered. Did you forget to apply the @AppConfig decorator?`.
|
|
164
|
+
|
|
165
|
+
An error thrown inside `config()`, for example `EnvironmentVariableNotFound`
|
|
166
|
+
from `getOrThrow`, reaches you as it is.
|
|
167
|
+
|
|
168
|
+
### Validating at boot
|
|
169
|
+
|
|
170
|
+
Describe the environment as a DTO class, with the same validation
|
|
171
|
+
decorators as request DTOs, and let the app check it when it starts:
|
|
172
|
+
|
|
173
|
+
```ts [src/config/env.ts]
|
|
174
|
+
import { IsIn, IsInt, IsString, Min } from '@meghjs/core';
|
|
175
|
+
|
|
176
|
+
export class Env {
|
|
177
|
+
@IsInt()
|
|
178
|
+
@Min(1)
|
|
179
|
+
PORT: number;
|
|
180
|
+
|
|
181
|
+
@IsString()
|
|
182
|
+
DATABASE_URL: string;
|
|
183
|
+
|
|
184
|
+
@IsIn(['development', 'production', 'test'])
|
|
185
|
+
NODE_ENV: string;
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
```ts [src/app.ts]
|
|
190
|
+
app.useEnvSchema(Env);
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
`run()` then fails before anything starts, listing every problem:
|
|
194
|
+
|
|
195
|
+
```txt
|
|
196
|
+
ConfigValidationError: [Megh] Invalid environment:
|
|
197
|
+
PORT: PORT must not be less than 1
|
|
198
|
+
DATABASE_URL: DATABASE_URL must be a string
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Only the variables the DTO declares are checked. Properties typed `number`
|
|
202
|
+
or `boolean` are converted first (`"4000"` → `4000`, `"true"`/`"1"` →
|
|
203
|
+
`true`). `validateEnv(Env)` does the same anywhere and returns the converted
|
|
204
|
+
values.
|
|
205
|
+
|
|
206
|
+
A config class can declare the shape of what `config()` returns:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
@AppConfig({ schema: MailSettingsDto })
|
|
210
|
+
export class MailConfig extends MeghConfig<MailSettings> { ... }
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The result is checked on the first `GetConfig(MailConfig)` and, for every
|
|
214
|
+
class with a schema, when the app starts. Properties the schema doesn't
|
|
215
|
+
declare are not checked. Both throw `ConfigValidationError`, whose `issues`
|
|
216
|
+
list each failing property.
|
|
217
|
+
|
|
218
|
+
### Reading a token
|
|
219
|
+
|
|
220
|
+
`GetConfig` also accepts a token or string name and returns whatever is
|
|
221
|
+
registered for it in the container:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
import { GetConfig, MeghContainer } from '@meghjs/core';
|
|
225
|
+
|
|
226
|
+
MeghContainer.set('FEATURE_FLAGS', { newCheckout: true });
|
|
227
|
+
|
|
228
|
+
const flags = GetConfig<{ newCheckout: boolean }>('FEATURE_FLAGS');
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
It throws `Config token "FEATURE_FLAGS" is not registered in the container.`
|
|
232
|
+
when nothing is set.
|
|
233
|
+
|
|
234
|
+
### Passing a config class to the app
|
|
235
|
+
|
|
236
|
+
Some `use*` methods take a config class in place of options and call
|
|
237
|
+
`config()` for you:
|
|
238
|
+
|
|
239
|
+
```ts [src/app.ts]
|
|
240
|
+
import { Megh } from '@meghjs/core';
|
|
241
|
+
import { OpenApiConfig } from './config/openapi.config';
|
|
242
|
+
import { DatabaseConfig } from './config/database.config';
|
|
243
|
+
|
|
244
|
+
const app = Megh.createApplication();
|
|
245
|
+
|
|
246
|
+
app.useMeghORM(DatabaseConfig); // MeghConfig<DatabaseOptions>
|
|
247
|
+
app.useOpenApi(OpenApiConfig); // MeghConfig<OpenApiUiOptions>
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
`useMeghORM` only recognises a class that extends `MeghConfig`, so always
|
|
251
|
+
extend it. The config is read once, when the method is called.
|
|
252
|
+
|
|
253
|
+
## Summary
|
|
254
|
+
|
|
255
|
+
| API | Use |
|
|
256
|
+
|-----|-----|
|
|
257
|
+
| `Environment` | Injectable service: `get`, `getOrThrow`, `getAll`, `Environment.reload()` |
|
|
258
|
+
| `EnvironmentVariableNotFound` | Error thrown by `getOrThrow()`; check it with `instanceof` |
|
|
259
|
+
| `MeghConfig<T>` | Base class for config classes. Implement `config(env): T` |
|
|
260
|
+
| `@AppConfig` | Registers a config class for injection |
|
|
261
|
+
| `GetConfig(ConfigClass)` | Builds and returns the typed settings |
|
|
262
|
+
| `GetConfig(token)` | Returns the value registered for a token or string |
|
|
263
|
+
| `MEGH_DOTENV=false` | Don't read `.env` at all: only `process.env` is used |
|
|
264
|
+
|
|
265
|
+
See also [Application](/getting-started/application) for `NODE_ENV`, `HOST`
|
|
266
|
+
and other variables the app reads, and
|
|
267
|
+
[Deployment](/production/deployment) for setting the environment in
|
|
268
|
+
production.
|