@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,350 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Controllers
|
|
3
|
+
description: Defining routes with controllers, reading route parameters, building REST controllers and returning errors.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Controllers
|
|
7
|
+
|
|
8
|
+
A controller groups related routes. Mark the class with `@ApiController` and its
|
|
9
|
+
methods with a route decorator — `@Get`, `@Post`, `@Put`, `@Patch`, `@Delete`.
|
|
10
|
+
|
|
11
|
+
## Basic controller
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npx megh make:controller welcome
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```ts [src/controllers/welcome.controller.ts]
|
|
18
|
+
import { ApiController, Get } from '@meghjs/core';
|
|
19
|
+
|
|
20
|
+
@ApiController('/welcome')
|
|
21
|
+
export class WelcomeController {
|
|
22
|
+
@Get()
|
|
23
|
+
sayHello() {
|
|
24
|
+
return 'Hello';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Register it on the app:
|
|
30
|
+
|
|
31
|
+
```ts [app.ts]
|
|
32
|
+
import { Megh } from '@meghjs/core';
|
|
33
|
+
import { WelcomeController } from './controllers/welcome.controller';
|
|
34
|
+
|
|
35
|
+
const app = Megh.createApplication();
|
|
36
|
+
app.useControllers([WelcomeController]);
|
|
37
|
+
|
|
38
|
+
export default app;
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`@ApiController` may be used bare, in which case routes mount at the root:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
@ApiController
|
|
45
|
+
export class WelcomeController {}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Route parameters
|
|
49
|
+
|
|
50
|
+
| Decorator | Reads from |
|
|
51
|
+
|-----------|------------|
|
|
52
|
+
| `@Param('id')` | Route path segment |
|
|
53
|
+
| `@Query()` | Query string |
|
|
54
|
+
| `@Body()` | Request body |
|
|
55
|
+
| `@Header('x-token')` | Request header |
|
|
56
|
+
| `@AuthUser()` | The authenticated user |
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
@Get('/:id')
|
|
60
|
+
findOne(@Param('id') id: number) {
|
|
61
|
+
return { id };
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## REST controller with a built-in collection
|
|
66
|
+
|
|
67
|
+
`Collection` holds items in memory — useful for prototypes and tests, with no
|
|
68
|
+
database required.
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
npx megh make:controller users --model user --rest
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
or shorthand
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
npx megh m:c users -m user -r
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
::: code-group
|
|
81
|
+
```ts [users.controller.ts]
|
|
82
|
+
import {
|
|
83
|
+
ApiController,
|
|
84
|
+
Get,
|
|
85
|
+
Post,
|
|
86
|
+
Put,
|
|
87
|
+
Delete,
|
|
88
|
+
Param,
|
|
89
|
+
Body,
|
|
90
|
+
Collection,
|
|
91
|
+
HttpExceptions,
|
|
92
|
+
} from '@meghjs/core';
|
|
93
|
+
import { User } from '../models/user';
|
|
94
|
+
|
|
95
|
+
@ApiController('/users')
|
|
96
|
+
export class UsersController {
|
|
97
|
+
private readonly users = Collection.from<User>([
|
|
98
|
+
{ id: 1, name: 'test 1', age: 20, active: true },
|
|
99
|
+
{ id: 2, name: 'test 2', age: 45, active: true },
|
|
100
|
+
{ id: 3, name: 'test 3', age: 38, active: false },
|
|
101
|
+
]);
|
|
102
|
+
|
|
103
|
+
@Get()
|
|
104
|
+
findAll() {
|
|
105
|
+
return this.users.find();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
@Get('/:id')
|
|
109
|
+
findOne(@Param('id') id: number) {
|
|
110
|
+
const user = this.users.findOne((u) => u.id === id);
|
|
111
|
+
if (!user) throw HttpExceptions.notFound('User not found');
|
|
112
|
+
return user;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
@Post()
|
|
116
|
+
create(@Body() createBody: Partial<User>) {
|
|
117
|
+
const lastId = this.users.max('id');
|
|
118
|
+
return this.users.add({ ...createBody, id: lastId + 1 });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
@Put('/:id')
|
|
122
|
+
update(@Param('id') id: number, @Body() updateBody: Partial<User>) {
|
|
123
|
+
const user = this.users.findOne((u) => u.id === id);
|
|
124
|
+
if (!user) throw HttpExceptions.notFound('User not found');
|
|
125
|
+
this.users.update((u) => u.id === id, updateBody);
|
|
126
|
+
return 'Updated Successfully';
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
@Delete('/:id')
|
|
130
|
+
delete(@Param('id') id: number) {
|
|
131
|
+
const user = this.users.findOne((u) => u.id === id);
|
|
132
|
+
if (!user) throw HttpExceptions.notFound('User not found');
|
|
133
|
+
this.users.delete((u) => u.id === id);
|
|
134
|
+
return 'Deleted Successfully';
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
```ts [models/user.ts]
|
|
140
|
+
export class User {
|
|
141
|
+
id: number;
|
|
142
|
+
name: string;
|
|
143
|
+
age: number;
|
|
144
|
+
active: boolean;
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
:::
|
|
148
|
+
|
|
149
|
+
`Collection` also offers `paginate({ page, perPage })`, `max`, `min`, `sum`, `avg`,
|
|
150
|
+
`updateBy`, `deleteBy` and async variants (`findAsync`, `findOneAsync`).
|
|
151
|
+
`paginate` returns the same `{ data, meta }` shape as the database paginators;
|
|
152
|
+
see [Pagination](/advanced/orm/queries#pagination).
|
|
153
|
+
|
|
154
|
+
## REST controller with a MeghORM model
|
|
155
|
+
|
|
156
|
+
With `--model` the generated controller delegates to a service that queries a
|
|
157
|
+
[MeghORM](/advanced/orm) model, which keeps data access out of the controller.
|
|
158
|
+
The model, its DTOs and the service are generated too if they don't exist yet;
|
|
159
|
+
the model's columns are read from the migration that creates its table.
|
|
160
|
+
|
|
161
|
+
```sh
|
|
162
|
+
npx megh make:controller users --model user --rest
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
or shorthand
|
|
166
|
+
|
|
167
|
+
```sh
|
|
168
|
+
npx megh m:c users -m user -r
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
::: code-group
|
|
172
|
+
```ts [users.controller.ts]
|
|
173
|
+
import {
|
|
174
|
+
ApiController,
|
|
175
|
+
ApiResponse,
|
|
176
|
+
Body,
|
|
177
|
+
Delete,
|
|
178
|
+
Get,
|
|
179
|
+
Paginated,
|
|
180
|
+
Param,
|
|
181
|
+
Post,
|
|
182
|
+
Put,
|
|
183
|
+
Query,
|
|
184
|
+
} from '@meghjs/core';
|
|
185
|
+
import { User } from '../models/user.model';
|
|
186
|
+
import { CreateUserDto, ListUsersQuery, UpdateUserDto } from '../dtos/user.dto';
|
|
187
|
+
import { UserService } from '../services/user.service';
|
|
188
|
+
|
|
189
|
+
@ApiController('/users')
|
|
190
|
+
export class UsersController {
|
|
191
|
+
constructor(private readonly userService: UserService) {}
|
|
192
|
+
|
|
193
|
+
@Get()
|
|
194
|
+
@ApiResponse(200, Paginated(User))
|
|
195
|
+
index(@Query() query: ListUsersQuery) {
|
|
196
|
+
return this.userService.paginate(query);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
@Get('/:id')
|
|
200
|
+
@ApiResponse(200, User)
|
|
201
|
+
@ApiResponse(404)
|
|
202
|
+
show(@Param('id') id: number) {
|
|
203
|
+
return this.userService.findOrFail(id);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
@Post()
|
|
207
|
+
@ApiResponse(200, User)
|
|
208
|
+
create(@Body() body: CreateUserDto) {
|
|
209
|
+
return this.userService.create(body);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
@Put('/:id')
|
|
213
|
+
@ApiResponse(200, User)
|
|
214
|
+
@ApiResponse(404)
|
|
215
|
+
update(@Param('id') id: number, @Body() body: UpdateUserDto) {
|
|
216
|
+
return this.userService.update(id, body);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
@Delete('/:id')
|
|
220
|
+
@ApiResponse(200, { type: 'object', properties: { message: { type: 'string' } } })
|
|
221
|
+
@ApiResponse(404)
|
|
222
|
+
async delete(@Param('id') id: number) {
|
|
223
|
+
await this.userService.delete(id);
|
|
224
|
+
return { message: 'User deleted.' };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
```ts [services/user.service.ts]
|
|
230
|
+
import { AppService, type CreateInput, type PageRequest, type UpdateInput } from '@meghjs/core';
|
|
231
|
+
import { User } from '../models/user.model';
|
|
232
|
+
|
|
233
|
+
@AppService
|
|
234
|
+
export class UserService {
|
|
235
|
+
findAll() {
|
|
236
|
+
return User.query().orderBy('id').get();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** One page of users: `{ data, meta }`. */
|
|
240
|
+
paginate(request: PageRequest = {}) {
|
|
241
|
+
return User.query().orderBy('id').paginate(request);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** The user with this id; throws a 404 when there is none. */
|
|
245
|
+
findOrFail(id: number) {
|
|
246
|
+
return User.findOrFail(id);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
create(input: CreateInput<typeof User>) {
|
|
250
|
+
return User.create(input);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** `save()` writes only the columns that changed. */
|
|
254
|
+
async update(id: number, changes: UpdateInput<User>) {
|
|
255
|
+
const user = await User.findOrFail(id);
|
|
256
|
+
// A DTO instance holds `undefined` for every field that was not sent.
|
|
257
|
+
const sent = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== undefined));
|
|
258
|
+
return user.fill(sent).save();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async delete(id: number) {
|
|
262
|
+
const user = await User.findOrFail(id);
|
|
263
|
+
await user.delete();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
```ts [models/user.model.ts]
|
|
269
|
+
import { Model, Table, PrimaryKey, AutoIncrement, Column, CreatedAt, UpdatedAt } from '@meghjs/core';
|
|
270
|
+
|
|
271
|
+
@Table('users')
|
|
272
|
+
export class User extends Model {
|
|
273
|
+
@PrimaryKey()
|
|
274
|
+
@AutoIncrement()
|
|
275
|
+
id?: number;
|
|
276
|
+
|
|
277
|
+
@Column()
|
|
278
|
+
name!: string;
|
|
279
|
+
|
|
280
|
+
@Column({ unique: true })
|
|
281
|
+
email!: string;
|
|
282
|
+
|
|
283
|
+
@CreatedAt()
|
|
284
|
+
created_at?: Date;
|
|
285
|
+
|
|
286
|
+
@UpdatedAt()
|
|
287
|
+
updated_at?: Date;
|
|
288
|
+
}
|
|
289
|
+
```
|
|
290
|
+
:::
|
|
291
|
+
|
|
292
|
+
`findOrFail` throws a 404 on its own, so the controller needs no
|
|
293
|
+
`HttpExceptions.notFound` check. See [MeghORM](/advanced/orm) for connecting the
|
|
294
|
+
database, and [Queries](/advanced/orm/queries) for what models can do.
|
|
295
|
+
|
|
296
|
+
## Global prefix and versioning
|
|
297
|
+
|
|
298
|
+
`setGlobalPrefix` serves every controller and inline route under a prefix.
|
|
299
|
+
Health routes and the API docs page keep their own paths; `exclude` leaves
|
|
300
|
+
more routes alone (paths as declared, or RegExps):
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
app.setGlobalPrefix('/api', { exclude: ['/status'] });
|
|
304
|
+
// @ApiController('/users') @Get('/') → GET /api/users
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
`useVersioning` serves controllers under API versions. Mark a controller or
|
|
308
|
+
a route with `@Version()` (or `@ApiController({ path, version })`); a route's
|
|
309
|
+
version overrides its controller's:
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
import { ApiController, Get, Version } from '@meghjs/core';
|
|
313
|
+
|
|
314
|
+
@Version('2')
|
|
315
|
+
@ApiController('/users')
|
|
316
|
+
export class UsersV2Controller {
|
|
317
|
+
@Get('/')
|
|
318
|
+
list() { ... }
|
|
319
|
+
|
|
320
|
+
@Get('/export')
|
|
321
|
+
@Version(['1', '2']) // served for both versions
|
|
322
|
+
export() { ... }
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
| Option | Requests look like |
|
|
327
|
+
|--------|--------------------|
|
|
328
|
+
| `{ type: 'uri' }` | `GET /api/v2/users`. `prefix` changes the `v` |
|
|
329
|
+
| `{ type: 'header' }` | `GET /api/users` with `X-API-Version: 2`. `header` changes the header name |
|
|
330
|
+
|
|
331
|
+
`defaultVersion` is the version of controllers without `@Version()`. With
|
|
332
|
+
header versioning it is also used when a request sends no version header.
|
|
333
|
+
Without a default, unversioned controllers keep their plain path.
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
app.useVersioning({ type: 'uri', defaultVersion: '1' });
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
Inline routes (`app.mapGet`, ...) get the global prefix but are not
|
|
340
|
+
versioned.
|
|
341
|
+
|
|
342
|
+
## Throwing errors
|
|
343
|
+
|
|
344
|
+
`HttpExceptions` covers the common status codes — `notFound`, `badRequest`,
|
|
345
|
+
`unauthorized`, `forbidden`, `internalError` — and each takes an optional
|
|
346
|
+
message:
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
throw HttpExceptions.notFound('User not found');
|
|
350
|
+
```
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Dependency Injection
|
|
3
|
+
description: Registering services and injecting them with constructors, inject() and tokens.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Dependency Injection
|
|
7
|
+
|
|
8
|
+
Megh builds your controllers, services and middleware for you, and gives each
|
|
9
|
+
one the services it needs. Every service is created once and shared.
|
|
10
|
+
|
|
11
|
+
## Registering a service
|
|
12
|
+
|
|
13
|
+
Mark a class with `@AppService` (or `@Injectable()`). Controllers, middleware,
|
|
14
|
+
config classes and queue workers are registered by their own decorators.
|
|
15
|
+
|
|
16
|
+
```ts [src/services/mailer.service.ts]
|
|
17
|
+
import { AppService } from '@meghjs/core';
|
|
18
|
+
|
|
19
|
+
@AppService
|
|
20
|
+
export class MailerService {
|
|
21
|
+
send(to: string, body: string) {
|
|
22
|
+
// ...
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Injecting with `inject()`
|
|
28
|
+
|
|
29
|
+
Call `inject()` in a field initializer:
|
|
30
|
+
|
|
31
|
+
```ts [src/services/user.service.ts]
|
|
32
|
+
import { AppService, inject } from '@meghjs/core';
|
|
33
|
+
import { MailerService } from './mailer.service';
|
|
34
|
+
import { UserRepository } from './user.repository';
|
|
35
|
+
|
|
36
|
+
@AppService
|
|
37
|
+
export class UserService {
|
|
38
|
+
private readonly users = inject(UserRepository);
|
|
39
|
+
private readonly mailer = inject(MailerService);
|
|
40
|
+
|
|
41
|
+
async register(email: string) {
|
|
42
|
+
const user = await this.users.create({ email });
|
|
43
|
+
this.mailer.send(email, 'Welcome!');
|
|
44
|
+
return user;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Unlike [constructor injection](#injecting-through-the-constructor),
|
|
50
|
+
`inject()` doesn't rely on `emitDecoratorMetadata`, so it also works with test
|
|
51
|
+
runners and bundlers that can't emit it, such as esbuild.
|
|
52
|
+
|
|
53
|
+
It works outside classes too, for example in a startup script:
|
|
54
|
+
|
|
55
|
+
```ts [serve.ts]
|
|
56
|
+
import { Environment, inject } from '@meghjs/core';
|
|
57
|
+
import app from './app';
|
|
58
|
+
|
|
59
|
+
async function serve() {
|
|
60
|
+
const env = inject(Environment);
|
|
61
|
+
await app.run(Number(env.get('PORT')) || 4000);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
serve();
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Optional dependencies
|
|
68
|
+
|
|
69
|
+
Pass `{ optional: true }` to get `undefined` instead of an error when nothing
|
|
70
|
+
is registered:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
private readonly analytics = inject(AnalyticsService, { optional: true });
|
|
74
|
+
// AnalyticsService | undefined
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
This only covers the service not being registered. If it's registered but
|
|
78
|
+
fails to build (one of its own dependencies is missing, or its constructor
|
|
79
|
+
throws), `inject()` still throws.
|
|
80
|
+
|
|
81
|
+
## Injecting through the constructor
|
|
82
|
+
|
|
83
|
+
Constructor parameters are injected from their types:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
@AppService
|
|
87
|
+
export class UserService {
|
|
88
|
+
constructor(
|
|
89
|
+
private readonly users: UserRepository,
|
|
90
|
+
private readonly mailer: MailerService,
|
|
91
|
+
) {}
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
This needs `experimentalDecorators` and `emitDecoratorMetadata` in
|
|
96
|
+
`tsconfig.json`, which `megh new` projects have.
|
|
97
|
+
|
|
98
|
+
Parameters typed as interfaces, unions or primitives (`string`, `number`)
|
|
99
|
+
have no runtime type to resolve: TypeScript emits `Object` or `String` for
|
|
100
|
+
them. Building such a class fails with a `ContainerError` that names the
|
|
101
|
+
parameter. Inject a [token](#tokens) with `@Inject`, or mark the parameter
|
|
102
|
+
`@Optional()` to get `undefined`:
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { AppService, Inject, Optional } from '@meghjs/core';
|
|
106
|
+
import { PAYMENTS, type PaymentGateway } from './tokens';
|
|
107
|
+
|
|
108
|
+
@AppService
|
|
109
|
+
export class OrderService {
|
|
110
|
+
constructor(
|
|
111
|
+
@Inject(PAYMENTS) private readonly gateway: PaymentGateway,
|
|
112
|
+
@Optional() private readonly audit?: AuditLog, // undefined unless registered
|
|
113
|
+
) {}
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`@Inject(id, { optional: true })` injects `undefined` when nothing is
|
|
118
|
+
registered for `id`. `@Optional()` on a class-typed parameter injects the
|
|
119
|
+
instance when the class is registered, and `undefined` when it isn't.
|
|
120
|
+
|
|
121
|
+
Both styles resolve the same shared instances, and you can mix them in a
|
|
122
|
+
class.
|
|
123
|
+
|
|
124
|
+
## Tokens
|
|
125
|
+
|
|
126
|
+
Use a `Token` for values that aren't classes, such as a client from another
|
|
127
|
+
library or a setting:
|
|
128
|
+
|
|
129
|
+
```ts [src/tokens.ts]
|
|
130
|
+
import { Token } from '@meghjs/core';
|
|
131
|
+
import type { Redis } from 'ioredis';
|
|
132
|
+
|
|
133
|
+
export const REDIS = new Token<Redis>('REDIS');
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
```ts [src/app.ts]
|
|
137
|
+
import { MeghContainer } from '@meghjs/core';
|
|
138
|
+
import Redis from 'ioredis';
|
|
139
|
+
import { REDIS } from './tokens';
|
|
140
|
+
|
|
141
|
+
MeghContainer.set(REDIS, new Redis(process.env.REDIS_URL));
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
@AppService
|
|
146
|
+
export class RateLimiter {
|
|
147
|
+
private readonly redis = inject(REDIS); // typed as Redis
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## `MeghContainer`
|
|
152
|
+
|
|
153
|
+
| Method | Use |
|
|
154
|
+
|--------|-----|
|
|
155
|
+
| `MeghContainer.get(id)` | Resolve a class, token or name. Same as `inject(id)` |
|
|
156
|
+
| `MeghContainer.set(id, value)` | Register a value, or replace a class with another implementation |
|
|
157
|
+
| `MeghContainer.has(id)` | Whether anything is registered for `id` |
|
|
158
|
+
| `MeghContainer.reset()` | Drop created class instances so they're built again. Token values are kept. For tests |
|
|
159
|
+
|
|
160
|
+
## Testing
|
|
161
|
+
|
|
162
|
+
Replace a dependency before the class that uses it is built, and reset after
|
|
163
|
+
each test:
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
import { MeghContainer } from '@meghjs/core';
|
|
167
|
+
|
|
168
|
+
afterEach(() => MeghContainer.reset());
|
|
169
|
+
|
|
170
|
+
it('sends a welcome email', async () => {
|
|
171
|
+
const sent: string[] = [];
|
|
172
|
+
MeghContainer.set(MailerService, { send: (to: string) => sent.push(to) });
|
|
173
|
+
|
|
174
|
+
await MeghContainer.get(UserService).register('a@b.c');
|
|
175
|
+
|
|
176
|
+
expect(sent).toEqual(['a@b.c']);
|
|
177
|
+
});
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`MeghContainer.set(MailerService, fake)` works for both `inject()` and
|
|
181
|
+
constructor injection.
|
|
182
|
+
|
|
183
|
+
## Errors
|
|
184
|
+
|
|
185
|
+
Errors are `ContainerError`s and name the chain of classes being built:
|
|
186
|
+
|
|
187
|
+
```
|
|
188
|
+
Cannot construct UserService -> MailerService: SmtpClient is not registered.
|
|
189
|
+
Mark it with @Injectable() (or @AppService), or register an instance with
|
|
190
|
+
MeghContainer.set(SmtpClient, value).
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
A parameter with no type to resolve fails when the class is first built,
|
|
194
|
+
instead of injecting `undefined`:
|
|
195
|
+
|
|
196
|
+
```
|
|
197
|
+
Cannot resolve parameter 0 of OrderService: its type is an interface, union
|
|
198
|
+
or primitive (emitted as Object). Use @Inject(TOKEN) on the parameter or
|
|
199
|
+
inject(TOKEN) in a field, type it as a class, or mark it @Optional().
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
A class-typed parameter can also show up as `Object` when two files import
|
|
203
|
+
each other: the class isn't loaded yet when TypeScript emits the type.
|
|
204
|
+
|
|
205
|
+
Two services that need each other while being built are reported instead of
|
|
206
|
+
overflowing the stack:
|
|
207
|
+
|
|
208
|
+
```
|
|
209
|
+
Circular dependency: OrderService -> UserService -> OrderService.
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
To break a cycle, have one side call `inject()` inside the method that needs
|
|
213
|
+
it, not in a field initializer or constructor.
|