@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,605 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Generators
|
|
3
|
+
description: Generating resources, controllers, services, models, classes, middleware, config classes and their unit tests with the Megh CLI.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Generators
|
|
7
|
+
|
|
8
|
+
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.
|
|
9
|
+
|
|
10
|
+
## Folders
|
|
11
|
+
|
|
12
|
+
A plain name goes in the folder for its type. A name with a folder in front
|
|
13
|
+
is a module: the module folder comes first, then the type folder.
|
|
14
|
+
|
|
15
|
+
| Command | Writes |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `make:model user` | `src/models/user.model.ts` |
|
|
18
|
+
| `make:model users/user` | `src/users/models/user.model.ts` |
|
|
19
|
+
| `make:controller users/user` | `src/users/controllers/user.controller.ts` |
|
|
20
|
+
| `make:service users/user` | `src/users/services/user.service.ts` |
|
|
21
|
+
| `make:resource users/user` | `src/users/{models,dtos,services,controllers}/user.*.ts` |
|
|
22
|
+
|
|
23
|
+
`--root <dir>` replaces the type folder: `make:model users/user --root domain`
|
|
24
|
+
writes `src/users/domain/user.model.ts`.
|
|
25
|
+
|
|
26
|
+
`useControllers({ auto: true })` finds controllers in every `controllers/`
|
|
27
|
+
folder under `src/`, so module controllers are registered too.
|
|
28
|
+
|
|
29
|
+
::: info Before 0.6.3
|
|
30
|
+
Nested names wrote `src/models/users/user.model.ts`. Files already there keep
|
|
31
|
+
working: `make:resource`, `make:factory` and `sync:model` look there when
|
|
32
|
+
the new location has no file.
|
|
33
|
+
:::
|
|
34
|
+
|
|
35
|
+
## Reviewing changes
|
|
36
|
+
|
|
37
|
+
A generator that would change a file that already exists (with `-f`, or
|
|
38
|
+
`sync:model`) shows what it is about to do and asks first:
|
|
39
|
+
|
|
40
|
+
```txt
|
|
41
|
+
Changes
|
|
42
|
+
~ changed src/blog/models/post.model.ts
|
|
43
|
+
|
|
44
|
+
src/blog/models/post.model.ts
|
|
45
|
+
title!: string;
|
|
46
|
+
|
|
47
|
+
- @Column({ nullable: true, type: "text" })
|
|
48
|
+
- body!: string | null;
|
|
49
|
+
|
|
50
|
+
@Column()
|
|
51
|
+
Can affect:
|
|
52
|
+
src/blog/services/post.service.ts imports it
|
|
53
|
+
line 5 uses .body, which is removed
|
|
54
|
+
|
|
55
|
+
? Apply these changes to 1 existing file? (y/N)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- **Changes** lists new files (`+ new`) and changed ones (`~ changed`), with a
|
|
59
|
+
diff of each changed file.
|
|
60
|
+
- **Can affect** lists the files that import a changed file, and the lines
|
|
61
|
+
that use a property or method the change removes or retypes.
|
|
62
|
+
- Answering no puts everything back, including the new files the command
|
|
63
|
+
made along the way.
|
|
64
|
+
|
|
65
|
+
A command that only creates new files doesn't ask. `-y` / `--yes` applies
|
|
66
|
+
without asking; so does running outside a terminal (scripts and CI), which
|
|
67
|
+
still prints the review.
|
|
68
|
+
|
|
69
|
+
## Resource
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
npx megh make:resource user
|
|
73
|
+
# shorthand
|
|
74
|
+
npx megh m:r user
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Generates a complete REST resource for a [Megh ORM](/advanced/orm) model:
|
|
78
|
+
|
|
79
|
+
| File | Contents |
|
|
80
|
+
|------|----------|
|
|
81
|
+
| `src/models/user.model.ts` | Reused if it exists; otherwise built from the migration that creates `users` (as `make:model` does) |
|
|
82
|
+
| `src/dtos/user.dto.ts` | `CreateUserDto`, `UpdateUserDto` (every field optional) and `ListUsersQuery` (`page`, `perPage`) |
|
|
83
|
+
| `src/services/user.service.ts` | `findAll`, `paginate`, `find`, `findOrFail`, `create`, `update`, `delete` |
|
|
84
|
+
| `src/controllers/user.controller.ts` | `GET /users`, `GET /users/:id`, `POST /users`, `PUT /users/:id`, `DELETE /users/:id` |
|
|
85
|
+
| `src/services/user.service.spec.ts` | A test for each service method, with the model's queries replaced by spies |
|
|
86
|
+
| `src/controllers/user.controller.spec.ts` | A test for each route, with a stand-in service |
|
|
87
|
+
|
|
88
|
+
The DTO validators come from the model's fields and the migration's column
|
|
89
|
+
types: `varchar(255)` gets `@MaxLength(255)`, an `email` column `@IsEmail()`,
|
|
90
|
+
nullable columns and columns with a default are optional, and the generated
|
|
91
|
+
primary key and timestamps are left out. A missing row gives a 404.
|
|
92
|
+
|
|
93
|
+
If there is neither a model nor a migration for the table, nothing is
|
|
94
|
+
written; create the migration first (`megh make:migration create_users_table`).
|
|
95
|
+
Use `--table <name>` when the table name isn't the plural snake_case name, and
|
|
96
|
+
`-f` to overwrite existing DTO, service and controller files. Nested names
|
|
97
|
+
work too: `megh m:r admin/user` writes to `src/admin/` and serves
|
|
98
|
+
`/admin/users`. See [Folders](#folders).
|
|
99
|
+
|
|
100
|
+
If the model is a [TypeORM](/advanced/database) entity instead, the service
|
|
101
|
+
uses its repository and no DTOs are generated. A model that is a plain class
|
|
102
|
+
(`make:model` without `--orm`) has no table, so the command stops and says to
|
|
103
|
+
regenerate it with `make:model user --orm --force`.
|
|
104
|
+
|
|
105
|
+
Register the controller in your app:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
app.useControllers([UserController]);
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Controller
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
npx megh make:controller user
|
|
115
|
+
# shorthand
|
|
116
|
+
npx megh m:c user
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Pass `-r` for a full REST skeleton, and `-m <model>` to bind it to a model:
|
|
120
|
+
|
|
121
|
+
```sh
|
|
122
|
+
npx megh m:c user -m user -r
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
With `-m`, the controller is generated like [`make:resource`](#resource): the model's
|
|
126
|
+
DTOs, service and model (from its migration) are created if missing, and the
|
|
127
|
+
controller delegates to the service, which queries the [MeghORM](/advanced/orm)
|
|
128
|
+
model (`--orm` says so explicitly). To use a [TypeORM](/advanced/database)
|
|
129
|
+
repository instead, add `--typeorm`.
|
|
130
|
+
|
|
131
|
+
Use `-rt <dir>` to place the file under a different directory, and `--base-path`
|
|
132
|
+
to emit `@ApiController` without a route prefix.
|
|
133
|
+
|
|
134
|
+
## Service
|
|
135
|
+
|
|
136
|
+
```sh
|
|
137
|
+
npx megh make:service user
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
A resource service uses the [Megh ORM](/advanced/orm) model (generated from its
|
|
141
|
+
migration if it doesn't exist yet):
|
|
142
|
+
|
|
143
|
+
```sh
|
|
144
|
+
npx megh make:service user -m user -r
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
To use a [TypeORM](/advanced/database) repository instead, add `--typeorm`:
|
|
148
|
+
|
|
149
|
+
```sh
|
|
150
|
+
npx megh make:service user -m user -r --typeorm
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## Model
|
|
154
|
+
|
|
155
|
+
```sh
|
|
156
|
+
# Plain class
|
|
157
|
+
npx megh make:model user
|
|
158
|
+
|
|
159
|
+
# Megh ORM model
|
|
160
|
+
npx megh make:model user --orm
|
|
161
|
+
npx megh make:model user --orm --table app_users # table name other than "users"
|
|
162
|
+
|
|
163
|
+
# TypeORM entity (with @meghjs/data)
|
|
164
|
+
npx megh m:m user --typeorm
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Without a flag, `make:model` writes a plain class, not mapped to a table:
|
|
168
|
+
|
|
169
|
+
```ts [src/models/user.model.ts]
|
|
170
|
+
export class User {
|
|
171
|
+
// Add the fields a User has, e.g.
|
|
172
|
+
// id!: number;
|
|
173
|
+
// name!: string;
|
|
174
|
+
|
|
175
|
+
constructor(values: Partial<User> = {}) {
|
|
176
|
+
Object.assign(this, values);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
If a migration already creates the table, the command says so and suggests
|
|
182
|
+
`--orm`.
|
|
183
|
+
|
|
184
|
+
::: warning Before 0.6.5
|
|
185
|
+
`make:model user` wrote a Megh ORM model, and `--orm` made a TypeORM entity.
|
|
186
|
+
Now `--orm` means Megh ORM and `--typeorm` means TypeORM, on `make:model`,
|
|
187
|
+
`make:controller` and `make:service`.
|
|
188
|
+
:::
|
|
189
|
+
|
|
190
|
+
With `--orm`, `make:model` writes a [Megh ORM](/advanced/orm) model. It looks for the
|
|
191
|
+
model's table (by default the plural snake_case name: `User` → `users`,
|
|
192
|
+
`BlogPost` → `blog_posts`) in your migrations. If one creates it, the model
|
|
193
|
+
gets a decorated field for every column, with its type, nullability and
|
|
194
|
+
value conversion. The primary key, auto-increment, timestamp and soft-delete
|
|
195
|
+
columns get their own decorators. Later migrations that add, drop or rename
|
|
196
|
+
columns are taken into account:
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
// Columns read from the migrations (the table is created in 20260101000000_create_users_table.ts).
|
|
200
|
+
@Table("users")
|
|
201
|
+
export class User extends Model {
|
|
202
|
+
@PrimaryKey()
|
|
203
|
+
@AutoIncrement()
|
|
204
|
+
id?: number;
|
|
205
|
+
|
|
206
|
+
@Column()
|
|
207
|
+
email!: string;
|
|
208
|
+
|
|
209
|
+
@Column({ nullable: true, type: "string" })
|
|
210
|
+
name!: string | null;
|
|
211
|
+
|
|
212
|
+
@Column({ type: "boolean" })
|
|
213
|
+
is_admin?: boolean;
|
|
214
|
+
|
|
215
|
+
@CreatedAt()
|
|
216
|
+
created_at?: Date;
|
|
217
|
+
|
|
218
|
+
@UpdatedAt()
|
|
219
|
+
updated_at?: Date;
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Columns the database fills in (auto-increment, defaults, timestamps) are
|
|
224
|
+
declared with `?`, so `create()` can leave them out. Nullable columns name
|
|
225
|
+
their type (`type: "string"`), since a `string | null` field's type isn't
|
|
226
|
+
visible at runtime; [OpenAPI](/microservices/openapi#responses) uses it to
|
|
227
|
+
document the model. If no migration creates
|
|
228
|
+
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.
|
|
229
|
+
Relations aren't generated; add them yourself.
|
|
230
|
+
|
|
231
|
+
To write the migration too, start from a template or a list of fields (these
|
|
232
|
+
always build a Megh ORM model, so `--orm` isn't needed); see
|
|
233
|
+
[Templates and Fields](/cli/scaffold/templates):
|
|
234
|
+
|
|
235
|
+
```sh
|
|
236
|
+
npx megh make:model Product --template ecommerce/product
|
|
237
|
+
npx megh make:resource Ticket --fields "title,body,status:in(open|closed),user_id:cascade"
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### Syncing a model
|
|
241
|
+
|
|
242
|
+
After a migration alters the table, bring the model up to date without
|
|
243
|
+
regenerating it:
|
|
244
|
+
|
|
245
|
+
```sh
|
|
246
|
+
npx megh sync:model user
|
|
247
|
+
npx megh s:m user --dry-run # show the review, write nothing
|
|
248
|
+
npx megh s:m user --dto # also rewrite src/dtos/user.dto.ts
|
|
249
|
+
npx megh s:m user --yes # apply without asking
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
It shows the changes and what they affect, and asks before writing (see
|
|
253
|
+
[Reviewing changes](#reviewing-changes)). It was called `update:model` before
|
|
254
|
+
0.6.3; that name (and `u:m`) still works.
|
|
255
|
+
|
|
256
|
+
For a migration such as:
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
await schema.table("users", (table) => {
|
|
260
|
+
table.string("phone", 20).nullable();
|
|
261
|
+
table.dropColumn("age");
|
|
262
|
+
});
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
`sync:model` adds `@Column({ nullable: true, type: "string" }) phone!: string | null;` after the
|
|
266
|
+
model's existing columns, removes the `age` field (with its doc comment), and
|
|
267
|
+
rewrites any field still in the shape `make:model` writes when its type or
|
|
268
|
+
nullability changed. Only column fields are touched: relations, methods,
|
|
269
|
+
getters and comments stay as they are. A field you customized (a `name:`
|
|
270
|
+
mapping, a custom cast, extra options) is kept as written and reported so you
|
|
271
|
+
can check it. A renamed column shows up as one field removed and one added.
|
|
272
|
+
|
|
273
|
+
The model must be a decorated (`@Table`) model; for an older model with
|
|
274
|
+
`static table` and `static casts`, regenerate it with `make:model --orm --force`.
|
|
275
|
+
Without `--dto`, a DTO from `make:resource` is not changed, and the command
|
|
276
|
+
reminds you it may be out of date.
|
|
277
|
+
|
|
278
|
+
## Middleware
|
|
279
|
+
|
|
280
|
+
```sh
|
|
281
|
+
npx megh make:middleware auth
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Generates a class extending `MeghMiddleware`:
|
|
285
|
+
|
|
286
|
+
```ts [src/middlewares/auth.middleware.ts]
|
|
287
|
+
import { AppMiddleware, MeghMiddleware, IRequest, IResponse } from '@meghjs/core';
|
|
288
|
+
|
|
289
|
+
@AppMiddleware
|
|
290
|
+
export class AuthMiddleware extends MeghMiddleware {
|
|
291
|
+
async invoke(req: IRequest, res?: IResponse) {
|
|
292
|
+
// your logic goes here
|
|
293
|
+
return req;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
## Mail
|
|
299
|
+
|
|
300
|
+
```sh
|
|
301
|
+
npx megh make:mail OrderShipped
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Generates a `Mailable` in `src/mail`, with `envelope()`, `content()` and
|
|
305
|
+
`attachments()` to fill in. The `Mail` suffix is added for you, and a name like
|
|
306
|
+
`admin/Invoice` writes to `src/admin/mail/invoice.mail.ts`:
|
|
307
|
+
|
|
308
|
+
```ts [src/mail/order-shipped.mail.ts]
|
|
309
|
+
import { Mailable } from '@meghjs/core';
|
|
310
|
+
|
|
311
|
+
export class OrderShippedMail extends Mailable {
|
|
312
|
+
envelope() {
|
|
313
|
+
return { subject: 'Order Shipped' };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
content() {
|
|
317
|
+
return {
|
|
318
|
+
html: '<p>Order Shipped</p>',
|
|
319
|
+
text: 'Order Shipped',
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
attachments() {
|
|
324
|
+
return [];
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
If `src/app.ts` doesn't call `app.useMail()` yet, the command says so. See
|
|
330
|
+
[Mail](/advanced/mail).
|
|
331
|
+
|
|
332
|
+
## View
|
|
333
|
+
|
|
334
|
+
```sh
|
|
335
|
+
npx megh make:view pages.about # or pages/about
|
|
336
|
+
# shorthand
|
|
337
|
+
npx megh m:v pages.about
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
Writes `views/pages/about.megh.html`, which you render with
|
|
341
|
+
`Results.View('pages.about', data)`. Views live in `views/` at the project
|
|
342
|
+
root, not under `src/`, and no unit test is written. When
|
|
343
|
+
`views/layouts/app.megh.html` exists (as in a `new --mvc` project) the page
|
|
344
|
+
extends it:
|
|
345
|
+
|
|
346
|
+
```html [views/pages/about.megh.html]
|
|
347
|
+
@extends('layouts.app')
|
|
348
|
+
|
|
349
|
+
@section('title', 'About')
|
|
350
|
+
|
|
351
|
+
@section('content')
|
|
352
|
+
<h1>About</h1>
|
|
353
|
+
@endsection
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
| Option | Effect |
|
|
357
|
+
|--------|--------|
|
|
358
|
+
| `-l, --layout <layout>` | Extend another layout, e.g. `layouts.admin` |
|
|
359
|
+
| `--no-layout` | Write a standalone HTML page |
|
|
360
|
+
| `-c, --component` | Write a component in `views/components/`: `make:view forms/input -c` is used as `<x-forms.input>` |
|
|
361
|
+
|
|
362
|
+
If `src/app.ts` doesn't call `app.useViews()` yet, the command says so. See
|
|
363
|
+
[Views](/advanced/views).
|
|
364
|
+
|
|
365
|
+
## Events
|
|
366
|
+
|
|
367
|
+
```sh
|
|
368
|
+
npx megh make:event UserCreated
|
|
369
|
+
npx megh make:listener SendWelcomeEmail --event UserCreated
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
`make:event` writes `src/events/user-created.event.ts`: a `UserCreatedEvent`
|
|
373
|
+
extending `MeghEvent`, with a `UserCreatedPayload` type to fill in.
|
|
374
|
+
|
|
375
|
+
`make:listener` writes `src/listeners/send-welcome-email.listener.ts`: a
|
|
376
|
+
`SendWelcomeEmailListener` typed to the event, marked `@AppService` so it can
|
|
377
|
+
inject services. With `--event` (`-e`), the event is created too if it doesn't
|
|
378
|
+
exist yet; without it, the listener takes any `MeghEvent`.
|
|
379
|
+
|
|
380
|
+
```ts [src/listeners/send-welcome-email.listener.ts]
|
|
381
|
+
import { AppService, MeghEventListener } from '@meghjs/core';
|
|
382
|
+
import { UserCreatedEvent } from '../events/user-created.event';
|
|
383
|
+
|
|
384
|
+
@AppService
|
|
385
|
+
export class SendWelcomeEmailListener extends MeghEventListener<UserCreatedEvent> {
|
|
386
|
+
async handler(event: UserCreatedEvent): Promise<void> {
|
|
387
|
+
// event.payload is the data; event.name and event.timestamp are set for you.
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
Listeners are registered by hand, once at startup. The command prints the line
|
|
393
|
+
to add to `src/app.ts`:
|
|
394
|
+
|
|
395
|
+
```ts
|
|
396
|
+
EventRegistry.getInstance().register(UserCreatedEvent, MeghContainer.get(SendWelcomeEmailListener));
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
See [Events](/advanced/events).
|
|
400
|
+
|
|
401
|
+
## Queues and workers
|
|
402
|
+
|
|
403
|
+
```sh
|
|
404
|
+
npx megh make:queue OrderExport # queue "order-export"
|
|
405
|
+
npx megh make:worker Report --queue reports # consumes "reports"
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
`make:queue` writes `src/queues/order-export.queue.ts`: an `OrderExportQueue`
|
|
409
|
+
that both adds jobs and handles them, with a payload type and one
|
|
410
|
+
`@JobHandler('process')` method. `--queue` (`-q`) sets the queue name in Redis;
|
|
411
|
+
it defaults to the kebab-case name.
|
|
412
|
+
|
|
413
|
+
```ts [src/queues/order-export.queue.ts]
|
|
414
|
+
import { Job, JobHandler, MeghQueue, Queue } from '@meghjs/core';
|
|
415
|
+
|
|
416
|
+
export type OrderExportPayload = {
|
|
417
|
+
id: number; // replace with what the job needs
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
@Queue({ name: 'order-export' })
|
|
421
|
+
export class OrderExportQueue extends MeghQueue<OrderExportPayload> {
|
|
422
|
+
constructor() {
|
|
423
|
+
super();
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
@JobHandler('process')
|
|
427
|
+
async handleProcess(job: Job<OrderExportPayload>) {
|
|
428
|
+
// job.data is the payload
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
`make:worker` writes a `MeghWorkerBase` with `process()`, `onCompleted()` and
|
|
434
|
+
`onFailed()`, for a queue another part of the system fills.
|
|
435
|
+
|
|
436
|
+
Both print `app.useWorker([...])` if `src/app.ts` doesn't register the class,
|
|
437
|
+
and `npm i bullmq ioredis` if the project doesn't depend on BullMQ. Redis
|
|
438
|
+
defaults to `127.0.0.1:6379`; set `MEGH_QUEUE_DRIVER=memory` to run jobs
|
|
439
|
+
without it. See [Queue](/advanced/queue).
|
|
440
|
+
|
|
441
|
+
## Scheduled tasks
|
|
442
|
+
|
|
443
|
+
```sh
|
|
444
|
+
npx megh make:task CleanupTokens # hourly
|
|
445
|
+
npx megh make:task NightlyReport --cron "0 3 * * *" # 03:00 every day
|
|
446
|
+
npx megh make:task PollPayments --interval 30000 # every 30 seconds
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
Writes `src/tasks/cleanup-tokens.task.ts`: a `@ScheduledTask()` class with one
|
|
450
|
+
`@Cron` (or, with `--interval`, `@Interval`) method. `make:scheduler` is an
|
|
451
|
+
alias.
|
|
452
|
+
|
|
453
|
+
```ts [src/tasks/cleanup-tokens.task.ts]
|
|
454
|
+
import { Cron, ScheduledTask } from '@meghjs/core';
|
|
455
|
+
|
|
456
|
+
@ScheduledTask()
|
|
457
|
+
export class CleanupTokensTask {
|
|
458
|
+
@Cron('0 * * * *') // every hour, on the hour
|
|
459
|
+
async run() {
|
|
460
|
+
// your logic goes here
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
`--cron` takes 5 fields, or 6 with seconds first. The command prints
|
|
466
|
+
`app.useScheduler([...])` unless `src/app.ts` already lists the class or scans a
|
|
467
|
+
folder with `useScheduler({ path })`. See [Scheduler](/advanced/scheduler).
|
|
468
|
+
|
|
469
|
+
## Config
|
|
470
|
+
|
|
471
|
+
```sh
|
|
472
|
+
npx megh make:config jwt
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
Generates a class extending `MeghConfig` and registered with `@AppConfig`:
|
|
476
|
+
|
|
477
|
+
```ts [src/config/jwt.config.ts]
|
|
478
|
+
import { AppConfig, MeghConfig, Environment } from '@meghjs/core';
|
|
479
|
+
|
|
480
|
+
@AppConfig
|
|
481
|
+
export class JwtConfig extends MeghConfig {
|
|
482
|
+
config(env: Environment) {
|
|
483
|
+
return {};
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
## DTO
|
|
489
|
+
|
|
490
|
+
```sh
|
|
491
|
+
npx megh make:dto CreatePost
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
Writes `src/dtos/create-post.dto.ts`: a `CreatePostDto` with class-validator
|
|
495
|
+
rules for a `name` and an optional `description`, to replace with your fields.
|
|
496
|
+
Its test checks that a valid body passes and that `name` is required.
|
|
497
|
+
|
|
498
|
+
## Class
|
|
499
|
+
|
|
500
|
+
```sh
|
|
501
|
+
npx megh make:class Money
|
|
502
|
+
# shorthand
|
|
503
|
+
npx megh m:cls billing/Money
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
Writes a plain class (no decorators, nothing to register) in
|
|
507
|
+
`src/classes/money.ts`, or `src/billing/classes/money.ts` for the nested
|
|
508
|
+
name, with a test that creates it. `--root <dir>` picks another folder, e.g.
|
|
509
|
+
`make:class Money --root utils` writes `src/utils/money.ts`.
|
|
510
|
+
|
|
511
|
+
## Tests
|
|
512
|
+
|
|
513
|
+
Every generator except `make:model` and the database ones (`make:migration`,
|
|
514
|
+
`make:seeder`, `make:factory`) writes a [Vitest](/advanced/testing) unit test
|
|
515
|
+
next to the file it creates. The app's `vitest.config.mts` runs every
|
|
516
|
+
`src/**/*.spec.ts`, so `npm test` picks them up:
|
|
517
|
+
|
|
518
|
+
| Command | Also writes |
|
|
519
|
+
|---|---|
|
|
520
|
+
| `make:service user` | `src/services/user.service.spec.ts` |
|
|
521
|
+
| `make:resource user` | `src/services/user.service.spec.ts`, `src/controllers/user.controller.spec.ts` |
|
|
522
|
+
| `make:controller user -m user` | `src/controllers/user.controller.spec.ts` (and the service's, when it creates the service) |
|
|
523
|
+
| `make:class Money` | `src/classes/money.spec.ts` |
|
|
524
|
+
|
|
525
|
+
Each test matches what was generated:
|
|
526
|
+
|
|
527
|
+
- **Resource services** (`make:resource`, `make:service -m`) get a test for
|
|
528
|
+
every method: `findAll`, `paginate`, `find`, `findOrFail`, `create`,
|
|
529
|
+
`update` (it checks that fields sent as `undefined` are skipped) and
|
|
530
|
+
`delete`, including the 404 cases. The model's queries are replaced with
|
|
531
|
+
`vi.spyOn`, so no database is needed. `create` and `update` use sample values
|
|
532
|
+
for the model's columns (`email` gets `user@example.com`, a boolean `true`).
|
|
533
|
+
With `--typeorm`, the repository is a stand-in.
|
|
534
|
+
- **Resource controllers** get a test for every route, with a stand-in
|
|
535
|
+
service passed to `MeghTest.getController`.
|
|
536
|
+
- **Other files** (a basic service or controller, config, middleware, mail,
|
|
537
|
+
event, listener, queue, worker, task, DTO, class) get a test of what the
|
|
538
|
+
template does. Replace it as you write the real code.
|
|
539
|
+
|
|
540
|
+
```ts [src/services/user.service.spec.ts]
|
|
541
|
+
describe('delete', () => {
|
|
542
|
+
it('deletes the user', async () => {
|
|
543
|
+
const existing = row();
|
|
544
|
+
vi.spyOn(User, 'findOrFail').mockResolvedValue(existing as never);
|
|
545
|
+
const remove = vi.spyOn(existing, 'delete').mockResolvedValue();
|
|
546
|
+
|
|
547
|
+
await service.delete(1);
|
|
548
|
+
expect(remove).toHaveBeenCalled();
|
|
549
|
+
});
|
|
550
|
+
});
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
Skip the test with `--notest` (or `-nt`):
|
|
554
|
+
|
|
555
|
+
```sh
|
|
556
|
+
npx megh make:service user -nt
|
|
557
|
+
npx megh make:resource user --notest
|
|
558
|
+
npx megh scaffold:domain ecommerce --resource --notest
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
Running a generator again with `-f` keeps an existing test, unless it is
|
|
562
|
+
overwritten too (the review shows it first).
|
|
563
|
+
|
|
564
|
+
### make:test
|
|
565
|
+
|
|
566
|
+
`make:test` writes the test for a file that already exists, next to it:
|
|
567
|
+
|
|
568
|
+
```sh
|
|
569
|
+
npx megh make:test user.service # src/services/user.service.spec.ts
|
|
570
|
+
npx megh make:test UserController # src/controllers/user.controller.spec.ts
|
|
571
|
+
npx megh make:test user --type service # the same as user.service
|
|
572
|
+
npx megh m:t price-calculator # finds src/**/price-calculator.ts
|
|
573
|
+
npx megh m:t checkout # nothing matches: src/tests/checkout.spec.ts
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
The kind comes from the name (`user.service`, `UserService`) or `--type`
|
|
577
|
+
(`service`, `controller`, `config`, `middleware`, `mail`, `event`, `listener`,
|
|
578
|
+
`queue`, `worker`, `task`, `dto`, `model` or `class`). Without one, it looks
|
|
579
|
+
for a file of that name anywhere under `src/`, and asks you to be more specific
|
|
580
|
+
when several match.
|
|
581
|
+
|
|
582
|
+
A resource service or controller is recognised and gets the full tests above.
|
|
583
|
+
Any other class gets a test that creates it (through the container for
|
|
584
|
+
services, controllers, middleware and the like) and a `it.todo()` for each of
|
|
585
|
+
its public methods:
|
|
586
|
+
|
|
587
|
+
```ts [src/utils/price-calculator.spec.ts]
|
|
588
|
+
import { describe, expect, it } from 'vitest';
|
|
589
|
+
import { PriceCalculator } from './price-calculator';
|
|
590
|
+
|
|
591
|
+
describe('PriceCalculator', () => {
|
|
592
|
+
const priceCalculator = new PriceCalculator();
|
|
593
|
+
|
|
594
|
+
it('should be defined', () => {
|
|
595
|
+
expect(priceCalculator).toBeDefined();
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
it.todo('total()');
|
|
599
|
+
|
|
600
|
+
it.todo('refresh()');
|
|
601
|
+
});
|
|
602
|
+
```
|
|
603
|
+
|
|
604
|
+
A name that matches no file gets a starter spec in `src/tests/`. An existing
|
|
605
|
+
spec is not replaced without `-f`.
|