@appweaver/skill 0.0.0-stage → 3.1.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 +29 -2
- package/index.d.ts +39 -0
- package/index.js +105 -0
- package/package.json +41 -3
- package/skill/GUIDELINES.md +383 -0
- package/skill/SKILL.md +121 -0
- package/skill/references/ai.md +231 -0
- package/skill/references/audit.md +220 -0
- package/skill/references/cache.md +233 -0
- package/skill/references/cli.md +760 -0
- package/skill/references/client.md +982 -0
- package/skill/references/configuration.md +1224 -0
- package/skill/references/database.md +349 -0
- package/skill/references/dependency-injection.md +301 -0
- package/skill/references/errors.md +486 -0
- package/skill/references/events.md +203 -0
- package/skill/references/logging.md +157 -0
- package/skill/references/mailer.md +393 -0
- package/skill/references/mcp.md +245 -0
- package/skill/references/modules.md +509 -0
- package/skill/references/patterns.md +1217 -0
- package/skill/references/payments.md +795 -0
- package/skill/references/queue.md +281 -0
- package/skill/references/realtime.md +572 -0
- package/skill/references/resources.md +2238 -0
- package/skill/references/scheduler.md +228 -0
- package/skill/references/security.md +1185 -0
- package/skill/references/sms.md +143 -0
- package/skill/references/spatial.md +197 -0
- package/skill/references/storage.md +500 -0
- package/skill/references/telemetry.md +207 -0
- package/skill/references/templates.md +488 -0
- package/skill/references/timeseries.md +312 -0
- package/skill/references/workflow.md +224 -0
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
# Database
|
|
2
|
+
|
|
3
|
+
The database module exposes a thin abstraction over the underlying database client. The default implementation
|
|
4
|
+
wraps [Prisma](https://www.prisma.io/) and is registered under the abstract `Database` class. The framework connects on
|
|
5
|
+
startup and disconnects on shutdown automatically. An unreachable database never fails the startup: the connection is
|
|
6
|
+
checked with a `SELECT 1`, the failure is logged as an error, and the next query connects again with a new client.
|
|
7
|
+
|
|
8
|
+
## Injecting the client
|
|
9
|
+
|
|
10
|
+
A project scaffolded with the `data` module exports the typed client from `database/client.ts`, imported as
|
|
11
|
+
`@db/client`:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { injectDatabaseClient } from '@appweaver/core';
|
|
15
|
+
import { PrismaClient } from '@db/client/client';
|
|
16
|
+
|
|
17
|
+
export const db = injectDatabaseClient<PrismaClient>();
|
|
18
|
+
|
|
19
|
+
export default db;
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
#### `injectDatabaseClient<T>()`
|
|
23
|
+
|
|
24
|
+
Returns the client of the `Database` definition, typed by `T` (the generated `PrismaClient`). The client is resolved
|
|
25
|
+
from the application context on every member access rather than when `injectDatabaseClient` is called, so it can be
|
|
26
|
+
created at the top level of a module that is imported before the application is created, i.e. by a test file, and it
|
|
27
|
+
always reaches the database of the current application. Accessing a member before the application is created throws,
|
|
28
|
+
as `inject(Database)` does.
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import db from '@db/client';
|
|
32
|
+
|
|
33
|
+
const users = await db.user.findMany({ where: { enabled: true } });
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
#### `db.client<T>()`
|
|
37
|
+
|
|
38
|
+
Returns the underlying database client cast to type `T`. For the default Prisma provider `T` is `PrismaClient`. The
|
|
39
|
+
client runs its queries in the current transaction, so a client resolved once at startup still joins one.
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
const users = await client.user.findMany({ where: { active: true } });
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
#### `db.connect()`
|
|
46
|
+
|
|
47
|
+
Opens the database connection, throwing when it fails. Called by the framework during `onInit`, which logs the failure
|
|
48
|
+
instead of throwing.
|
|
49
|
+
|
|
50
|
+
#### `db.disconnect()`
|
|
51
|
+
|
|
52
|
+
Closes the database connection. Called automatically by the framework during `onDestroy`.
|
|
53
|
+
|
|
54
|
+
#### `db.checkHealth()`
|
|
55
|
+
|
|
56
|
+
Returns a `HealthCheckResult`. Executes a lightweight `SELECT 1` query to verify the connection.
|
|
57
|
+
|
|
58
|
+
## Transactions
|
|
59
|
+
|
|
60
|
+
`runTransaction` runs a function in one transaction. Every resource service call and client query made inside it
|
|
61
|
+
commits together when it resolves, and an error thrown out of it rolls everything back and is rethrown unchanged. An
|
|
62
|
+
error caught inside the function does not roll back.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { afterCommit, injectService } from '@appweaver/core';
|
|
66
|
+
import { runTransaction } from '@appweaver/data';
|
|
67
|
+
import { Prisma } from '@db/client/client';
|
|
68
|
+
|
|
69
|
+
const orders = injectService('Order');
|
|
70
|
+
|
|
71
|
+
// The parameter type gives the transaction client the models of the application
|
|
72
|
+
const order = await runTransaction(async (tx: Prisma.TransactionClient) => {
|
|
73
|
+
const order = await orders.create({ customer: customerId, total });
|
|
74
|
+
await tx.product.updateMany({
|
|
75
|
+
where: { id: productId, stock: { gte: 1 } },
|
|
76
|
+
data: { stock: { decrement: 1 } }
|
|
77
|
+
});
|
|
78
|
+
afterCommit(() => sendOrderEmail(order)); // runs only once committed
|
|
79
|
+
return order;
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
await runTransaction('Serializable', async () => {
|
|
83
|
+
// Database calls...
|
|
84
|
+
});
|
|
85
|
+
await runTransaction(
|
|
86
|
+
{
|
|
87
|
+
isolationLevel: 'Serializable',
|
|
88
|
+
timeout: 10_000,
|
|
89
|
+
maxWait: 2_000,
|
|
90
|
+
retries: 3
|
|
91
|
+
},
|
|
92
|
+
async () => {
|
|
93
|
+
// Database calls...
|
|
94
|
+
}
|
|
95
|
+
);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
| Option | Default | Description |
|
|
99
|
+
| ---------------- | ------------------------------------------------- | --------------------------------------------------------------------------------- |
|
|
100
|
+
| `isolationLevel` | database default, always `Serializable` on SQLite | `ReadUncommitted`, `ReadCommitted`, `RepeatableRead`, `Serializable`, `Snapshot`. |
|
|
101
|
+
| `timeout` | `DATABASE_TRANSACTION_TIMEOUT` | Maximum run time in milliseconds. |
|
|
102
|
+
| `maxWait` | `DATABASE_TRANSACTION_MAX_WAIT` | Maximum wait for a connection in milliseconds. |
|
|
103
|
+
| `retries` | `0` | Reruns the whole function after a write conflict (Prisma `P2034`). |
|
|
104
|
+
|
|
105
|
+
- The resource events, the cache invalidation, and the removal of stored files run after the commit and are dropped on
|
|
106
|
+
rollback. A file stored inside a rolled back transaction is removed. Wrap other side effects (emails, jobs) in
|
|
107
|
+
`afterCommit(fn)`, which runs right away outside a transaction.
|
|
108
|
+
- A `runTransaction` (or `$transaction`) inside another one joins it. Asking it for another isolation level throws.
|
|
109
|
+
- On PostgreSQL a failed query aborts the whole transaction, so only catch the errors thrown before a write fails (i.e.
|
|
110
|
+
a `RESOURCE_NOT_FOUND` or `RESOURCE_FORBIDDEN` of a service).
|
|
111
|
+
- A failed database operation of a resource service throws a `DatabaseError` describing it, i.e.
|
|
112
|
+
`DATABASE_UNIQUE_VIOLATION` with the violated `fields` in its details. Translate the errors of a direct Prisma call
|
|
113
|
+
the same way with `toDatabaseError(e, 'Model')` (see [errors.md](./errors.md#throwing-errors-in-the-application)).
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## Schema and migrations
|
|
118
|
+
|
|
119
|
+
By convention the Prisma schema lives at `./database/schema.prisma` and migrations at `./database/migrations/`. These
|
|
120
|
+
paths are configurable.
|
|
121
|
+
|
|
122
|
+
**schema.prisma example:**
|
|
123
|
+
|
|
124
|
+
```prisma
|
|
125
|
+
datasource db {
|
|
126
|
+
provider = env("DATABASE_TYPE")
|
|
127
|
+
url = env("DATABASE_URL")
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
generator client {
|
|
131
|
+
provider = "prisma-client-js"
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
model User {
|
|
135
|
+
id Int @id @default(autoincrement())
|
|
136
|
+
email String @unique
|
|
137
|
+
name String
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Generate the Prisma schema and client after resource models change:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
weaver generate
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Check whether the models need a new migration, then create it:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
weaver migration check # exit code 1 and the SQL when one is needed
|
|
151
|
+
weaver migration new <migration_name>
|
|
152
|
+
weaver migration new <migration_name> --create-only # to edit its migration.sql before applying it
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Both leave the FTS5 tables of the full-text indexes of SQLite out (as the `tables.external` of a config written beside
|
|
156
|
+
`prisma.config.ts` while Prisma runs), so Prisma neither drops them nor reports them as a drift. The `FULLTEXT` index of
|
|
157
|
+
MySQL is an index of the table Prisma compares: drop it before `weaver migration new` in development (the application
|
|
158
|
+
creates it again when it starts), and remove its `DROP INDEX` from a migration `weaver migration check` prints.
|
|
159
|
+
|
|
160
|
+
Run pending migrations, or print them with their SQL first:
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
weaver migrate --dry-run
|
|
164
|
+
weaver migrate
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
The options of these commands are in [cli.md](./cli.md#weaver-generate).
|
|
168
|
+
|
|
169
|
+
## SQL migrations
|
|
170
|
+
|
|
171
|
+
The SQL Prisma does not generate (an expression, trigram or partial index, a trigger, a function, a view, a check
|
|
172
|
+
constraint, an extension) goes into the SQL migrations of `database.sqlDirPath` (`./database/sql`), plain SQL files
|
|
173
|
+
`weaver migrate` applies after the Prisma migrations, once, recorded in the `SqlMigration` framework model (the
|
|
174
|
+
`_sql_migrations` table, in the Prisma schema only while the directory exists):
|
|
175
|
+
|
|
176
|
+
```
|
|
177
|
+
database/sql/
|
|
178
|
+
20261201_post_search.sql # any database
|
|
179
|
+
20261201_post_search.postgresql.sql # replaces the generic file on PostgreSQL
|
|
180
|
+
20261205_post_trgm.postgresql.sql # PostgreSQL only, skipped on the others
|
|
181
|
+
functions/slugify.sql # repeatable: applied again whenever it changes
|
|
182
|
+
views/published_posts.sql
|
|
183
|
+
triggers/post_search.sql
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
weaver migration new post_trgm --sql --database postgresql # creates database/sql/<timestamp>_post_trgm.postgresql.sql
|
|
188
|
+
weaver migrate --dry-run # lists the pending Prisma and SQL migrations
|
|
189
|
+
weaver migrate # Prisma migrations, SQL migrations, database setup
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
- A versioned file is `<version>_<name>[.<database>].sql`, the database one of `sqlite`, `postgresql`, `mysql` or
|
|
193
|
+
`sqlserver` (any other suffix fails). For one version, the file of the current database is applied if there is
|
|
194
|
+
one, else the generic file, else nothing. Files run in version order, then the repeatable files of `functions/`,
|
|
195
|
+
`views/` and `triggers/` (write them with `CREATE OR REPLACE`, or `DROP ... IF EXISTS` first).
|
|
196
|
+
- A file runs in a transaction (except on MySQL, which commits every DDL statement), unless its first line is
|
|
197
|
+
`-- appweaver:no-transaction` (`CREATE INDEX CONCURRENTLY`), without the 5 s timeout of `database.transactionTimeout`
|
|
198
|
+
(a day). It is split into statements at the semicolons outside of the strings (with the backslash escapes of MySQL
|
|
199
|
+
and of the `E'...'` strings of PostgreSQL), the comments, the dollar quotes of PostgreSQL and the `BEGIN ... END`
|
|
200
|
+
bodies (`END IF`, `END CASE`, `END LOOP` included), and into batches at the `GO` lines on SQL Server. The
|
|
201
|
+
`DELIMITER` command of the MySQL client is not supported.
|
|
202
|
+
- A run takes a lock of the database first (an advisory lock on PostgreSQL, `GET_LOCK` on MySQL, `sp_getapplock` on
|
|
203
|
+
SQL Server), held by a transaction of its own while the files run on the other connections of the pool, so two
|
|
204
|
+
`weaver migrate` started together (two instances of a deployment) apply a file once. SQLite has no such lock: run
|
|
205
|
+
one migration at a time.
|
|
206
|
+
- A versioned file changed after it was applied fails `weaver migrate`: add a new file instead, or record the new
|
|
207
|
+
checksum with `weaver migrate --fix-checksums`.
|
|
208
|
+
- `weaver test setup`, `weaver test reset` and `weaver migration reset` apply them after the reset, so the tests run
|
|
209
|
+
with them. They connect with the Prisma client of the build, so build before migrating, like the database setup.
|
|
210
|
+
`weaver migration reset` skips them while the project has no Prisma migration, since the Prisma migrations create
|
|
211
|
+
the tables they need: run `weaver migrate` after the first `weaver migration new`.
|
|
212
|
+
- A module ships its own in the `sql` directory of its manifest (`path.join(__dirname, 'sql')`), applied before the
|
|
213
|
+
application's, recorded under the module name (`billing/20261201_plans`).
|
|
214
|
+
- Prisma does not know these objects: `weaver migration new` and `weaver migration check` fail when the next Prisma
|
|
215
|
+
migration would drop a column or an index a SQL file creates (`CREATE INDEX`, `ADD COLUMN`), or on SQLite when it
|
|
216
|
+
redefines (copies) a table holding a column, an index or a trigger of a SQL file, which the copy loses. Declare such
|
|
217
|
+
an object in the model, or keep it out of the tables Prisma manages. `weaver migration new --create-only` only
|
|
218
|
+
warns, so the migration can be created, then a SQL migration creating the lost objects again
|
|
219
|
+
(`CREATE INDEX IF NOT EXISTS`), applied after it by `weaver migrate`; the repeatable `indexes/generated.sql` is
|
|
220
|
+
applied again only once it changes.
|
|
221
|
+
- The generated columns of `columns/generated.sql` are the exception, since Prisma sees a column: `weaver migration
|
|
222
|
+
new` records them in a Prisma migration of their own first ([resources.md](./resources.md#generated-columns)).
|
|
223
|
+
- `weaver generate` writes the repeatable `columns/generated.sql` and `indexes/generated.sql` from the generated
|
|
224
|
+
columns and the expression indexes of the models ([resources.md](./resources.md#generated-columns)); leave them to it.
|
|
225
|
+
- A Docker image copies `database/sql` beside `database/migrations`.
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
229
|
+
## Configuration
|
|
230
|
+
|
|
231
|
+
| Key | Type | Default | Description |
|
|
232
|
+
| ------------------------------- | -------- | ---------------------------- | ----------------------------------------------- |
|
|
233
|
+
| `DATABASE_TYPE` | `enum` | — | `sqlite`, `postgresql`, `mysql`, or `sqlserver` |
|
|
234
|
+
| `DATABASE_URL` | `string` | — | Connection string / DSN of the application |
|
|
235
|
+
| `DATABASE_MIGRATION_URL` | `string` | `DATABASE_URL` | Connection string / DSN of the migrations |
|
|
236
|
+
| `DATABASE_SCHEMA_PATH` | `string` | `'./database/schema.prisma'` | Path to the Prisma schema file |
|
|
237
|
+
| `DATABASE_MIGRATIONS_DIR_PATH` | `string` | `'./database/migrations'` | Path to the migrations directory |
|
|
238
|
+
| `DATABASE_TRANSACTION_MAX_WAIT` | `int` | `2000` | Max time (ms) to wait to acquire a transaction |
|
|
239
|
+
| `DATABASE_TRANSACTION_TIMEOUT` | `int` | `5000` | Max time (ms) a transaction may run |
|
|
240
|
+
| `DATABASE_PROVIDER` | `string` | `'auto'` | `auto`/`prisma`, or `none` for no database |
|
|
241
|
+
|
|
242
|
+
Configure the URL in `appweaver.json`, referencing the password of the gitignored `.env` (`DB_PASSWORD=myapp`), a
|
|
243
|
+
`DB_HOST` a docker-compose container sets to the database service name, and a `DB_NAME` and `DB_USER` to rename the
|
|
244
|
+
database or change its user. The type is resolved from the URL scheme when not set:
|
|
245
|
+
|
|
246
|
+
```json
|
|
247
|
+
{
|
|
248
|
+
"config": {
|
|
249
|
+
"database": {
|
|
250
|
+
"url": "postgresql://${DB_USER:-myapp}:${DB_PASSWORD}@${DB_HOST:-localhost}:5432/${DB_NAME:-myapp}"
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
The test database URL goes to the `environments.test` section of `appweaver.json` (i.e. the `${DB_NAME:-myapp}-test`
|
|
257
|
+
database of the same server).
|
|
258
|
+
|
|
259
|
+
PostgreSQL uses the `public` schema unless the URL selects another one with `?schema=` (i.e.
|
|
260
|
+
`...:5432/myapp?schema=webshop`). Prisma Migrate creates the schema and its tables there, and the framework passes it on
|
|
261
|
+
to the PostgreSQL adapter, so the queries use it as well. Existing tables are not moved from `public`. Prefer a name
|
|
262
|
+
without hyphens (`my_app`), which raw SQL would otherwise have to double-quote.
|
|
263
|
+
|
|
264
|
+
### Separate migration and application users
|
|
265
|
+
|
|
266
|
+
The application connects with `database.url`, the migrations with `database.migrationUrl` (`database.url` when not
|
|
267
|
+
set). The application user then only reads and writes the rows, while the migrations run as the owner of the tables,
|
|
268
|
+
or through a direct connection beside a pooler. Both URLs must point to the same database, so set both in an
|
|
269
|
+
environment that changes it.
|
|
270
|
+
|
|
271
|
+
```json
|
|
272
|
+
{
|
|
273
|
+
"config": {
|
|
274
|
+
"database": {
|
|
275
|
+
"url": "postgresql://${DB_USER:-myapp}:${DB_PASSWORD}@${DB_HOST:-localhost}:5432/${DB_NAME:-myapp}",
|
|
276
|
+
"migrationUrl": "postgresql://${DB_MIGRATION_USER:-myapp-owner}:${DB_MIGRATION_PASSWORD}@${DB_HOST:-localhost}:5432/${DB_NAME:-myapp}"
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
- `prisma.config.ts` sets `url: migrationUrl()` (of `@appweaver/data/config`); a project created before it has
|
|
283
|
+
`databaseConfig.URL` there, which ignores the migration URL.
|
|
284
|
+
- `weaver migrate` also sets up the TimescaleDB hypertables, the PostGIS geometry triggers and the full-text indexes
|
|
285
|
+
(on every database), which need the owner.
|
|
286
|
+
Build first, since it reads the built models. A start finding them out of date asks to run `weaver migrate`.
|
|
287
|
+
- The owner keeps the right to create databases in development, for the shadow database of `weaver migration new`.
|
|
288
|
+
|
|
289
|
+
The application user, granted by the owner:
|
|
290
|
+
|
|
291
|
+
```sql
|
|
292
|
+
-- PostgreSQL
|
|
293
|
+
CREATE ROLE "myapp" LOGIN PASSWORD '...';
|
|
294
|
+
GRANT CONNECT ON DATABASE "myapp" TO "myapp";
|
|
295
|
+
GRANT USAGE ON SCHEMA public TO "myapp";
|
|
296
|
+
ALTER DEFAULT PRIVILEGES FOR ROLE "myapp-owner" IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO "myapp";
|
|
297
|
+
ALTER DEFAULT PRIVILEGES FOR ROLE "myapp-owner" IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO "myapp";
|
|
298
|
+
|
|
299
|
+
-- MySQL / MariaDB
|
|
300
|
+
CREATE USER 'myapp'@'%' IDENTIFIED BY '...';
|
|
301
|
+
GRANT SELECT, INSERT, UPDATE, DELETE ON `myapp`.* TO 'myapp'@'%';
|
|
302
|
+
|
|
303
|
+
-- SQL Server
|
|
304
|
+
CREATE LOGIN [myapp] WITH PASSWORD = '...';
|
|
305
|
+
CREATE USER [myapp] FOR LOGIN [myapp];
|
|
306
|
+
ALTER ROLE db_datareader ADD MEMBER [myapp];
|
|
307
|
+
ALTER ROLE db_datawriter ADD MEMBER [myapp];
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
See `sample/vehicle-tracking-api` and its `database/postgres-init.sh`.
|
|
311
|
+
SQLite has no users, so it needs neither URL.
|
|
312
|
+
|
|
313
|
+
---
|
|
314
|
+
|
|
315
|
+
## SQLite in production
|
|
316
|
+
|
|
317
|
+
SQLite (`better-sqlite3`, or `libsql` on Bun) suits one instance with a moderate load. Its driver runs every statement
|
|
318
|
+
synchronously on the event loop, so measured on `cms-api` at 100k posts:
|
|
319
|
+
|
|
320
|
+
- **One slow query stalls every request**: the throughput does not grow with the connections, and a text search
|
|
321
|
+
(`contains` on three columns, ~150 ms) or an exact count holds every other request behind it.
|
|
322
|
+
- **`server.requestTimeout` answers the client, not the database**: the query runs to its end. Keep the queries
|
|
323
|
+
bounded instead: `totalCount` stays off unless a page needs it (the count stops at `resource.countLimit`, along the
|
|
324
|
+
index of the sort), the cursor instead of deep offset pages (`resource.maxOffset`), `from`/`to` on `aggregate`.
|
|
325
|
+
- **Index what the policies filter and sort on**: the `readRestrictions` of a public listing run on every request; an
|
|
326
|
+
index on `(status, createdAt, id)` took the anonymous listing of `cms-api` from 7 to 296 requests a second.
|
|
327
|
+
- **One instance**: the database is a file of the instance; for several instances, heavy writes, or a text search over
|
|
328
|
+
large tables, use PostgreSQL, MySQL or SQL Server.
|
|
329
|
+
|
|
330
|
+
## Real-world example
|
|
331
|
+
|
|
332
|
+
```ts
|
|
333
|
+
import { inject } from '@appweaver/core';
|
|
334
|
+
import db from '@db/client';
|
|
335
|
+
|
|
336
|
+
export class UserRepository {
|
|
337
|
+
async findById(id: number) {
|
|
338
|
+
return db.user.findUnique({ where: { id } });
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async create(data: { email: string; name: string }) {
|
|
342
|
+
return db.user.create({ data });
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
async runInTransaction<T>(fn: (tx: PrismaClient) => Promise<T>): Promise<T> {
|
|
346
|
+
return db.$transaction(fn);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
```
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
# Dependency Injection
|
|
2
|
+
|
|
3
|
+
The application context provides a lightweight dependency injection (DI) system through `define` and `inject`. Values,
|
|
4
|
+
class constructors, and singleton instances are stored in the context and resolved by name or class reference.
|
|
5
|
+
|
|
6
|
+
#### `define(value, nameOrClass?, mode?)`
|
|
7
|
+
|
|
8
|
+
Registers a value or class constructor in the application context.
|
|
9
|
+
|
|
10
|
+
| Parameter | Type | Description |
|
|
11
|
+
| ------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
12
|
+
| `value` | any | The value, instance, or class constructor to register |
|
|
13
|
+
| `nameOrClass` | `string \| symbol \| Class \| Function` | Token used to look up this definition. Defaults to the value's class name or `RESOURCE_NAME` property |
|
|
14
|
+
| `mode` | `'ignore' \| 'override' \| 'append' \| 'fail' \| 'default'` | How to handle duplicates. Defaults to `'ignore'` |
|
|
15
|
+
|
|
16
|
+
The `mode` decides what happens when a definition with the same name exists:
|
|
17
|
+
|
|
18
|
+
- `'ignore'` (default) – keeps the existing definition and logs a warning.
|
|
19
|
+
- `'append'` – adds another definition under the same name, all of them resolved by `injectAll`. A resource (model,
|
|
20
|
+
service, routes, or policy) has one definition per name, so it replaces the existing one.
|
|
21
|
+
- `'override'` – replaces the existing definition.
|
|
22
|
+
- `'fail'` – throws an error.
|
|
23
|
+
- `'default'` – keeps an existing definition silently (a default replaces an earlier default), otherwise adds a
|
|
24
|
+
default that a later definition under the same name replaces in the `ignore`, `override` and `fail` modes, while
|
|
25
|
+
`append` adds beside it. The providers and services of the modules are defined so, so a plain
|
|
26
|
+
`define(new MyEmailService(), EmailService)` in an application file replaces the one of a module.
|
|
27
|
+
|
|
28
|
+
**Register a plain value with a string token:**
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { define } from '@appweaver/core';
|
|
32
|
+
|
|
33
|
+
define('https://api.example.com', 'ApiBaseUrl');
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
**Register a class instance under an abstract class token:**
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { define } from '@appweaver/core';
|
|
40
|
+
import { SecurityStore } from '@appweaver/common';
|
|
41
|
+
import { MySecurityStore } from './my-security-store';
|
|
42
|
+
|
|
43
|
+
// MySecurityStore will be looked up by SecurityStore.name
|
|
44
|
+
define(new MySecurityStore(), SecurityStore);
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**Register a class constructor (lazy instantiation on the first injection):**
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { define } from '@appweaver/core';
|
|
51
|
+
import { Cache } from '@appweaver/common';
|
|
52
|
+
import { MyCacheService } from './my-cache-service';
|
|
53
|
+
|
|
54
|
+
// MyCacheService is instantiated the first time inject(Cache) is called
|
|
55
|
+
define(MyCacheService, Cache);
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
**Register with a symbol token:**
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { define } from '@appweaver/core';
|
|
62
|
+
|
|
63
|
+
const RATE_LIMITER = Symbol('RateLimiter');
|
|
64
|
+
define(new TokenBucketLimiter(), RATE_LIMITER);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
**Override an existing definition:**
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
import { define } from '@appweaver/core';
|
|
71
|
+
import { Cache } from '@appweaver/common';
|
|
72
|
+
|
|
73
|
+
define(new InMemoryCacheService(), Cache, 'override');
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
#### `inject(nameOrClass, required?)`
|
|
77
|
+
|
|
78
|
+
Retrieves a definition from the application context. If the stored value is a class constructor, it is instantiated on
|
|
79
|
+
first access, and the instance replaces the constructor in the context (singleton pattern).
|
|
80
|
+
|
|
81
|
+
| Parameter | Type | Description |
|
|
82
|
+
| ------------- | --------------------------------------- | -------------------------------------- |
|
|
83
|
+
| `nameOrClass` | `string \| symbol \| Class \| Function` | Token that identifies the definition |
|
|
84
|
+
| `required` | `boolean` | Throw if not found. Defaults to `true` |
|
|
85
|
+
|
|
86
|
+
**Inject by abstract class (the most common pattern):**
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { inject } from '@appweaver/core';
|
|
90
|
+
import { SecurityStore } from '@appweaver/common';
|
|
91
|
+
|
|
92
|
+
export class AuthService {
|
|
93
|
+
private readonly _store = inject(SecurityStore);
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**Inject by string token:**
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { inject } from '@appweaver/core';
|
|
101
|
+
|
|
102
|
+
const apiUrl = inject<string>('ApiBaseUrl');
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
A string token ending with `Model`, `Service`, `Routes`, or `Policy` (e.g. `'PostService'`) also resolves the resource
|
|
106
|
+
definition of that model, but only when no definition was registered under that exact name, so a value defined as
|
|
107
|
+
`'ShippingService'` is always injectable by that name.
|
|
108
|
+
|
|
109
|
+
**Inject by symbol token:**
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { inject } from '@appweaver/core';
|
|
113
|
+
|
|
114
|
+
const RATE_LIMITER = Symbol('RateLimiter');
|
|
115
|
+
const limiter = inject<RateLimiter>(RATE_LIMITER);
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
**Optionally inject (returns `undefined` instead of throwing):**
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
import { inject } from '@appweaver/core';
|
|
122
|
+
import { Mailer } from '@appweaver/common';
|
|
123
|
+
|
|
124
|
+
const mailer = inject(Mailer, false); // undefined if not registered, i.e. with MAILER_PROVIDER=none
|
|
125
|
+
if (mailer) {
|
|
126
|
+
await mailer.sendEmail({
|
|
127
|
+
to: 'jane@example.com',
|
|
128
|
+
subject: 'Welcome',
|
|
129
|
+
text: 'Hello!'
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
#### `isDefined(nameOrClass)` and `injectCreated(nameOrClass)`
|
|
135
|
+
|
|
136
|
+
`isDefined` checks if a definition is registered without creating its instance, i.e. whether a contract has a provider
|
|
137
|
+
or a module is enabled. `injectCreated` returns the instance only once it is created, `undefined` before, so it never
|
|
138
|
+
instantiates a class:
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
import { injectCreated, isDefined } from '@appweaver/core';
|
|
142
|
+
import { HttpServer } from '@appweaver/web';
|
|
143
|
+
import { Scheduler } from '@appweaver/common';
|
|
144
|
+
|
|
145
|
+
if (isDefined(Scheduler)) {
|
|
146
|
+
// a scheduler driver is selected
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const server = injectCreated(HttpServer)?.instance; // the Fastify instance, once the server is created
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**Real-world example — service using injected dependencies:**
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
// src/features/notifications/notification-service.ts
|
|
156
|
+
import { CacheService, inject } from '@appweaver/core';
|
|
157
|
+
import { Mailer } from '@appweaver/common';
|
|
158
|
+
|
|
159
|
+
export class NotificationService {
|
|
160
|
+
private readonly _mailer = inject(Mailer);
|
|
161
|
+
private readonly _cache = inject(CacheService);
|
|
162
|
+
|
|
163
|
+
public async notify(email: string, message: string): Promise<void> {
|
|
164
|
+
const key = `notification:${email}`;
|
|
165
|
+
if (await this._cache.getCachedValue(key)) return;
|
|
166
|
+
await this._mailer.sendEmail({
|
|
167
|
+
to: email,
|
|
168
|
+
subject: 'Notification',
|
|
169
|
+
text: message
|
|
170
|
+
});
|
|
171
|
+
await this._cache.addToCache(key, true, 60_000);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Then register it so other code can inject it:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
import { define } from '@appweaver/core';
|
|
180
|
+
import { NotificationService } from './notification-service';
|
|
181
|
+
|
|
182
|
+
define(NotificationService);
|
|
183
|
+
// or define the instance directly:
|
|
184
|
+
define(new NotificationService(), NotificationService);
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
#### `injectAll(nameOrClass)` and `injectAllWhere(predicate)`
|
|
188
|
+
|
|
189
|
+
Resolve every definition registered under a name (see the `'append'` mode of `define`), or every definition matching a
|
|
190
|
+
predicate, instantiating the class constructors as `inject` does. Both return an empty array when nothing matches.
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
import { define, injectAll, injectAllWhere } from '@appweaver/core';
|
|
194
|
+
|
|
195
|
+
define(new SlackNotifier(), 'Notifier', 'append');
|
|
196
|
+
define(new EmailNotifier(), 'Notifier', 'append');
|
|
197
|
+
|
|
198
|
+
const notifiers = injectAll<Notifier>('Notifier'); // [SlackNotifier, EmailNotifier]
|
|
199
|
+
const lifecycle = injectAllWhere(
|
|
200
|
+
(def) => typeof def.value?.onInit === 'function'
|
|
201
|
+
);
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
#### `loadProvider(baseDir, classPath, definition?, required?)`
|
|
205
|
+
|
|
206
|
+
Dynamically loads a class from a file path and registers it in the context. The first exported constructor in the
|
|
207
|
+
resolved module is used. The infrastructure providers are defined by the modules from their `provider` keys (see
|
|
208
|
+
[modules](./modules.md)), which call `loadProvider` for a key holding a module path; call it directly only to load a
|
|
209
|
+
class from a configurable path.
|
|
210
|
+
|
|
211
|
+
| Parameter | Type | Description |
|
|
212
|
+
| ------------ | --------- | ------------------------------------------------------------------------------------ |
|
|
213
|
+
| `baseDir` | `string` | Base directory for resolving relative paths |
|
|
214
|
+
| `classPath` | `string` | Path to the module — relative to `baseDir`, project source path, or npm package name |
|
|
215
|
+
| `definition` | `Class` | Abstract class / token to register the loaded class under |
|
|
216
|
+
| `required` | `boolean` | Throw on load failure. Defaults to `true` |
|
|
217
|
+
|
|
218
|
+
**Load a provider and register it under an abstract token:**
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import { loadProvider } from '@appweaver/core';
|
|
222
|
+
import { Database } from '@appweaver/common';
|
|
223
|
+
|
|
224
|
+
// Loads the first exported class from './providers/postgres-database.ts'
|
|
225
|
+
// and registers it as Database
|
|
226
|
+
loadProvider(__dirname, './providers/postgres-database', Database);
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
**Load an optional class (no error if the file is missing), registered by its own class name:**
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
import { loadProvider } from '@appweaver/core';
|
|
233
|
+
|
|
234
|
+
loadProvider(
|
|
235
|
+
__dirname,
|
|
236
|
+
'../notifications/notification-service',
|
|
237
|
+
undefined,
|
|
238
|
+
false
|
|
239
|
+
);
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
`selectedProvider(Contract)` returns the name of the provider the modules selected for a contract (`redis` for the
|
|
243
|
+
`Memory`), or `undefined` when none is.
|
|
244
|
+
|
|
245
|
+
`inject` resolves the definition when it is called and throws before the application has defined it. To hold the
|
|
246
|
+
database client in a module-level constant, use `injectDatabaseClient<PrismaClient>()` instead, which resolves the
|
|
247
|
+
client on every access.
|
|
248
|
+
|
|
249
|
+
## Lifecycle hooks
|
|
250
|
+
|
|
251
|
+
A class registered in the application context can run code when the application starts and stops by implementing the
|
|
252
|
+
interfaces of `@appweaver/common`, called in this order:
|
|
253
|
+
|
|
254
|
+
| Hook | Interface | Runs |
|
|
255
|
+
| -------------- | ------------ | -------------------------------------------------------------------------------------------------------------------- |
|
|
256
|
+
| `onInit()` | `OnInit` | Once when the application starts. |
|
|
257
|
+
| `onReady()` | `OnReady` | Once every `onInit` finished, i.e. to start serving requests (the server listens unless `SERVER_LISTEN` is `false`). |
|
|
258
|
+
| `onShutdown()` | `OnShutdown` | First when the application stops, before any service is destroyed, i.e. to stop serving requests. |
|
|
259
|
+
| `onDestroy()` | `OnDestroy` | Last when the application stops, after every `onShutdown`, to release the resources. |
|
|
260
|
+
|
|
261
|
+
The services are destroyed before the drivers of the contracts (the queue, the database, ...), so the last writes of
|
|
262
|
+
an `onDestroy` reach them; the hooks of one group run at once.
|
|
263
|
+
|
|
264
|
+
The HTTP server is such a service: `HttpServer` of the `@appweaver/web` module listens in `onReady` and closes in
|
|
265
|
+
`onShutdown`, finishing the requests in flight before any service is destroyed.
|
|
266
|
+
|
|
267
|
+
The class must also set the static `[LIFECYCLE]` tag, otherwise its hooks are never called:
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
// src/features/rates/exchange-rates.ts
|
|
271
|
+
import { LIFECYCLE, OnDestroy, OnInit } from '@appweaver/common';
|
|
272
|
+
import { define } from '@appweaver/core';
|
|
273
|
+
|
|
274
|
+
export class ExchangeRates implements OnInit, OnDestroy {
|
|
275
|
+
static [LIFECYCLE] = true;
|
|
276
|
+
|
|
277
|
+
private _timer?: NodeJS.Timeout;
|
|
278
|
+
|
|
279
|
+
async onInit(): Promise<void> {
|
|
280
|
+
await this.refresh();
|
|
281
|
+
this._timer = setInterval(() => this.refresh(), 60_000);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async onDestroy(): Promise<void> {
|
|
285
|
+
clearInterval(this._timer);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
private async refresh(): Promise<void> {
|
|
289
|
+
// Load the current rates
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
define(ExchangeRates);
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
- The hooks of one kind run in parallel for every class, with no order between them, so a hook must not rely on the
|
|
297
|
+
same hook of another class having finished.
|
|
298
|
+
- Only the classes defined before the application is created are collected: the ones defined in the files the
|
|
299
|
+
application loads on start (modules, resources and application files) or before `createApp()` is called.
|
|
300
|
+
- A class defined as a constructor is instantiated when the application is created, as the single instance every
|
|
301
|
+
`inject` call then returns.
|