@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.
@@ -0,0 +1,2238 @@
1
+ # Resources
2
+
3
+ Resources are the core building blocks of an Appweaver application. There are four resource types: **model**,
4
+ **service**, **routes**, and **policy**. A service depends on the model, routes on the service, and a policy only on the
5
+ model. Each resource type is created using a corresponding factory function and autoloaded from `src/resources/*/` on
6
+ application start. Source directory and resources pattern could be changed with `APP_SOURCE_PATH` and
7
+ `RESOURCE_{MODEL,SERVICE,...}_PATTERN` config variables.
8
+
9
+ - A **model** is always required.
10
+ - A **service** requires a model.
11
+ - The **Routes** require a service.
12
+ - A **policy** is optional and independent of the chain.
13
+
14
+ ---
15
+
16
+ ## createModel
17
+
18
+ Creates a resource model definition. The model defines database fields, relations, files, virtual fields, DTOs for CRUD
19
+ operations, and index configuration. It is used to generate Prisma schema, TypeScript types, and route request/response
20
+ schemas.
21
+
22
+ ```ts
23
+ import { createModel } from '@appweaver/data';
24
+
25
+ export default createModel({
26
+ name: 'Product'
27
+ // ... configuration
28
+ });
29
+ ```
30
+
31
+ ### Configuration
32
+
33
+ ```ts
34
+ function createModel(
35
+ config: ResourceModelConfig,
36
+ override?: boolean // replace the one defined for the model (default: false)
37
+ ) {}
38
+ ```
39
+
40
+ | Property | Type | Required | Default | Description |
41
+ |--------------------|--------------------------------|----------|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------|
42
+ | `name` | string | yes | - | Model name (PascalCase). Used as database table name and type name. |
43
+ | `tableName` | string | no | (model name) | Custom database table name override. |
44
+ | `generateTypes` | boolean | no | `true` | Generate TypeScript types for this model. |
45
+ | `generateDbSchema` | boolean | no | `true` | Generate Prisma schema for this model. |
46
+ | `id` | IdField | no | Autoincrement integer | ID field configuration. |
47
+ | `audit` | AuditFields | no | All included | Audit timestamps and creator tracking fields. |
48
+ | `scalars` | Record\<string, ScalarField> | no | - | Scalar fields (database columns). |
49
+ | `relations` | Record\<string, RelationField> | no | - | Relations to other models. |
50
+ | `files` | Record\<string, FileField> | no | - | File upload fields. |
51
+ | `virtual` | Record\<string, VirtualField> | no | - | Computed/virtual fields not stored in database. |
52
+ | `read` | OperationConfig | no | - | Pick/omit fields for the read DTO. |
53
+ | `create` | OperationConfig | no | - | Pick/omit fields for the create DTO. |
54
+ | `update` | UpdateOperationConfig | no | - | Pick/omit fields for the update and replace DTOs (PATCH and PUT), and the `operations` of numeric fields (`increment`, `decrement`). |
55
+ | `export` | Record\<string, ExportField> | no | - | CSV export field configuration. |
56
+ | `index` | string[] \| string[][] | no | - | Database index definitions (`-field` desc, `+field` asc). |
57
+ | `unique` | string[] \| string[][] | no | - | Composite unique constraints, in the same shape as `index`. |
58
+ | `softDelete` | boolean \| `{ purgeAfter }` | no | `false` | Mark deleted records instead of removing them, `purgeAfter` (a duration) removing them once deleted for it. |
59
+
60
+ The spatial fields are described in [spatial.md](./spatial.md#declaring-spatial-fields), the `series` fields and
61
+ `seriesOptions` in [timeseries.md](./timeseries.md#declaring-series-fields).
62
+
63
+ ### ID field
64
+
65
+ ```ts
66
+ const config = {
67
+ // Integer ID with autoincrement (default)
68
+ id: {
69
+ type: 'int',
70
+ generator: 'autoincrement()'
71
+ },
72
+
73
+ // String ID with generator
74
+ id: {
75
+ type: 'string',
76
+ generator: 'uuid()'
77
+ }
78
+ };
79
+ ```
80
+
81
+ | Property | Type | Default | Description |
82
+ |-------------|-----------------------------------------------------------------------------------------------|-----------------------------------------------|------------------------------------------------------|
83
+ | `type` | `'string'` \| `'int'` \| `'bigInt'` | `'int'` | ID field data type. |
84
+ | `generator` | `'uuid()'` \| `'uuid(7)'` \| `'cuid()'` \| `'cuid(2)'` \| `'nanoid()'` \| `'autoincrement()'` | `'autoincrement()'` (`'uuid()'` for `string`) | Value generator. String types use UUID/CUID/Nano ID. |
85
+
86
+ Declaring only a string generator (i.e. `{ generator: 'cuid()' }`) infers the `'string'` type.
87
+
88
+ #### String IDs
89
+
90
+ String IDs are generated on creation like auto-incrementing integers, so no value is sent. Both ID types can be mixed
91
+ across models in the same project, and the choice flows through everywhere the primary key appears:
92
+
93
+ | Where | Integer ID | String ID |
94
+ |--------------------------------|--------------------------|-----------------------------------------|
95
+ | Prisma column | `id Int @id` | `id String @id` |
96
+ | Generated TypeScript type | `id: number` | `id: string` |
97
+ | Route path parameter | `GET /posts/{id}` number | `GET /comments/{id}` string |
98
+ | Foreign key on a related model | `authorId Int` | `pinnedCommentId String` |
99
+ | Relation input | `{ author: 12 }` | `{ pinnedComment: 'k4pcxi0t5vs8rl65' }` |
100
+ | `createdById` audit column | `Int?` | `String?` (follows the auth model) |
101
+ | Service methods | `find(12)` | `find('k4pcxi0t5vs8rl65')` |
102
+
103
+ #### Generated column types
104
+
105
+ Generated string columns are sized after the value they hold, on the primary key, the foreign keys referencing it, and
106
+ any string scalar with a `defaultGenerator`. SQLite keeps the plain column.
107
+
108
+ | Generator | PostgreSQL | MySQL | SQL Server |
109
+ |---------------------|-------------------|-------------------|------------------------|
110
+ | `uuid()`, `uuid(7)` | `@db.Uuid` | `@db.Char(36)` | `@db.UniqueIdentifier` |
111
+ | `cuid()` | `@db.VarChar(25)` | `@db.VarChar(25)` | `@db.VarChar(25)` |
112
+ | `cuid(2)` | `@db.VarChar(24)` | `@db.VarChar(24)` | `@db.VarChar(24)` |
113
+ | `nanoid()` | `@db.VarChar(21)` | `@db.VarChar(21)` | `@db.VarChar(21)` |
114
+
115
+ The generator width wins over an explicit `maxLength`, which only bounds what the API accepts.
116
+
117
+ Service and hook signatures take `ResourceId` (`number | string`), so they work with either ID type:
118
+
119
+ ```ts
120
+ import { ResourceId } from '@appweaver/common';
121
+
122
+ export default createService({
123
+ modelName: 'Comment',
124
+ beforeFind: (id: ResourceId) => console.log('Finding comment', id)
125
+ });
126
+ ```
127
+
128
+ The `resourceId` column of the built-in `File` model stores the owning record ID as text, so files attach to resources
129
+ with either ID type.
130
+
131
+ > Changing the ID type of the existing model rewrites its primary key column and every foreign key pointing at it. Run
132
+ > `weaver generate` then `weaver migration new <name>`, and treat it as destructive on a populated database.
133
+
134
+ ### Audit fields
135
+
136
+ It is recommended to always use all audit fields for all resource models, unless specified otherwise. In the usual
137
+ scenario audit should be left out (including all fields by default).
138
+
139
+ ```ts
140
+ const config = {
141
+ // By default all audit fields are included
142
+ audit: {
143
+ createdAt: true,
144
+ updatedAt: true,
145
+ createdById: true
146
+ }
147
+ };
148
+ ```
149
+
150
+ | Property | Type | Default | Description |
151
+ |---------------|---------|---------|-------------------------------------------------|
152
+ | `createdAt` | boolean | `true` | Add `createdAt` timestamp field. |
153
+ | `updatedAt` | boolean | `true` | Add `updatedAt` timestamp field. |
154
+ | `createdById` | boolean | `true` | Add `createdById` foreign key to the auth user. |
155
+
156
+ ### Soft delete
157
+
158
+ A model with `softDelete` enabled keeps its deleted records in the database instead of removing them. The delete marks
159
+ the record with two extra columns. They are hidden fields: typed on the full generated model type (i.e. `Post`), so
160
+ server code can read them, but never part of any API request or response, nor of the OpenAPI document:
161
+
162
+ | Column | Type | Description |
163
+ |---------------|---------------------|------------------------------------------------------------------------|
164
+ | `deletedAt` | `DateTime?` | When the record was deleted, `null` for a live record. |
165
+ | `deletedById` | auth model id (`?`) | The user who deleted the record. Only added when an auth model exists. |
166
+
167
+ `deletedById` is indexed like any other foreign key, but `deletedAt` is not. Every read filters on `deletedAt IS NULL`,
168
+ so add the column to the indexes matching the queries of the model where it helps, i.e.
169
+ `index: [['deletedAt', '-createdAt', 'id']]` for the default listing.
170
+
171
+ ```ts
172
+ const config = {
173
+ softDelete: true
174
+ };
175
+ ```
176
+
177
+ The stored files of a soft deleted record are **kept** by default, so a manual restore loses nothing, while a record
178
+ removed from the database loses them by default. Each file field decides for itself with `onResourceSoftDeleted` and
179
+ `onResourceDeleted` (see [File fields](#file-fields)). A kept file is never served again, see
180
+ [Files of deleted resources](./storage.md#deleting-all-files-on-resource-deletion).
181
+
182
+ ```ts
183
+ const config = {
184
+ softDelete: true,
185
+ files: {
186
+ avatar: {}, // kept on soft delete, removed on a database delete
187
+ idScan: { onResourceSoftDeleted: 'delete' } // removed on both
188
+ }
189
+ };
190
+ ```
191
+
192
+ Soft deleted records are hidden from every read, so for API users a soft delete is indistinguishable from a real one:
193
+
194
+ - `find`, `update` and `delete` respond with 404, `query`, `aggregate` and `export` leave the record out.
195
+ - List relations and relation counts skip it, a single relation pointing at it reads as `null`.
196
+ - Relation filters never match through it: `_some`, `_none`, `_every` and `_exists` only consider live records, and a
197
+ `null` filter on a single relation matches a deleted related record.
198
+ - Connecting or inline updating it through a relation input is rejected with 400.
199
+ - Its files are served as missing, whether they were kept or removed.
200
+
201
+ Restoring a record, or reading the deleted ones, is not part of the API: set `deletedAt` and `deletedById` back to
202
+ `null` in the database, on the record, on the records soft deleted with it and on the `File` rows of its kept files,
203
+ which all share the same `deletedAt` value. Unique values of a deleted record stay taken until the row is removed.
204
+
205
+ The delete follows the `onDelete` action of every relation referencing the record, mirroring a database delete:
206
+
207
+ | `onDelete` of the referencing relation | On soft delete |
208
+ |-----------------------------------------------|---------------------------------------------------------------------------------------------|
209
+ | `cascade` | The referencing records are soft deleted with the same `deletedAt`, level by level. |
210
+ | `restrict`, `noAction` (default if required) | The delete fails with `RESOURCE_DELETE_RESTRICTED` (409) while a live record references it. |
211
+ | `setNull`, `setDefault` (default if optional) | The reference is kept, so a manual restore brings the link back. |
212
+
213
+ A soft delete never runs the database cascade, so every model a soft deleted model cascades into must enable
214
+ `softDelete` too. The application refuses to start and `weaver generate` fails otherwise:
215
+
216
+ ```
217
+ Model 'Comment' must enable 'softDelete', since its relation 'Comment.post' cascades on delete from the soft deleted model 'Post'.
218
+ ```
219
+
220
+ The framework owned `ApiKey` and `ConnectedAccount` models cascade from the auth model, so they enable `softDelete`
221
+ automatically when the auth model does.
222
+
223
+ After enabling `softDelete` on a model, regenerate the schema and create a migration (`weaver generate`, then
224
+ `weaver migration new <name>`).
225
+
226
+ ### Scalar field types
227
+
228
+ All scalar fields share these common properties:
229
+
230
+ | Property | Type | Default | Description |
231
+ |---------------------|-----------------------------|---------|------------------------------------------------------------------------------------------------------------------------------|
232
+ | `required` | boolean | `true` | Whether the field is required. |
233
+ | `unique` | boolean | `false` | Add a unique constraint. |
234
+ | `hidden` | boolean | `false` | Hide from API output (e.g. password hashes). |
235
+ | `redact` | boolean | `false` | Keep the values out of the audit log, a change recorded as `[Redacted]` (hidden fields always are, see `audit.md`). |
236
+ | `default` | varies | - | Default static value. |
237
+ | `defaultGenerator` | string | - | Default is generated by function (e.g. uuid(), cuid(), autoincrement(), now(), ...). |
238
+ | `defaultExpression` | string | - | Default is generated by database expression in supported database syntax (e.g. concat('token\_', gen_random_uuid()))::TEXT). |
239
+ | `array` | boolean | `false` | Store as array (supported on string, int, float). |
240
+ | `example` | string \| number \| boolean | - | Example value for OpenAPI (Swagger) schema documentation. |
241
+
242
+ A `default` must satisfy the constraints declared on its own field (`minimum`, `maximum`, `minLength`, `maxLength`,
243
+ `pattern`, enum `values`) and match its type. The application **refuses to start** otherwise, naming every offending
244
+ field.
245
+
246
+ #### String
247
+
248
+ ```ts
249
+ const config = {
250
+ title: {
251
+ type: 'string',
252
+ minLength: 1,
253
+ maxLength: 200,
254
+ default: 'No title'
255
+ },
256
+ email: {
257
+ type: 'string',
258
+ format: 'email'
259
+ },
260
+ slug: {
261
+ type: 'string',
262
+ pattern: '^[a-z0-9-]+$'
263
+ },
264
+ code: {
265
+ type: 'string',
266
+ defaultGenerator: 'uuid()'
267
+ }
268
+ };
269
+ ```
270
+
271
+ | Property | Type | Description |
272
+ |-------------|---------------------------------------------------------------------------------------|--------------------------------------|
273
+ | `type` | `'string'` | String field type. |
274
+ | `minLength` | number | Minimum string length. |
275
+ | `maxLength` | number | Maximum string length. |
276
+ | `format` | `'email'` \| `'hostname'` \| `'ipv4'` \| `'ipv6'` \| `'uri'` \| `'uuid'` \| `'regex'` | Built-in format validation. |
277
+ | `pattern` | string | Custom regex pattern for validation. |
278
+
279
+ String defaults can also be ID generators: `'uuid()'`, `'uuid(7)'`, `'cuid()'`, `'cuid(2)'`, `'nanoid()'`, which also
280
+ size the column (see [Generated column types](#generated-column-types)).
281
+
282
+ `maxLength` sizes the `VARCHAR` column on PostgreSQL and MySQL, and the `NVARCHAR` column on SQL Server, whose `VARCHAR`
283
+ holds no Unicode. A length beyond the longest one of the database is stored in its text type instead: `MEDIUMTEXT` above
284
+ 16,383 characters on MySQL, `NVARCHAR(MAX)` above 4,000 on SQL Server, and `TEXT` above 10,485,760 on PostgreSQL. SQLite
285
+ keeps the plain column.
286
+
287
+ #### Number (int, bigInt, float)
288
+
289
+ ```ts
290
+ const config = {
291
+ price: {
292
+ type: 'float',
293
+ minimum: 0
294
+ },
295
+ quantity: {
296
+ type: 'int',
297
+ minimum: 0,
298
+ maximum: 10000
299
+ }
300
+ };
301
+ ```
302
+
303
+ | Property | Type | Description |
304
+ |-----------|------------------------------------|--------------------|
305
+ | `type` | `'int'` \| `'bigInt'` \| `'float'` | Number field type. |
306
+ | `minimum` | number | Minimum value. |
307
+ | `maximum` | number | Maximum value. |
308
+
309
+ Integer defaults can be `'autoincrement()'`.
310
+
311
+ #### Boolean
312
+
313
+ ```ts
314
+ const config = {
315
+ enabled: {
316
+ type: 'boolean',
317
+ default: true
318
+ }
319
+ };
320
+ ```
321
+
322
+ | Property | Type | Description |
323
+ |----------|-------------|---------------------|
324
+ | `type` | `'boolean'` | Boolean field type. |
325
+
326
+ #### DateTime
327
+
328
+ ```ts
329
+ const config = {
330
+ publishedAt: {
331
+ type: 'dateTime',
332
+ defaultGenerator: 'now()'
333
+ },
334
+ eventDate: {
335
+ type: 'dateTime',
336
+ format: 'date'
337
+ }
338
+ };
339
+ ```
340
+
341
+ | Property | Type | Description |
342
+ |----------|---------------------------------------|----------------------|
343
+ | `type` | `'dateTime'` | DateTime field type. |
344
+ | `format` | `'date-time'` \| `'time'` \| `'date'` | DateTime format. |
345
+
346
+ Default can be `'now()'` for current timestamp.
347
+
348
+ #### JSON
349
+
350
+ ```ts
351
+ const config = {
352
+ metadata: {
353
+ type: 'json',
354
+ default: {}
355
+ }
356
+ };
357
+ ```
358
+
359
+ | Property | Type | Description |
360
+ |----------|----------|------------------------------------------------------|
361
+ | `type` | `'json'` | JSON field type. Stores arbitrary objects or arrays. |
362
+
363
+ On SQLite the default is written to the schema as the quoted SQL literal (`@default(dbgenerated("'{}'"))`), since the
364
+ migrations of Prisma would write a plain `@default("{}")` unquoted, which SQLite rejects.
365
+
366
+ SQL Server has no JSON type, so the field is an `NVARCHAR(MAX)` column holding the serialized value, which the data
367
+ layer
368
+ serializes on every write and parses in every result, the included relations too. Its Prisma client type is `string`,
369
+ and the JSON filters of Prisma (`path`, `array_contains`, ...) are not available on it.
370
+
371
+ #### Enum
372
+
373
+ ```ts
374
+ const config = {
375
+ status: {
376
+ type: 'enum',
377
+ values: ['Draft', 'Active', 'Sold'],
378
+ default: 'Draft'
379
+ }
380
+ };
381
+ ```
382
+
383
+ | Property | Type | Description |
384
+ |----------|----------|---------------------------------|
385
+ | `type` | `'enum'` | Enum field type. |
386
+ | `values` | string[] | Allowed enum values (required). |
387
+
388
+ SQL Server has no enums, so the field is an `NVARCHAR` column sized to the longest value, the values still validated by
389
+ the API. Its Prisma client type is `string`.
390
+
391
+ ### Relations
392
+
393
+ ```ts
394
+ // src/resources/product/model.ts
395
+ const config = {
396
+ relations: {
397
+ category: {
398
+ model: 'Category',
399
+ type: 'manyToOne',
400
+ mappedBy: 'products',
401
+ output: {
402
+ type: 'always'
403
+ }
404
+ },
405
+ reviews: {
406
+ model: 'Review',
407
+ type: 'oneToMany',
408
+ mappedBy: 'product',
409
+ output: {
410
+ type: 'single',
411
+ count: true
412
+ }
413
+ }
414
+ }
415
+ };
416
+ ```
417
+
418
+ ```ts
419
+ // src/resources/category/model.ts
420
+ const config = {
421
+ relations: {
422
+ products: {
423
+ model: 'Product',
424
+ type: 'oneToMany',
425
+ mappedBy: 'category',
426
+ output: {
427
+ type: 'single'
428
+ }
429
+ }
430
+ }
431
+ };
432
+ ```
433
+
434
+ ```ts
435
+ // src/resources/review/model.ts
436
+ const config = {
437
+ relations: {
438
+ product: {
439
+ model: 'Product',
440
+ type: 'manyToOne',
441
+ mappedBy: 'reviews',
442
+ input: {
443
+ type: 'none'
444
+ }
445
+ }
446
+ }
447
+ };
448
+ ```
449
+
450
+ | Property | Type | Default | Description |
451
+ |-----------------|-------------------|--------------|--------------------------------------------------------------------------|
452
+ | `model` | string | **required** | Target model name. |
453
+ | `type` | RelationType | **required** | `'oneToOne'`, `'oneToMany'`, `'manyToOne'`, or `'manyToMany'`. |
454
+ | `owner` | boolean | `false` | This side owns the foreign key column (implied by `manyToOne`). |
455
+ | `mappedBy` | string | - | Name of the inverse relation on the target model. |
456
+ | `required` | boolean | `true` | Whether the relation is required (nullable foreign key if not required). |
457
+ | `minItems` | number | - | Minimum items for list relations. |
458
+ | `orphanRemoval` | boolean | `false` | Delete the related records an update removes from the relation. |
459
+ | `onDelete` | ReferentialAction | - | Foreign key action on delete. |
460
+ | `onUpdate` | ReferentialAction | - | Foreign key action on update. |
461
+ | `index` | boolean | `true` | Index the foreign key column; `false` leaves it unindexed. |
462
+ | `input` | RelationInput | - | Input DTO configuration. |
463
+ | `output` | RelationOutput | - | Output DTO configuration. |
464
+
465
+ **ReferentialAction values**: `'cascade'`, `'restrict'`, `'noAction'`, `'setNull'`, `'setDefault'`
466
+
467
+ Without an explicit `onDelete`, a **required** owning relation falls back to `restrict`, so deleting the referenced
468
+ record fails with a foreign key violation while any child row still exists. Set `onDelete: 'cascade'` on relations whose
469
+ rows are owned by the parent and meaningless without it. Optional owning relations (`required: false`) fall back to
470
+ `setNull`, which already lets the referenced record be deleted.
471
+
472
+ The stored files of the records a `cascade` removes are cleaned up together with the files of the deleted record. A
473
+ model with soft delete applies the same actions itself, see its section.
474
+
475
+ SQL Server rejects a referential action forming a cycle or a second path of actions between two tables, i.e. a self
476
+ relation, or two relations from the same table. `weaver generate` then writes `onDelete: NoAction, onUpdate: NoAction`
477
+ on the foreign keys whose action would form one, always on the `createdBy` and `deletedBy` relations to the auth model,
478
+ and keeps the declared actions before the implicit `setNull` ones, in the order of the models and their fields. The
479
+ actions on update are `NoAction` unless declared, since the ids never change. A `cascade` or `setNull` the database
480
+ leaves out is applied by the data layer before every `delete` and `deleteMany` of the referenced records, in their
481
+ transaction, so the deletes behave as on the other databases, except for a nested `delete` of an update
482
+ (`orphanRemoval`), which only the database actions follow.
483
+
484
+ With `orphanRemoval: true`, an update deletes the related records it removes from the relation instead of only
485
+ disconnecting them. The orphans are deleted like any other record: their stored files are removed following
486
+ `onResourceDeleted` and the records cascading from them are removed too. Orphans of a model with `softDelete` enabled
487
+ are soft deleted instead, keep their
488
+ references for a manual restore, and keep their files unless a field sets `onResourceSoftDeleted: 'delete'`.
489
+
490
+ #### Relationship types
491
+
492
+ The `type` property declares the relation cardinality explicitly, and `owner` marks the side that holds the foreign key
493
+ column in the generated table:
494
+
495
+ **One-to-One** (`type: 'oneToOne'`): Both sides reference a single record. The side with `owner: true` holds a unique
496
+ foreign key; the inverse side is always optional.
497
+
498
+ ```ts
499
+ // User model
500
+ const config = {
501
+ relations: {
502
+ profile: {
503
+ model: 'Profile',
504
+ type: 'oneToOne',
505
+ mappedBy: 'user',
506
+ owner: true,
507
+ required: false // otherwise the Profile DTO must be sent when creating the user resource
508
+ }
509
+ }
510
+ };
511
+ ```
512
+
513
+ ```ts
514
+ // Profile model
515
+ const config = {
516
+ relations: {
517
+ user: {
518
+ model: 'User',
519
+ type: 'oneToOne',
520
+ mappedBy: 'profile'
521
+ }
522
+ }
523
+ };
524
+ ```
525
+
526
+ **One-to-Many** (`type: 'oneToMany'` and `type: 'manyToOne'`): The "many" side holds the foreign key and references a
527
+ single record, declared as `manyToOne`; the "one" side holds a list of related records, declared as `oneToMany`. A
528
+ `manyToOne` relation is the same as a `oneToMany` relation with `owner: true`, which is still accepted.
529
+
530
+ ```ts
531
+ // Category model (one, list side)
532
+ const config = {
533
+ relations: {
534
+ products: {
535
+ model: 'Product',
536
+ type: 'oneToMany',
537
+ mappedBy: 'category'
538
+ }
539
+ }
540
+ };
541
+ ```
542
+
543
+ ```ts
544
+ // Product model (many, foreign key side)
545
+ const config = {
546
+ relations: {
547
+ category: {
548
+ model: 'Category',
549
+ type: 'manyToOne',
550
+ mappedBy: 'products'
551
+ }
552
+ }
553
+ };
554
+ ```
555
+
556
+ **Many-to-Many** (`type: 'manyToMany'`): Both sides hold lists of related records, joined through an implicit join
557
+ table. The `owner` property has no effect on this relation type.
558
+
559
+ ```ts
560
+ // Post model
561
+ const config = {
562
+ relations: {
563
+ tags: {
564
+ model: 'Tag',
565
+ type: 'manyToMany',
566
+ mappedBy: 'posts'
567
+ }
568
+ }
569
+ };
570
+ ```
571
+
572
+ ```ts
573
+ // Tag model
574
+ const config = {
575
+ relations: {
576
+ posts: {
577
+ model: 'Post',
578
+ type: 'manyToMany',
579
+ mappedBy: 'tags'
580
+ }
581
+ }
582
+ };
583
+ ```
584
+
585
+ #### Relation pair validation
586
+
587
+ `weaver generate` validates every bidirectional relation pair linked through `mappedBy` and fails schema generation with
588
+ a descriptive error when the two sides are inconsistent:
589
+
590
+ - Both sides must declare the same relation `type`, where a `manyToOne` side pairs with a `oneToMany` side.
591
+ - The mapped relation must reference the declaring model back via its `model` property.
592
+ - For `oneToOne` and `oneToMany` relations, exactly one side must declare `owner: true` (neither or both is an error).
593
+
594
+ A relation whose `mappedBy` field does not exist on the target model is treated as single-sided and skipped by the
595
+ validation; an inverse field is generated automatically in the Prisma schema.
596
+
597
+ #### Relation input
598
+
599
+ | Property | Type | Description |
600
+ |---------------|-------------------------------------------------|-------------------------------------------------------------------------------------------------------|
601
+ | `type` | `'all'` \| `'create'` \| `'update'` \| `'none'` | When the relation field is available as input. |
602
+ | `allowCreate` | boolean | Allow creating related records inline (input objects without an `id`). |
603
+ | `allowUpdate` | boolean | Allow updating related records inline on parent update requests (input objects with a required `id`). |
604
+ | `uniqueKey` | string | Unique field matching existing records, turning an inline create into a connect-or-create. |
605
+
606
+ Both flags are off by default: a relation only connects existing records unless `allowCreate` / `allowUpdate` is set.
607
+
608
+ By default, a relation input only connects existing records. It accepts an id value, an `{ id }` object, or an array of
609
+ either for list relations. The `allowCreate` and `allowUpdate` flags also accept the related model's own data:
610
+
611
+ - **`allowCreate: true`** — input objects **without** an `id` create the related record inline. The accepted fields are
612
+ the related model's create data, without its own relations and files (`<Model>RelationCreate`).
613
+ - **`allowUpdate: true`** — input objects **with** an `id` and further fields update the related record inline
614
+ (`<Model>RelationUpdate`). Objects carrying only an `id` are connected instead. This applies to parent **update**
615
+ requests only. On parent **create** requests an object with an `id` connects the record and carries no other field,
616
+ since the database updates relations only within an update action.
617
+
618
+ Each relation item is validated against the exact shapes the relation accepts for the action: a bare id, an `{ id }`
619
+ object (or `<Model>RelationUpdate` when inline updates apply), and `<Model>RelationCreate` when inline creation is
620
+ enabled. The presence of the `id` tells an inline update from an inline create. A field the matched shape does not
621
+ accept is rejected with a `400` `VALIDATION_FAILED` error naming it, i.e. a create-only field sent with an `id`
622
+ (`posts.0.slug` "is not allowed"), and so is a missing required create field (`posts.0.slug` "is required"). A
623
+ service called directly applies the same rules, throwing `RESOURCE_INVALID_RELATION` with the `unknownFields` or the
624
+ `missingFields` of the payload.
625
+
626
+ Connect, create, and update inputs can be mixed within one list relation request:
627
+
628
+ ```ts
629
+ // PATCH /api/users/1
630
+ {
631
+ posts: [
632
+ 5, // connect post 5 by id
633
+ { id: 7, title: 'Renamed' }, // update post 7 inline
634
+ { title: 'Fresh post', slug: 'new' } // create a new post inline
635
+ ];
636
+ }
637
+ ```
638
+
639
+ Records without an `id` require `allowCreate: true`. Otherwise, the request fails with a `400` error and the related
640
+ record has to be created through its own endpoint first. With `allowCreate` set, a `uniqueKey` matches an existing
641
+ record by that field before creating a new one, so the inline create becomes a connect-or-create. Without
642
+ `allowCreate` the `uniqueKey` has no effect. Plain connect and inline update always match related records by `id`,
643
+ so a bare value is an id on a relation with a `uniqueKey` too (`tags: [1, { name: 'Forests', slug: 'forests' }]`), and
644
+ an update keeps the current records the new value names by id or by unique key.
645
+
646
+ #### Relation output
647
+
648
+ | Property | Type | Description |
649
+ |------------|------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
650
+ | `type` | `'always'` \| `'single'` \| `'multiple'` \| `'none'` | When to include the relation in output. `always` = all reads, `single` = single record reads, `multiple` = list reads, `none` = never. |
651
+ | `include` | Record\<string, RelationOutput> | Nested relation output configuration. |
652
+ | `maxDepth` | number | Levels of a relation pointing back at its own model. Default `1`. |
653
+ | `count` | boolean | Include a count of related records. |
654
+ | `omit` | string[] | Fields of the related model left out of this relation only. Not in a nested `include`. |
655
+
656
+ A relation is typed as the related model's `<Model>Single`, so a nested record carries its own relations again and a
657
+ self-reference recurses. The schema says what a response can hold, the config how deep one is read.
658
+
659
+ A relation pointing back at its own model is read one level deep like any other, and `maxDepth` repeats it down the
660
+ tree, counting the relation itself as the first level. An `include` naming that same relation replaces the repetition;
661
+ any other `include` is applied at every level. Each level is a database join, cheap on a to-one relation such as
662
+ `parent` and expensive on a list one such as `children`.
663
+
664
+ ```ts
665
+ const config = {
666
+ relations: {
667
+ // A category response carries three levels of ancestors
668
+ parent: {
669
+ model: 'Category',
670
+ type: 'manyToOne',
671
+ mappedBy: 'children',
672
+ required: false,
673
+ output: { type: 'always', maxDepth: 3 }
674
+ },
675
+ // Kept out of the response, counted as childrenCount instead
676
+ children: {
677
+ model: 'Category',
678
+ type: 'oneToMany',
679
+ mappedBy: 'parent',
680
+ output: { type: 'none', count: true }
681
+ }
682
+ }
683
+ };
684
+ ```
685
+
686
+ `omit` hides fields of the related model in this relation only (routes, MCP tools, realtime events), while its own
687
+ routes keep them; an unknown name fails the startup. A field to hide everywhere is `hidden` instead. The omitted fields
688
+ can neither be filtered nor sorted on through the relation (the filter of the relation is its own
689
+ `<Model><Relation>RelationQueryFilter` schema, i.e. `PostAuthorRelationQueryFilter`), or their values could be guessed
690
+ one condition at a time.
691
+
692
+ ```ts
693
+ // The author of a public post, without the contact details
694
+ const config = {
695
+ author: {
696
+ model: 'User',
697
+ type: 'manyToOne',
698
+ mappedBy: 'posts',
699
+ output: {
700
+ type: 'always',
701
+ omit: ['email', 'phone']
702
+ }
703
+ }
704
+ };
705
+ ```
706
+
707
+ A nested `include` entry carries its own `maxDepth`, applied to the model that entry belongs to:
708
+
709
+ ```ts
710
+ // A post reads its category with the breadcrumb above it
711
+ const config = {
712
+ category: {
713
+ model: 'Category',
714
+ type: 'manyToOne',
715
+ mappedBy: 'posts',
716
+ output: {
717
+ type: 'always',
718
+ include: { parent: { type: 'always', maxDepth: 3 } }
719
+ }
720
+ }
721
+ };
722
+ ```
723
+
724
+ ### File fields
725
+
726
+ The files are saved by `FileService` in the `Storage` provider, see [storage.md](./storage.md#fileservice-usage).
727
+
728
+ ```ts
729
+ const config = {
730
+ files: {
731
+ photo: {
732
+ mimeType: 'image/*',
733
+ namePattern: 'photos/{userId}-{name}-{hash}.{extension}',
734
+ maxSize: '2 MB',
735
+ image: {
736
+ quality: 80,
737
+ maxWidth: 1200,
738
+ maxHeight: 1200,
739
+ fit: 'inside'
740
+ }
741
+ },
742
+ documents: {
743
+ mimeType: 'application/pdf',
744
+ array: true,
745
+ maxCount: 5
746
+ }
747
+ }
748
+ };
749
+ ```
750
+
751
+ | Property | Type | Description |
752
+ |-------------------------|------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
753
+ | `mimeType` | string \| RegExp | Allowed MIME types (glob patterns like `'image/*'` supported). |
754
+ | `namePattern` | string \| function | File naming pattern or function (available variables are listed below). |
755
+ | `array` | boolean | Allow multiple files. |
756
+ | `maxSize` | number \| string | Maximum file size (e.g. `'2 MB'`, `5242880`). |
757
+ | `maxCount` | number | Maximum number of files (for array fields). |
758
+ | `output` | RelationOutput | When to include file info in output, and its count. Takes no `include` or `maxDepth`. |
759
+ | `onResourceDeleted` | `'delete'` \| `'keep'` | When the owning resource is removed from the database, also by a cascade or an orphan removal. `'delete'` (default) removes files from storage, `'keep'` retains them without serving them. |
760
+ | `onResourceSoftDeleted` | `'delete'` \| `'keep'` | When the owning resource is soft deleted (see `softDelete`). `'keep'` (default) retains files for a manual restore without serving them, `'delete'` removes them from storage. |
761
+ | `image` | ImageConfig | Image compression and resize settings. Only applies to image MIME types (excluding GIF). |
762
+ | `versions` | false \| object | Previous versions kept with `storage.versions.enabled`, `false` for none, `{ maxCount, maxAge }` overriding the config ([File versions](./storage.md#file-versions)). |
763
+
764
+ The first bytes of an upload are checked against its declared type for a content a browser could run: an HTML page or
765
+ an SVG image declared as anything else (`image/png`, `text/plain`, `application/xml`), or a Windows or ELF executable
766
+ declared as anything but an executable, is rejected with `FILE_UNSUPPORTED_TYPE`. Any other content keeps its declared
767
+ type, under its usual name (`image/jpg` as `image/jpeg`, `audio/x-wav` as `audio/wav`, `audio/mp3` as `audio/mpeg`),
768
+ whether its first bytes show that type, another harmless one or none (an MP3 without an ID3 tag, a WebM declared
769
+ `audio/webm`). A text type (`text/*`, JSON, XML, CSV) is checked for markup only, so a CSV starting with `BM` is never
770
+ taken for a BMP image. A declared `application/octet-stream` takes the type its content shows. The `mimeType` of the
771
+ field is checked against the stored type.
772
+
773
+ #### Available namePattern variables
774
+
775
+ Default pattern is: `{name}-{hash}.{extension}`.
776
+
777
+ | Variable | Type | Description |
778
+ |-----------------|--------|---------------------------------------------|
779
+ | `name` | string | Original filename without extension. |
780
+ | `extension` | string | Original file extension. |
781
+ | `resourceField` | string | Field name the file is assigned to. |
782
+ | `resourceName` | string | Resource model name. |
783
+ | `resourceId` | string | Resource ID. |
784
+ | `userId` | string | Authenticated user ID. |
785
+ | `userEmail` | string | Authenticated user email. |
786
+ | `year` | number | Current UTC year. |
787
+ | `month` | number | Current UTC month (1-12). |
788
+ | `day` | number | Current UTC day of month. |
789
+ | `weekDay` | number | Current UTC day of week (0-6, Sunday is 0). |
790
+ | `yearWeek` | number | ISO week number. |
791
+ | `yearDay` | number | Day of year (1-366). |
792
+ | `hours` | number | Current UTC hours. |
793
+ | `minutes` | number | Current UTC minutes. |
794
+ | `seconds` | number | Current UTC seconds. |
795
+ | `milliseconds` | number | Current UTC milliseconds. |
796
+ | `timestamp` | number | Unix timestamp in milliseconds. |
797
+ | `date` | string | Current date in ISO 8601 format. |
798
+ | `uuid` | string | Generated random UUID. |
799
+ | `hash` | string | Generated random hash (32 bytes). |
800
+
801
+ #### Image compression
802
+
803
+ Configure automatic image compression and resizing by adding the `image` property to a file field. Processing only
804
+ applies to supported image MIME types: `image/jpeg`, `image/png`, `image/webp`, `image/avif`, `image/tiff`. GIF files
805
+ are passed through unchanged.
806
+
807
+ | Property | Type | Description |
808
+ |-------------|----------|----------------------------------------------------------------------------------------------------------------|
809
+ | `quality` | number | Compression quality (1-100). Applies to JPEG, PNG, WebP, AVIF, and TIFF. |
810
+ | `width` | number | Exact resize width in pixels. |
811
+ | `height` | number | Exact resize height in pixels. |
812
+ | `maxWidth` | number | Maximum width. Only downscales if the image exceeds this dimension. |
813
+ | `maxHeight` | number | Maximum height. Only downscales if the image exceeds this dimension. |
814
+ | `fit` | ImageFit | How the image fits the target dimensions: `'inside'` (default), `'contain'`, `'cover'`, `'fill'`, `'outside'`. |
815
+
816
+ `width`/`height` take precedence over `maxWidth`/`maxHeight`. When using `maxWidth`/`maxHeight`, images smaller than the
817
+ specified dimensions are not enlarged.
818
+
819
+ ```ts
820
+ // Compress and limit dimensions
821
+ const config = {
822
+ files: {
823
+ avatar: {
824
+ mimeType: 'image/*',
825
+ maxSize: '5 MB',
826
+ image: { quality: 80, maxWidth: 800, maxHeight: 800 }
827
+ }
828
+ }
829
+ };
830
+ ```
831
+
832
+ ```ts
833
+ // Exact resize for thumbnails
834
+ const config = {
835
+ files: {
836
+ thumbnail: {
837
+ mimeType: 'image/jpeg',
838
+ image: { quality: 70, width: 200, height: 200, fit: 'inside' }
839
+ }
840
+ }
841
+ };
842
+ ```
843
+
844
+ ### Virtual fields
845
+
846
+ Virtual fields are computed values not stored in the database. They can appear in input DTOs (to receive data) and/or
847
+ output DTOs (to return computed values).
848
+
849
+ ```ts
850
+ const config = {
851
+ virtual: {
852
+ displayName: {
853
+ type: 'string',
854
+ output: {
855
+ type: 'always',
856
+ value: (resource) => `${resource.firstName} ${resource.lastName}`
857
+ }
858
+ },
859
+ inviteCode: {
860
+ type: 'string',
861
+ input: {
862
+ type: 'create'
863
+ }
864
+ }
865
+ }
866
+ };
867
+ ```
868
+
869
+ | Property | Type | Description |
870
+ |------------------|------------------------------------------------------|------------------------------------------------------------|
871
+ | _(scalar props)_ | - | All scalar field properties (type, minLength, etc.) apply. |
872
+ | `input.type` | `'all'` \| `'create'` \| `'update'` \| `'none'` | When the virtual field accepts input. |
873
+ | `input.value` | primitive \| function | Default value or transformer for input. |
874
+ | `output.type` | `'always'` \| `'single'` \| `'multiple'` \| `'none'` | When the virtual field appears in output. |
875
+ | `output.value` | primitive \| function | Computed value or transformer for output. |
876
+
877
+ Virtual output values are applied automatically to responses of resource CRUD routes (including nested relation and file
878
+ objects) and to responses of custom `registerRoute` routes whose 2xx response schemas reference resource output models.
879
+ To apply them manually on a raw resource object (e.g. one fetched directly through a Prisma client), use the
880
+ `projectVirtualFields` helper:
881
+
882
+ ```ts
883
+ import { projectVirtualFields } from '@appweaver/data';
884
+
885
+ const projected = projectVirtualFields(post, 'Post'); // sets virtual values, recursing into relations and files
886
+ ```
887
+
888
+ The nested records are projected before the record itself, so an `output.value` function reads the virtual fields of
889
+ its relations. The projection of a model is compiled once, on its first use.
890
+
891
+ ### Operation config (read, create, update)
892
+
893
+ Control which fields appear in each DTO. Use `pick` for an allowlist or `omit` for a deny-list.
894
+
895
+ ```ts
896
+ const config = {
897
+ create: {
898
+ omit: ['status'] // All fields except status
899
+ },
900
+ update: {
901
+ pick: ['title', 'price'] // Only title and price
902
+ }
903
+ };
904
+ ```
905
+
906
+ | Property | Type | Description |
907
+ |----------|----------|------------------------------------------------|
908
+ | `omit` | string[] | Fields to exclude from the DTO. |
909
+ | `pick` | string[] | Fields to include in the DTO (overrides omit). |
910
+
911
+ `read` shapes the output of every read (`<Model>Single` and `<Model>Multiple`), `create` the `<Model>Create` input,
912
+ and `update` both `<Model>Update` (`PATCH`) and `<Model>Replace` (`PUT`), so the two update routes always accept the
913
+ same fields. The same holds for the `input: { type: 'update' }` of a relation or a virtual field, which `PUT` accepts
914
+ too. There is no separate replace config: the routes differ only by what an omitted field means (see
915
+ [update routes](#update-routes-update-replace)).
916
+
917
+ A create or update request sending a field its DTO excludes is rejected with a `400` `VALIDATION_FAILED` error naming
918
+ the field (`rule: "additionalProperties"`).
919
+
920
+ #### Increment and decrement
921
+
922
+ `update.operations` lets a numeric scalar (`int`, `bigInt`, `float`) of the update input be raised or lowered
923
+ atomically by the database, so two concurrent updates never lose one another:
924
+
925
+ ```ts
926
+ update: {
927
+ omit: ['uid'],
928
+ operations: {
929
+ viewCount: ['increment'], // only `{ viewCount: { increment: 1 } }`, never a value
930
+ stock: ['set', 'increment', 'decrement'] // a value, or `{ stock: { decrement: 2 } }`
931
+ }
932
+ }
933
+ ```
934
+
935
+ A field left out accepts `set` only, its value. The amount is a positive number (an integer for `int` and `bigInt`),
936
+ at most the range of the field (`maximum - minimum`) when it declares both, else the largest value of its type
937
+ (2147483647 for `int`, `Number.MAX_SAFE_INTEGER` for `bigInt`); the `minimum` and `maximum` of the field are not
938
+ checked against the result. A field without `set` is left out of
939
+ the `<Model>Replace` input (`PUT`). A service call takes the same form,
940
+ `injectService('Post').update(id, { viewCount: { increment: 1 } })`, and the hooks receive it as sent.
941
+
942
+ ### Views
943
+
944
+ A model declares named views, each a narrower projection for one audience: the fields it reads (within the `read` of
945
+ the model, `audit: false` leaving the audit fields out) and the fields it writes (within its `create` and `update`),
946
+ with their write operations. A view only removes fields, never adds them. The model itself is the full shape. The
947
+ `write.operations` of a view name fields it writes, among the operations the `update.operations` of the model allow
948
+ them (a field the model leaves out accepts any), so a view cannot `set` a field the model only increments.
949
+
950
+ ```ts
951
+ export default createModel({
952
+ name: 'Post',
953
+ scalars: { /* defined once */ },
954
+ views: {
955
+ public: {
956
+ read: { omit: ['seo', 'status'], audit: false },
957
+ write: { pick: ['viewCount'], operations: { viewCount: ['increment'] } }
958
+ }
959
+ }
960
+ });
961
+ ```
962
+
963
+ A view has the schemas of the model under its own names (`PostPublic`, `PostPublicSingle`, `PostPublicCreate`,
964
+ `PostPublicQueryFilter`, ...), and `weaver generate` writes its types (`PostPublic`, `PostPublicUpdate`,
965
+ `PostPublicQuery`, `PostPublicSort`). The application fails to start when one of these names is taken by a model
966
+ (`PostPublic`), another view or a schema of the model (a view named `single` and `PostSingle`). What binds to it:
967
+
968
+ - **Routes**: `createRoutes({ modelName: 'Post', view: 'public', ... })` registers routes of their own (at
969
+ `public/posts` unless `path` is set) answering the shape of the view, taking only the fields it writes, and
970
+ filtering and sorting only by the fields it reads. They are a resource of their own in the OpenAPI document and the
971
+ generated client. Their resource events stay on the routes of the model (`events` is refused on a view).
972
+ - **Policy**: `createPolicy({ modelName: 'Post', view: 'public', readRestrictions, checkAccess, writeRestrictions })`
973
+ applies on the calls through the view beside the policy of the model: both read restrictions apply, both access
974
+ checks must allow, the write restrictions of both apply, those of the model winning on a field both set. In code,
975
+ `runInView('Post', 'public', () => service.query(...))` of `@appweaver/data` calls the service of the model through
976
+ a view, and `currentView('Post')` tells the view of the current call of the model: a call of another model it makes,
977
+ i.e. in a hook, runs outside of the view.
978
+ - **Relations**: `output: { type: 'always', view: 'public' }` reads the related record through a view of its model,
979
+ i.e. the public view of the author of a post, instead of listing the fields to `omit`; the filter and the sort of
980
+ the relation are the ones of the view (`author.email` is refused when the view leaves `email` out), and the
981
+ `readRestrictions` of the policy of the view restrict the related records beside those of the model. A call through a
982
+ view (its routes, its MCP tools, `runInView`) sorts by the fields the view reads only, while the default sort of
983
+ the service (`-createdAt`) still applies.
984
+ - **MCP**: the `mcp` of the routes of a view exposes tools of their own (`post_public_find`), reading its shape,
985
+ filtering, sorting and aggregating by the fields it reads, and calling through it.
986
+ - **Aggregates**: a call through a view aggregates the fields it reads and ranges over its date fields only
987
+ (`dateField`, the default `createdAt` included once `from`, `to` or `interval` is given).
988
+ - **Export**: the `export` route of a view reads every batch through it and writes the columns of its shape, and an
989
+ export of any model writes a relation in the shape its `output.view` or `omit` gives it, like the responses.
990
+
991
+ ### Export config
992
+
993
+ Configure CSV export behavior per field:
994
+
995
+ ```ts
996
+ const config = {
997
+ export: {
998
+ price: {
999
+ headerName: 'Product Price',
1000
+ mapValue: 'price'
1001
+ },
1002
+ internalNotes: {
1003
+ exclude: true
1004
+ },
1005
+ status: {
1006
+ mapValue: (val) => val.toUpperCase()
1007
+ },
1008
+ author: {
1009
+ firstName: {
1010
+ headerName: 'Given Name'
1011
+ },
1012
+ lastName: {
1013
+ headerName: 'Family Name'
1014
+ }
1015
+ }
1016
+ }
1017
+ };
1018
+ ```
1019
+
1020
+ | Property | Type | Description |
1021
+ |--------------|--------------------|------------------------------------|
1022
+ | `headerName` | string | Custom CSV column header name. |
1023
+ | `exclude` | boolean | Exclude this field from exports. |
1024
+ | `mapValue` | string \| function | Transform the value during export. |
1025
+
1026
+ A `string` `mapValue` names the field to read the column value from. On a relation or file field it is read off the
1027
+ related record (and off every item for array relations, joined with `,`); on a scalar field it is read off the exported
1028
+ record itself. A function `mapValue` receives the field value (or each item of an array field) and returns the column
1029
+ value.
1030
+
1031
+ Hidden fields and virtual fields with `output: { type: 'none' }` are never exported, nested in a relation either. A
1032
+ relation without a `mapValue` writes one column per field of the related record. An array of plain values is joined
1033
+ with `export.csvJoinDelimiter`. A text cell a spreadsheet would run as a formula (starting with `=`, `+`, `-`, `@`, a
1034
+ tab or a carriage return) is prefixed with `'`, numeric text such as a phone number excepted
1035
+ (`export.csvEscapeFormulas`, on by default).
1036
+
1037
+ ### Index config
1038
+
1039
+ Define database indexes as a flat array (single-field indexes) or nested arrays (composite indexes):
1040
+
1041
+ ```ts
1042
+ index: ['title']; // Single-field index on title
1043
+ index: [['status', 'categoryId']]; // Composite index on status + categoryId
1044
+ index: ['email', ['status', 'createdAt']]; // Both single and composite
1045
+ ```
1046
+
1047
+ Prefix a field name with `-` for a descending index or `+` for an ascending one. Without a prefix the database default
1048
+ order is used:
1049
+
1050
+ ```ts
1051
+ index: ['-createdAt']; // @@index(createdAt(sort: Desc))
1052
+ index: ['+title']; // @@index(title(sort: Asc))
1053
+ index: [['status', '-createdAt']]; // @@index([status, createdAt(sort: Desc)])
1054
+ ```
1055
+
1056
+ The prefix is part of the index identity, so `['createdAt', '-createdAt']` emits two separate indexes.
1057
+
1058
+ An entry can also be a definition with options:
1059
+
1060
+ ```ts
1061
+ index: [
1062
+ { fields: ['title'], type: 'gin', ops: 'gin_trgm_ops' }, // @@index([title(ops: raw("gin_trgm_ops"))], type: Gin)
1063
+ { fields: ['-publishedAt'], where: `"status" = 'Published'` }, // a partial index
1064
+ { expression: 'lower("email")', name: 'User_email_lower_idx' } // an expression index
1065
+ ];
1066
+ unique: [{ fields: ['slug'], where: '"deletedAt" IS NULL' }]; // unique among the live records
1067
+ ```
1068
+
1069
+ | Option | Description |
1070
+ |--------------|-----------------------------------------------------------------------------------------------------------------|
1071
+ | `fields` | The indexed fields, with their `-`/`+` order prefix |
1072
+ | `type` | `btree`, `hash`, `gin`, `gist`, `brin` or `spgist`, PostgreSQL only |
1073
+ | `ops` | The operator class of every field, PostgreSQL only (`gin_trgm_ops` with the `pg_trgm` extension) |
1074
+ | `where` | The SQL condition of a partial index (PostgreSQL, SQLite, SQL Server), the `partialIndexes` preview of Prisma |
1075
+ | `expression` | A SQL expression indexed instead of the fields (PostgreSQL, SQLite), with `type`, `ops`, `where` and `name` |
1076
+ | `name` | The name of the index in the database |
1077
+
1078
+ Prisma has no expression index, so `weaver generate` writes them into the repeatable SQL migration
1079
+ `database/sql/indexes/generated.sql`, which `weaver migrate` applies ([database.md](./database.md#sql-migrations)).
1080
+ An index without a `name` is named after its definition (`<table>_<hash>_idx`), so a changed `type`, `ops`, `where` or
1081
+ expression creates a new index; the next file drops the one no longer generated, removed or renamed, and an index
1082
+ changed under its `name` is dropped before it is created again. Commit and apply every generated version: the drop is
1083
+ in the file of the next `weaver generate` only.
1084
+
1085
+ ### Generated columns
1086
+
1087
+ `generatedColumns` declares columns PostgreSQL computes from the others (`GENERATED ALWAYS AS (...) STORED`), i.e. the
1088
+ `tsvector` of a full-text search. They never reach the API, its filters or its types: raw SQL and the indexes read them.
1089
+
1090
+ ```ts
1091
+ createModel({
1092
+ name: 'Product',
1093
+ scalars: { name: { type: 'string' }, description: { type: 'string', required: false } },
1094
+ generatedColumns: {
1095
+ search: {
1096
+ dbType: 'tsvector',
1097
+ expression: `to_tsvector('simple', "name" || ' ' || coalesce("description", ''))`
1098
+ }
1099
+ },
1100
+ index: [{ expression: '"search"', type: 'gin', name: 'Product_search_idx' }]
1101
+ });
1102
+ ```
1103
+
1104
+ Prisma cannot create a generated column, so `weaver generate` writes it into `database/sql/columns/generated.sql`,
1105
+ applied by `weaver migrate`. Once the database has it, the next `weaver generate` reads its expression back as the
1106
+ database renders it (`prisma db pull`) and declares it in the Prisma schema, so Prisma never drops it, with the index of
1107
+ the column by its name. The workflow of a new column, and of a changed one, is `weaver generate`, `weaver migrate`,
1108
+ then `weaver generate` again; `weaver migration check` then reports no migration. A changed `dbType` or expression
1109
+ drops the column and adds it again (its indexes applied again with it).
1110
+
1111
+ `prisma migrate dev` compares the database with what the Prisma migrations build, where a column of a SQL migration
1112
+ is a drift. So `weaver migration new` first records the declared generated columns and their indexes in a Prisma
1113
+ migration of their own, `<timestamp>_generated_columns`, and applies it: the statements of the SQL migration
1114
+ (`ADD COLUMN IF NOT EXISTS`), changing nothing in a migrated database. It is written again only once a column or an
1115
+ index of one changes; commit it with the migration created after it, and never edit it. A migration that cannot be
1116
+ applied, on a database without the tables of the models, is removed and marked as rolled back. The command fails when the
1117
+ schema declares a column otherwise than the database has it, i.e. before the `weaver migrate` and `weaver generate` of
1118
+ a changed expression. A column removed from a model is dropped by the next Prisma migration. Query a generated column
1119
+ with raw SQL:
1120
+
1121
+ ```ts
1122
+ const products = await injectService('Product').client.$queryRaw`
1123
+ SELECT id, name FROM "Product" WHERE search @@ plainto_tsquery('simple', ${text}) LIMIT 20`;
1124
+ ```
1125
+
1126
+ Every foreign key column (relation `<name>Id` columns, `createdById` and `deletedById`) is indexed automatically, since
1127
+ PostgreSQL and SQLite do not index them on their own. A foreign key is skipped when it is already unique (`oneToOne`
1128
+ relations and file fields) or when an explicit `index` or `unique` entry leads with it, so
1129
+ `index: [['categoryId', '-publishedAt']]` replaces the automatic `@@index([categoryId])`. Set `index: false` on a
1130
+ relation to leave its foreign key unindexed, i.e. for a rarely queried relation of a write-heavy model:
1131
+
1132
+ ```ts
1133
+ const config = {
1134
+ relations: {
1135
+ author: {
1136
+ model: 'User',
1137
+ type: 'manyToOne',
1138
+ index: false
1139
+ }
1140
+ }
1141
+ };
1142
+ ```
1143
+
1144
+ The audit columns `createdById` and `deletedById` are always indexed.
1145
+
1146
+ ### Unique config
1147
+
1148
+ `unique` takes the same shape as `index` and emits `@@unique` constraints. Use it for a combination of columns that must
1149
+ be unique together; a single column is better marked with the scalar's own `unique: true`:
1150
+
1151
+ ```ts
1152
+ unique: [['provider', 'providerAccountId']]; // @@unique([provider, providerAccountId])
1153
+ ```
1154
+
1155
+ A create or update breaking the constraint fails in the database, so handle the conflict where concurrent writes can
1156
+ race to insert the same combination.
1157
+
1158
+ A unique constraint of SQL Server holds a single NULL, so on SQL Server an optional unique column, i.e. a scalar with
1159
+ `unique: true` and `required: false`, the foreign key of an optional `oneToOne` relation or of a single file field, is
1160
+ generated as a unique index of its values instead, `@@unique([coverId], where: { coverId: { not: null } })`, with the
1161
+ `partialIndexes` preview feature of Prisma enabled in the generator block.
1162
+
1163
+ ### Generated models
1164
+
1165
+ `createModel` produces the following TypeBox schema models used internally by routes and services:
1166
+
1167
+ | Model | Purpose |
1168
+ |--------------------------|------------------------------------------------|
1169
+ | `readModel` | Full model with all visible fields |
1170
+ | `createModel` | Request body for create operations |
1171
+ | `updateModel` | Request body for update operations |
1172
+ | `relationsModel` | Relations-only subset |
1173
+ | `virtualModel` | Virtual fields-only subset |
1174
+ | `filesModel` | File fields-only subset |
1175
+ | `readOneModel` | Response for single-item reads |
1176
+ | `readManyModel` | Response for list reads |
1177
+ | `readOneNullableModel` | `readOneModel` or null, for optional relations |
1178
+ | `createOneModel` | Request for create endpoint |
1179
+ | `updateOneModel` | Request for update endpoint |
1180
+ | `fileUploadModel` | Request for file upload endpoint |
1181
+ | `fileDeleteModel` | Request for file delete endpoint |
1182
+ | `fileVersionDeleteModel` | Request for file version delete endpoint |
1183
+ | `seriesModel` | The values of the series fields |
1184
+
1185
+ ---
1186
+
1187
+ ## createService
1188
+
1189
+ Creates a resource service with lifecycle hooks and business logic. The service handles all database operations for a
1190
+ model and triggers hooks on each CRUD operation before/after.
1191
+
1192
+ ```ts
1193
+ import { createService } from '@appweaver/data';
1194
+
1195
+ export default createService({
1196
+ modelName: 'Product',
1197
+ afterCreate: (resource) => {
1198
+ logger.info(`Product created: ${resource.id}`);
1199
+ },
1200
+ textSearch: {
1201
+ title: { contains: '{input}', mode: 'insensitive' }
1202
+ }
1203
+ });
1204
+ ```
1205
+
1206
+ ### Configuration
1207
+
1208
+ ```ts
1209
+ function createService(
1210
+ config: ResourceServiceConfig,
1211
+ override?: boolean // replace the one defined for the model (default: false)
1212
+ ) {}
1213
+ ```
1214
+
1215
+ | Property | Type | Description |
1216
+ |-------------------|--------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
1217
+ | `modelName` | string | Model name to bind this service to (required). |
1218
+ | `beforeFind` | `(id) => void` | Hook called before finding a single resource. |
1219
+ | `beforeQuery` | `(options) => void` | Hook called before querying resources, with the query options as given. Mutate `options` to change the query. |
1220
+ | `beforeAggregate` | `(options) => void` | Hook called before aggregation, with the aggregation options as given. Mutate `options` to change the aggregation. |
1221
+ | `beforeCreate` | `(data) => void` | Hook called before creating a resource. Mutate `data` to modify input. |
1222
+ | `beforeUpdate` | `(id, data) => void` | Hook called before updating or replacing a resource. |
1223
+ | `beforeDelete` | `(id) => void` | Hook called before deleting a resource. |
1224
+ | `afterFind` | `(resource) => void` | Hook called after finding a resource. |
1225
+ | `afterQuery` | `(response) => void` | Hook called after querying resources. |
1226
+ | `afterAggregate` | `(response) => void` | Hook called after aggregation. |
1227
+ | `afterCreate` | `(resource) => void` | Hook called after creating a resource. |
1228
+ | `afterUpdate` | `(resource, previous) => void` | Hook called after updating or replacing a resource, with the state the resource had before the update. |
1229
+ | `afterDelete` | `(resource) => void` | Hook called after deleting a resource. |
1230
+ | `textSearch` | object \| function | The full-text index of fields (`{ mode: 'fts', fields }`), a Prisma filter object (`'{input}'` as the placeholder) or a function `(input: string) => filter`. |
1231
+
1232
+ All hooks can be synchronous or return a `Promise`. Every operation also emits a resource event once committed,
1233
+ received with `onResourceEvent` ([events.md](./events.md)), and the service calls made inside `runTransaction` commit
1234
+ together ([database.md](./database.md#transactions)).
1235
+
1236
+ ### Service methods
1237
+
1238
+ The created service exposes the following methods:
1239
+
1240
+ | Method | Signature | Description |
1241
+ |-------------|------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------|
1242
+ | `find` | `(id) => Promise<ReadOne>` | Find a single resource by ID. |
1243
+ | `single` | `(filter?, sort?) => Promise<ReadOne \| null>` | Find the first resource matching the filter, ordered by `sort` (default `-createdAt`), or `null` when none matches. |
1244
+ | `query` | `(options?) => Promise<QueryResponse>` | Query resources with filtering, pagination, and sorting (see [Query sorting](#query-sorting) and [Cursor pagination](#cursor-pagination)). |
1245
+ | `count` | `(filter?) => Promise<number>` | Count the resources matching the filter. |
1246
+ | `exists` | `(filter?) => Promise<boolean>` | Check whether any resource matches the filter. |
1247
+ | `aggregate` | `(options) => Promise<AggregateResponse>` | Aggregate resources with time-series grouping (see [Aggregate selection](#aggregate-selection)). |
1248
+ | `create` | `(data) => Promise<ReadOne>` | Create a new resource. |
1249
+ | `update` | `(id, data) => Promise<ReadOne>` | Update the given fields of a resource (`PATCH /:id`). |
1250
+ | `replace` | `(id, data) => Promise<ReadOne>` | Replace a resource as a whole (`PUT /:id`). |
1251
+ | `delete` | `(id) => Promise<ReadOne>` | Delete a resource. |
1252
+ | `client` | `ResourceClient` (property) | Database client of the model, for operations outside the model contract. |
1253
+
1254
+ `query` takes the options `filter`, `page` (default `1`), `size` (default `50`), `sort` (default `-createdAt`),
1255
+ `cursor`, and `totalCount` (default `false`), and `aggregate` the options `select` (required), `filter`, `dateField`
1256
+ (default `createdAt`), `from`, `to`, and `interval` (see [Aggregate selection](#aggregate-selection)). Both are the same shape as the bodies
1257
+ of the `POST /query` and `POST /aggregate` routes, and as the query parameters of their GET variants:
1258
+
1259
+ ```ts
1260
+ const posts = injectService('Post');
1261
+ const page = await posts.query({
1262
+ filter: { status: 'Published' },
1263
+ size: 20,
1264
+ sort: '-publishedAt'
1265
+ });
1266
+ const latest = await posts.single({ status: 'Published' }, '-publishedAt');
1267
+ const drafts = await posts.count({ status: 'Draft' });
1268
+ ```
1269
+
1270
+ ### Typed models
1271
+
1272
+ The types `weaver generate` emits register every model in the `ResourceRegistry` of `@appweaver/common`, so the
1273
+ factories and `injectService` infer the model types from a model name:
1274
+
1275
+ - `createService({ modelName: 'Post' })` and `createAuthService` type their hooks with `Post`, `PostCreate`, and
1276
+ `PostUpdate`, and the `replace` method of the service with `PostReplace`.
1277
+ - `createPolicy({ modelName: 'Post' })` types the records its callbacks receive as `Post` along with the foreign key
1278
+ columns of the database record.
1279
+ - `injectService('Post')` returns the `PostResourceService` alias.
1280
+ - The `modelName` of every factory, and the `model` of a relation, only accept registered model names, and the
1281
+ `mappedBy` of a relation suggests the relations of the target model.
1282
+
1283
+ ```ts
1284
+ import { injectService } from '@appweaver/core';
1285
+
1286
+ const posts = injectService('Post'); // PostResourceService
1287
+ ```
1288
+
1289
+ Never pass the model types as generic arguments. A model added since the last `weaver generate` is not registered
1290
+ yet, so run `weaver generate` after adding or renaming a model or a relation. The `--no-registry` flag of
1291
+ `weaver generate` skips the registration.
1292
+
1293
+ The `PostResourceService` alias is `IResourceService<Post, PostMultiple, PostCreate, PostUpdate, PostQuery>`, so the
1294
+ `<Model>Query`, `<Model>Sort`, and `<Model>Aggregate` aliases are exactly the inputs its methods accept.
1295
+
1296
+ The `create` and `update` inputs are the model's declared contracts, so a field an operation config omits, a hidden
1297
+ scalar, or a relation with `input: { type: 'none' }` is deliberately not part of them. A write outside the contract
1298
+ belongs on `service.client`, the database client of the model.
1299
+
1300
+ ### Query filters
1301
+
1302
+ The `filter` option of `query` and `aggregate`, and the `filter` argument of `single`, `count`, `exists`, and `export`
1303
+ mirror the WHERE part of a database query. The matching
1304
+ `POST /query`, `POST /aggregate`, and `POST /export` routes accept the same structure, validated against a generated
1305
+ per-model `<Model>QueryFilter` schema that rejects unknown and hidden fields with a `400` `VALIDATION_FAILED` error
1306
+ naming the field, i.e. `{ "field": "filter.titel", "rule": "additionalProperties", "message": "is not allowed" }`.
1307
+
1308
+ A filter is bounded, so one request cannot build a query the database takes seconds to plan: at most
1309
+ `resource.filterMaxConditions` conditions (every field and operator key, nested filters included, `1000`),
1310
+ `resource.filterMaxDepth` nesting levels (`10`) and `resource.filterMaxListValues` values in a list (`2000`). A filter
1311
+ beyond them is refused with `400` `RESOURCE_FILTER_TOO_COMPLEX`, the details naming the `limit` and its `max`, before the
1312
+ request is validated; the service methods check the same limits. A JSON body is limited to `server.jsonBodyMaxSize`
1313
+ (`10M`), apart from the uploads (`server.bodyMaxSize`).
1314
+
1315
+ **Logical operators** (filter level) — take a single filter object (each entry becomes one condition) or a list of them:
1316
+
1317
+ | Operator | Description |
1318
+ |----------|-------------------------------------------|
1319
+ | `_and` | All nested conditions must match. |
1320
+ | `_or` | At least one nested condition must match. |
1321
+ | `_not` | No nested condition may match. |
1322
+ | `_nor` | Alias of `_not`. |
1323
+
1324
+ **Comparison operators** (field level) — combined inside one object, all must match:
1325
+
1326
+ | Operator | Description |
1327
+ |---------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
1328
+ | `_eq` | Equal to the given value. |
1329
+ | `_ne` | Not equal to the given value. |
1330
+ | `_gt`, `_gte`, `_lt`, `_lte` | Greater/lower than (or equal to) the given value. |
1331
+ | `_in`, `_nin` | Included / not included in the given list. |
1332
+ | `_between` | Inside the inclusive `[min, max]` range. |
1333
+ | `_like` | SQL LIKE pattern with `%` wildcards (`Luk%` → starts with, `%avatar%` → contains, `%png` → ends with, no wildcard → equals). |
1334
+ | `_ilike` | Case-insensitive `_like`: `mode: 'insensitive'` on PostgreSQL, the collation on MySQL and SQL Server (insensitive by default). On SQLite a pattern with a wildcard ignores the ASCII case (`LIKE`, like `_like`), one without compares exactly. |
1335
+ | `_starts`, `_ends`, `_contains` | Starts with / ends with / contains the given string. |
1336
+ | `_exists` | Not null (`true`) or null (`false`). |
1337
+ | `_not` | Negates a nested operator object or plain value. |
1338
+
1339
+ **List (array scalar) operators**: `_has`, `_hasSome`, `_hasEvery`, `_isEmpty`.
1340
+
1341
+ **Relation operators**: `_some`, `_every`, `_none` take a filter of the related model; `_exists` maps to an `is`/`isNot`
1342
+ null check on a single relation and to `some`/`none` on a list relation.
1343
+
1344
+ **Plain value shorthands**: a bare value matches by equality, a list by inclusion, a two-value list on a numeric or date
1345
+ field as an inclusive range, a value or list on a relation by id, an array field uses `has`/`hasSome`, and `null`
1346
+ matches missing values or related records.
1347
+
1348
+ ```json
1349
+ {
1350
+ "filter": {
1351
+ "_and": {
1352
+ "firstName": {
1353
+ "_eq": "Luka",
1354
+ "_exists": true
1355
+ },
1356
+ "avatar": {
1357
+ "_or": {
1358
+ "title": {
1359
+ "_eq": "New user avatar"
1360
+ },
1361
+ "description": {
1362
+ "_like": "%avatar%"
1363
+ }
1364
+ },
1365
+ "originalName": {
1366
+ "_eq": "new_user_avatar.png"
1367
+ }
1368
+ }
1369
+ },
1370
+ "_or": [
1371
+ {
1372
+ "firstName": {
1373
+ "_like": "Luk%"
1374
+ }
1375
+ },
1376
+ {
1377
+ "lastName": "Matošević"
1378
+ }
1379
+ ],
1380
+ "tags": {
1381
+ "_some": {
1382
+ "name": {
1383
+ "_contains": "news"
1384
+ }
1385
+ }
1386
+ }
1387
+ },
1388
+ "page": 1,
1389
+ "size": 50,
1390
+ "sort": "-createdAt",
1391
+ "totalCount": true
1392
+ }
1393
+ ```
1394
+
1395
+ The `QueryFilter<T>` type from `@appweaver/common` provides code completion, and `weaver generate` emits a
1396
+ `<Model>Query = QueryFilter<Model>` alias per model:
1397
+
1398
+ ```ts
1399
+ import { QueryFilter } from '@appweaver/common';
1400
+ import { User, UserQuery } from '@/types/generated';
1401
+
1402
+ const filter: UserQuery = {
1403
+ _and: {
1404
+ firstName: { _eq: 'Luka' },
1405
+ loginAt: { _exists: true }
1406
+ }
1407
+ };
1408
+ const users = await userService.query({ filter });
1409
+ ```
1410
+
1411
+ ### Query sorting
1412
+
1413
+ The `sort` argument of `query` and `export` (and the `sort` property of the `POST /query` and `POST /export` request
1414
+ bodies) accepts two interchangeable forms, both applying their fields in the declared order:
1415
+
1416
+ ```json
1417
+ {
1418
+ "sort": "-author.createdAt,tagsCount,id"
1419
+ }
1420
+ ```
1421
+
1422
+ ```json
1423
+ {
1424
+ "sort": {
1425
+ "author": {
1426
+ "createdAt": "desc"
1427
+ },
1428
+ "tagsCount": "asc",
1429
+ "id": "asc"
1430
+ }
1431
+ }
1432
+ ```
1433
+
1434
+ In the string form a `-` prefix sorts descending (`+` or no prefix ascending) and a dot notation path targets a relation
1435
+ field. In the object form a relation takes a nested object, and the only accepted directions are the lower case `asc`
1436
+ and `desc`.
1437
+
1438
+ | Field | String form | Object form | Notes |
1439
+ |------------------------|---------------------|-------------------------------------|----------------------------------------------------------------------------------------|
1440
+ | Scalar, `id`, audit | `title`, `-id` | `{ title: 'asc' }` | Hidden scalars, array scalars, and virtual fields cannot be sorted by. |
1441
+ | To-one relation field | `-author.createdAt` | `{ author: { createdAt: 'desc' } }` | The relation must be included in the response of the action, at any nesting depth. |
1442
+ | To-many relation count | `-tagsCount` | `{ tagsCount: 'desc' }` | Sorts by the number of related records; the relation name alone (`-tags`) is an alias. |
1443
+
1444
+ Anything else — a relation the action does not include, a field of a to-many relation, a hidden or virtual field, an
1445
+ unknown sort direction — is rejected with a `400` error naming the offending field instead of reaching the database.
1446
+ Over HTTP the sort object is additionally validated against a generated per-model `<Model>QuerySort` schema, which
1447
+ rejects unknown fields the same way the query filter schema does.
1448
+
1449
+ The default sort is `-createdAt`. Every sort is terminated with the primary key when it does not already order by one,
1450
+ so paging stays deterministic, and the `createdAt` entry is dropped for models configured with
1451
+ `audit: { createdAt: false }`.
1452
+
1453
+ Sort inputs are typed by `QuerySort<T>` from `@appweaver/common`, and `weaver generate` emits a
1454
+ `<Model>Sort = QuerySort<<Model>Multiple>` alias per model, built from the query output model so it only offers the
1455
+ relations a query response includes:
1456
+
1457
+ ```ts
1458
+ import { PostSort } from '@/types/generated';
1459
+
1460
+ const sort: PostSort = { author: { lastName: 'asc' }, createdAt: 'desc' };
1461
+ const posts = await postService.query({ sort });
1462
+ ```
1463
+
1464
+ ### Query response
1465
+
1466
+ ```ts
1467
+ const config = {
1468
+ resultCount: 50, // Items in this page
1469
+ totalCount: 123, // Items matching the filter, up to resource.countLimit; null unless totalCount was asked
1470
+ totalCountExact: true, // false when the count stopped at resource.countLimit or a full-text search at resource.textSearchMaxMatches; null when not counted
1471
+ nextCursor: '...', // Cursor of the following page, absent on the last page
1472
+ prevCursor: '...', // Cursor of the preceding page, absent on the first page
1473
+ items: [] // Page data
1474
+ };
1475
+ ```
1476
+
1477
+ ### Cursor pagination
1478
+
1479
+ The response returns a `nextCursor` and a `prevCursor`; send one back as `cursor` to get that page. The direction is
1480
+ part of the cursor, so a request never names one. A cursor takes precedence over `page` and does not slow down on the
1481
+ later pages.
1482
+
1483
+ ```ts
1484
+ // First page counted, the following ones skipping the count
1485
+ let result = await postService.query({ size: 50, totalCount: true });
1486
+
1487
+ while (result.nextCursor) {
1488
+ result = await postService.query({ size: 50, cursor: result.nextCursor });
1489
+ }
1490
+ ```
1491
+
1492
+ ```json5
1493
+ // POST /posts/query
1494
+ {
1495
+ filter: {
1496
+ enabled: true
1497
+ },
1498
+ size: 50,
1499
+ sort: '-createdAt',
1500
+ cursor: 'eyJpIjo0MiwiZiI6IkhkQjVfa2VMTVlyNyJ9'
1501
+ }
1502
+ ```
1503
+
1504
+ `totalCount` defaults to `false` (returned as `null`): ask for it on the first page only, since it scans the matching
1505
+ records. The count stops at `resource.countLimit` (10,000), answering that number with `totalCountExact: false`. An
1506
+ offset page skipping more than `resource.maxOffset` records (10,000) is refused with `400 RESOURCE_OFFSET_TOO_LARGE`:
1507
+ page deeper with the cursors, which never slow down.
1508
+
1509
+ A cursor is opaque and bound to the query that issued it: reusing one under a different resource, filter, or sort is
1510
+ rejected with a 400.
1511
+
1512
+ ### Aggregate selection
1513
+
1514
+ The `select` argument of `aggregate` (and the required `select` property of the `POST /aggregate` request body) holds
1515
+ the operators to apply per field. Only the fields the database can aggregate are accepted, which are the numeric and
1516
+ date scalars of the model together with its numeric `id` and audit fields:
1517
+
1518
+ | Field kind | Operators |
1519
+ |------------------------------------|------------------------------------------------------|
1520
+ | Numeric (`int`, `bigInt`, `float`) | `count`, `sum`, `avg`, `min`, `max`, `first`, `last` |
1521
+ | Date (`dateTime`) | `count`, `min`, `max`, `first`, `last` |
1522
+
1523
+ ```json
1524
+ {
1525
+ "select": {
1526
+ "counter": {
1527
+ "count": true,
1528
+ "sum": true,
1529
+ "avg": true,
1530
+ "first": true,
1531
+ "last": true
1532
+ },
1533
+ "publishedAt": {
1534
+ "min": true,
1535
+ "max": true
1536
+ }
1537
+ },
1538
+ "dateField": "createdAt",
1539
+ "from": "2026-01-01T00:00:00.000Z",
1540
+ "to": "2026-01-08T00:00:00.000Z",
1541
+ "interval": "1d"
1542
+ }
1543
+ ```
1544
+
1545
+ **The range and the periods**: `from` is inclusive and `to` exclusive, on the `dateField`. Without them the aggregate
1546
+ covers every record of the filter. `interval` splits the range into periods, an amount and a unit of `s`, `m`, `h`,
1547
+ `d`, `w`, `mo` or `y` (`'15m'`, `'1d'`, `'3mo'`), the calendar units (`d` and longer) in the local time of the server,
1548
+ keeping the time of day across daylight saving time changes. Without `from` the periods start at the earliest record
1549
+ of the filter truncated to the unit, without `to` they end after the latest one, and a filter matching no record
1550
+ answers no period. Without `interval` the response holds the `total` only (`items: []`). A range of more than
1551
+ `resource.aggregateMaxPeriods` periods (1000, at most 10,000) is rejected with `RESOURCE_INVALID_AGGREGATE`.
1552
+
1553
+ **One statement**: the aggregate runs as one SQL statement, the records grouped by period, the total in a row of its
1554
+ own, and `first` and `last` taken with window functions. A filter it cannot express in SQL (a relation, a JSON or a list
1555
+ filter) falls back to one Prisma aggregation per period in a transaction, with up to two extra queries per non-empty
1556
+ period for `first` and `last`.
1557
+
1558
+ **`first` and `last`** take the value held by the earliest and the latest record of a period, ordered by the aggregated
1559
+ `dateField` (ties broken by `id`), or `null` for a period holding no record.
1560
+
1561
+ Any other field, an operator its field kind does not support, and an empty selection are rejected with a `400` error.
1562
+ Over HTTP the selection is also validated against a generated per-model `<Model>AggregateSelect` schema. The `dateField`
1563
+ must be a date field of the model (`createdAt` by default).
1564
+
1565
+ Selections are typed by `AggregateSelect<T>` from `@appweaver/common`, with a `<Model>Aggregate` alias emitted per
1566
+ model:
1567
+
1568
+ ```ts
1569
+ import { PostAggregate } from '@/types/generated';
1570
+
1571
+ const select: PostAggregate = {
1572
+ counter: { sum: true },
1573
+ createdAt: { max: true }
1574
+ };
1575
+ const stats = await postService.aggregate({ select });
1576
+ ```
1577
+
1578
+ `aggregate` infers the response type from the selection it is given, so a selection passed as an object literal, or
1579
+ declared with `satisfies`, narrows the response to the fields it names, while one annotated as `<Model>Aggregate` keeps
1580
+ every aggregatable field of the model:
1581
+
1582
+ ```ts
1583
+ const narrow = await postService.aggregate({
1584
+ select: { counter: { sum: true } }
1585
+ });
1586
+ narrow.total.counter?.sum; // typed
1587
+ narrow.total.createdAt; // compile error, the field was not selected
1588
+
1589
+ const select = { counter: { sum: true } } satisfies PostAggregate; // narrows and checks against the model
1590
+ const wide: PostAggregate = { counter: { sum: true } }; // keeps the whole model in the response type
1591
+ ```
1592
+
1593
+ ### Aggregate response
1594
+
1595
+ The response shape follows whatever was selected, and its type carries the fields of the selection (see
1596
+ [Aggregate selection](#aggregate-selection)). Each aggregated field holds one property per operator applied to it, and
1597
+ the operators the selection left out are `undefined`:
1598
+
1599
+ ```ts
1600
+ const resp = {
1601
+ total: AggregateValue, // Overall aggregation
1602
+ items: Array<AggregateResult> // Per-period results
1603
+ };
1604
+
1605
+ // Each AggregateResult:
1606
+ const result = {
1607
+ date: 'Date', // the start of the period
1608
+ result: {
1609
+ [field]: {
1610
+ count: 123,
1611
+ min: 123, // an ISO date string for a date field
1612
+ max: 123, // an ISO date string for a date field
1613
+ avg: 123, // numeric fields only
1614
+ sum: 123, // numeric fields only
1615
+ first: 123, // value of the earliest record of the period
1616
+ last: 123 // value of the latest record of the period
1617
+ }
1618
+ }
1619
+ };
1620
+ ```
1621
+
1622
+ ### Text search example
1623
+
1624
+ The full-text mode matches the `searchText` of a query with the full-text index of the database, set up when the
1625
+ application starts and by `weaver migrate` (with the user of `database.migrationUrl`), like the PostGIS triggers. Use it
1626
+ beyond a few thousand records, where the `contains` of the object form reads every row (184 ms a query at 100k posts on SQLite, 7 ms with the index):
1627
+
1628
+ ```ts
1629
+ export default createService({
1630
+ modelName: 'Post',
1631
+ textSearch: {
1632
+ mode: 'fts',
1633
+ fields: ['title', 'excerpt', 'content'],
1634
+ language: 'english' // PostgreSQL text search configuration, SQL Server column language (default: simple)
1635
+ }
1636
+ });
1637
+ ```
1638
+
1639
+ - Every word of the text (a run of letters and digits, at most 16, the rest of the text ignored) must match the start
1640
+ of a word of one of the fields, the case ignored: `trail vele` matches "Walking the Velebit trail". The diacritics
1641
+ are ignored on SQLite, kept on PostgreSQL (unless the `language` is a configuration with `unaccent`), and compared
1642
+ by the collation on MySQL and the accent sensitivity of the catalog on SQL Server.
1643
+ - The query keeps the `resource.textSearchMaxMatches` (1,000) most relevant matches, then applies the rest of the
1644
+ filter, the policy and the sort, so a broad search may miss records the filter and the policy would keep. Its count
1645
+ stops there too, answered with `totalCountExact: false` when the search reached the limit.
1646
+ - The index, per database: an FTS5 table kept in line by triggers on SQLite (`<table>_fts_<hash>`, keyed by the
1647
+ integer id, or by a table of the keys `<table>_fts_<hash>_keys` for a string id, whose `rowid` a table copy
1648
+ renumbers), set up again when a Prisma migration redefining the table dropped its triggers, and left out of the
1649
+ migrations by `weaver migration new` and `weaver migration check`, a GIN index of the
1650
+ `to_tsvector` of the fields on PostgreSQL, a `FULLTEXT` index on MySQL (the words shorter than `innodb_ft_min_token_size`,
1651
+ 3 by default, and its stop words are not indexed, and Prisma sees it as a drift, see
1652
+ [database.md](./database.md)), and a full-text index of the primary key on SQL Server, which
1653
+ needs the Full-Text Search feature installed and fills the index in the background, a new record matching a moment
1654
+ later. A change of the fields replaces the index when the application starts; on SQL Server a change of the
1655
+ `language` alone is not detected, drop the index (`DROP FULLTEXT INDEX ON [Post]`) to have it created again.
1656
+ - The fields are string scalars of the model, not lists.
1657
+
1658
+ Object form with placeholder, replaced by the searched text wherever it appears in a string value:
1659
+
1660
+ ```ts
1661
+ const config = {
1662
+ textSearch: {
1663
+ title: {
1664
+ contains: '{input}',
1665
+ mode: 'insensitive'
1666
+ }
1667
+ }
1668
+ };
1669
+ ```
1670
+
1671
+ An `OR` given as an object is turned into a list, each entry becoming one condition, as the `_or` filter operator does:
1672
+
1673
+ ```ts
1674
+ const config = {
1675
+ textSearch: {
1676
+ OR: {
1677
+ title: { contains: '{input}' },
1678
+ excerpt: { contains: '{input}' }
1679
+ }
1680
+ }
1681
+ };
1682
+ ```
1683
+
1684
+ `mode: 'insensitive'` is supported on PostgreSQL and MongoDB only, the database rejects it on SQLite, MySQL, and SQL
1685
+ Server, where `contains` already ignores the case with the default collation (ASCII letters only on SQLite).
1686
+
1687
+ Function form for complex queries:
1688
+
1689
+ ```ts
1690
+ const config = {
1691
+ textSearch: (input) => ({
1692
+ OR: [
1693
+ { title: { contains: input, mode: 'insensitive' } },
1694
+ { description: { contains: input, mode: 'insensitive' } }
1695
+ ]
1696
+ })
1697
+ };
1698
+ ```
1699
+
1700
+ ---
1701
+
1702
+ ## createRoutes
1703
+
1704
+ Creates CRUD route definitions for a resource. Routes are automatically registered with Fastify and derive their
1705
+ request/response schemas from the resource model.
1706
+
1707
+ ```ts
1708
+ import { createRoutes } from '@appweaver/web';
1709
+
1710
+ export default createRoutes({
1711
+ modelName: 'Product',
1712
+ path: '/products',
1713
+ find: { roles: ['Admin', 'User'], rateLimit: { max: 100 } },
1714
+ actions: ['find', 'query', 'create', 'update', 'replace'], // no delete
1715
+ query: { cache: { ttl: 5000 } },
1716
+ create: { permissions: ['product:create'] }
1717
+ });
1718
+ ```
1719
+
1720
+ ### Configuration
1721
+
1722
+ ```ts
1723
+ function createRoutes(
1724
+ config: ResourceRoutesConfig,
1725
+ override?: boolean // replace the one defined for the model (default: false)
1726
+ ) {}
1727
+ ```
1728
+
1729
+ | Property | Type | Description |
1730
+ |---------------------|------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
1731
+ | `modelName` | string | Model name to bind routes to (required). |
1732
+ | `path` | string | Custom base URL path (default: derived from model name). |
1733
+ | `actions` | (ResourceAction \| 'crud')[] | The actions whose routes are registered, `crud` standing for `find`, `query`, `create`, `update`, `replace` and `delete` (default: `['crud']`). `aggregate`, `export`, the bulk, file and series actions are registered only when listed: `files` stands for `fileUpload`, `fileDelete`, `fileVersions` and `fileVersionDelete`, `series` for `seriesWrite`, `seriesQuery` and `seriesDelete` (see [File and series routes](#file-and-series-routes)). |
1734
+ | `defaults` | QueryRouteConfig | Config applied to every route (see [Route defaults](#route-defaults)). |
1735
+ | `find` | ReadRouteConfig | `GET /:id` - Find single resource by ID. |
1736
+ | `query` | QueryRouteConfig | `POST /query` - Query resources with filters. |
1737
+ | `aggregate` | QueryRouteConfig | `POST /aggregate` - Aggregate resources. |
1738
+ | `create` | RouteConfig | `POST /` - Create a new resource. |
1739
+ | `update` | RouteConfig | `PATCH /:id` - Update a resource (inherited by `replace`). |
1740
+ | `replace` | RouteConfig | `PUT /:id` - Replace a resource (inherits `update`). |
1741
+ | `delete` | RouteConfig | `DELETE /:id` - Delete a resource. |
1742
+ | `export` | RouteConfig | `POST /export` - Export resources to CSV. |
1743
+ | `fileUpload` | RouteConfig | `POST /:id/files` - Upload files to a resource. |
1744
+ | `fileDelete` | RouteConfig | `POST /:id/delete-files` - Delete files from a resource. |
1745
+ | `fileVersions` | RouteConfig | `GET /:id/file-versions?name=` - List the versions of a file. Registered with `storage.versions.enabled` for a model with a field keeping versions. |
1746
+ | `fileVersionDelete` | RouteConfig | `POST /:id/delete-file-versions` - Delete versions of files, `latest` restoring the previous version (inherits `fileDelete`). Registered like `fileVersions`. |
1747
+ | `seriesWrite` | SeriesWriteRouteConfig | `POST /:id/series`, `POST /series` - Write time series points ([timeseries.md](./timeseries.md)). |
1748
+ | `seriesQuery` | RouteConfig | `GET /:id/series`, `POST /series/query` - Query time series points. |
1749
+ | `seriesDelete` | RouteConfig | `POST /:id/delete-series` - Delete the time series points of a range. |
1750
+ | `bulkCreate` | BulkRouteConfig | `POST /bulk` - Create many (with the `bulkCreate` action). |
1751
+ | `bulkUpdate` | BulkRouteConfig | `PATCH /bulk` - Update many (with the `bulkUpdate` action). |
1752
+ | `bulkReplace` | BulkRouteConfig | `PUT /bulk` - Replace many (with the `bulkReplace` action, inherits `bulkUpdate`). |
1753
+ | `bulkDelete` | BulkRouteConfig | `DELETE /bulk` - Delete many (with the `bulkDelete` action). |
1754
+ | `events` | ResourceEventsConfig | The `create`, `update` and `delete` events exposed to the realtime connections (`{ actions, public?, roles?, permissions? }`, an action as an object `{ action, public?, roles?, permissions? }` with its own access), none unless set ([realtime.md](./realtime.md#resource-events)). |
1755
+ | `mcp` | ResourceMcpConfig | The actions exposed as tools of the MCP server of `@appweaver/mcp` (`{ actions, description?, exclude?, maxLimit?, public?, roles?, permissions? }`, `update` and `delete` only with `mcp.destructiveEnabled`), none unless set ([mcp.md](./mcp.md)). |
1756
+
1757
+ ### File and series routes
1758
+
1759
+ The routes of the file fields and of the time series fields are registered only when `actions` lists them, and only
1760
+ for a model having such fields: `['crud', 'files']`, or a single one, `['find', 'query', 'fileVersions']`. A route
1761
+ group without them, i.e. a read only one, has none, whatever the fields of its model. The routes of a view
1762
+ (`view`) serve the files only when the view reads (`fileVersions`) or writes (`fileUpload`, `fileDelete`,
1763
+ `fileVersionDelete`) every file field of the model, since these routes take any of them, and the time series routes
1764
+ are never registered for a view.
1765
+
1766
+ ```ts
1767
+ export default createRoutes({
1768
+ modelName: 'Product',
1769
+ actions: ['crud', 'files', 'series'],
1770
+ fileUpload: { roles: ['Admin'] }
1771
+ });
1772
+ ```
1773
+
1774
+ ### Route defaults
1775
+
1776
+ `defaults` takes any route option and applies it to every route, unless the route sets the option itself. Caching
1777
+ options reach only `find`, `query`, and `aggregate`, and `method` only `query` and `aggregate`. A route setting any of
1778
+ `public`, `roles`, `permissions`, or `auth` inherits none of them from the defaults, and the same holds for
1779
+ `recaptcha` and `recaptchaAction`, and for `turnstile` and `turnstileAction`.
1780
+
1781
+ ```ts
1782
+ export default createRoutes({
1783
+ modelName: 'Product',
1784
+ defaults: { roles: ['Admin'], cache: true, rateLimit: { max: 100 } },
1785
+ query: { public: true, cache: false } // public, not cached, rate limited
1786
+ });
1787
+ ```
1788
+
1789
+ ### Route config (all operations)
1790
+
1791
+ | Property | Type | Default | Description |
1792
+ |-------------------|--------------------------|---------|-------------------------------------------------------------------------------------------------------------------------------|
1793
+ | `public` | boolean | `false` | No authentication required. |
1794
+ | `roles` | string[] | - | Required roles (OR logic by default). |
1795
+ | `permissions` | string[] | - | Required permissions (OR logic by default). |
1796
+ | `auth` | AuthType[] | - | Allowed authentication types: `'jwt'`, `'apiKey'`, `'basic'`. |
1797
+ | `rateLimit` | RateLimitConfig \| false | - | Per-operation rate limiting. `false` disables. |
1798
+ | `compress` | boolean \| object | config | Response compression: `false`, or `{ threshold, encodings, levels }` over `server.compression`. |
1799
+ | `timeout` | integer | config | Milliseconds the route may take, `0` for none, over `server.requestTimeout` (`503 REQUEST_TIMEOUT`). |
1800
+ | `recaptcha` | boolean | `false` | Require reCAPTCHA verification. |
1801
+ | `recaptchaAction` | string | - | Expected reCAPTCHA action name for score validation. |
1802
+ | `turnstile` | boolean | `false` | Require Cloudflare Turnstile verification. |
1803
+ | `turnstileAction` | string | - | Expected Turnstile action name (enables the check). |
1804
+ | `errorCodes` | ErrorCode[] | - | Codes the route responds with besides the framework ones (a service hook throws them), listed in its OpenAPI error responses. |
1805
+
1806
+ `roles`, `permissions` and `auth` are checked as described in [security.md](./security.md#authorization), and the
1807
+ `errorCodes` are documented like the `errorResponses` of a custom route
1808
+ ([errors.md](./errors.md#documenting-the-errors-of-a-route)).
1809
+
1810
+ ### Read route config (find, query, aggregate)
1811
+
1812
+ Extends RouteConfig with caching options (the global TTL and invalidation strategy are in [cache.md](./cache.md)):
1813
+
1814
+ | Property | Type | Default | Description |
1815
+ |----------|-------------------|---------|-----------------------------------------------------------------------------|
1816
+ | `cache` | boolean \| object | `false` | Cache the responses: `true`, or `{ scope, ttl, skipInvalidation }` (below). |
1817
+
1818
+ | `cache` option | Type | Default | Description |
1819
+ |--------------------|--------------------------------------|----------------------------------------------|------------------------------------------------|
1820
+ | `scope` | `'public'` \| `'user'` \| `'shared'` | `public` on a public route, `user` otherwise | Who an entry is served to (below). |
1821
+ | `ttl` | number | `cache.defaultTtl` | Time to live in milliseconds. |
1822
+ | `skipInvalidation` | boolean | `false` | Skip the automatic invalidation on the writes. |
1823
+
1824
+ The scopes:
1825
+
1826
+ - `public`: a route without authentication (`public: true`), one entry for every request. Refused on an authenticated
1827
+ route, which would serve one user's response to another.
1828
+ - `user`: an entry per user, the default of an authenticated route.
1829
+ - `shared`: an authenticated route answering every user alike, one entry for all of them, served to every user the
1830
+ route lets in. A resource route accepts it only when neither the policy of its model (and of its `view`) nor the one
1831
+ of a model its responses include or count (and of the view a relation reads) has `readRestrictions` or `checkAccess`,
1832
+ failing at startup otherwise; a virtual field reading the
1833
+ current user must not be on it either. On a custom route the application is the judge.
1834
+
1835
+ The cache key of a resource route is built from the model, the route and the request (and the user in the `user`
1836
+ scope, with the API key it authenticated with, whose scope may narrow its roles), so the invalidation of the model's
1837
+ writes reaches it. A cached response replays only the headers describing its payload (`content-type`,
1838
+ `content-disposition`, `content-language`, `etag`, `last-modified`, `cache-control`, `vary`); the others, such as the
1839
+ CORS origin or the rate limit counters, are set again for every request. A custom `key`, with `modelName` and
1840
+ `relations`, is an option of the `cache` of the custom routes of [`registerRoute`](#registerroute) only: it replaces
1841
+ the request in the key, never the scope (the user in the `user` scope) nor the models evicting the entry.
1842
+
1843
+ ### Query route config (query, aggregate)
1844
+
1845
+ Extends ReadRouteConfig with the HTTP methods of the route:
1846
+
1847
+ | Property | Type | Default | Description |
1848
+ |----------|-------------|-------------------------------------------------------|---------------------------------------------------------------|
1849
+ | `method` | QueryMethod | `RESOURCE_QUERY_METHOD` / `RESOURCE_AGGREGATE_METHOD` | `'post'` (config default), `'get'`, or `'get-post'` for both. |
1850
+
1851
+ The GET route takes the request body properties as query parameters: `filter` and `select` JSON-encoded, `sort` as a
1852
+ field list or JSON object, the rest as plain values. It shares the settings and validation of the POST route.
1853
+
1854
+ ```
1855
+ GET /api/posts/query?filter={"viewCount":{"_gte":5}}&sort=-createdAt&size=20
1856
+ ```
1857
+
1858
+ Keep POST for large filters, since Node.js limits the request headers to 16 KB. With a string primary key, the id
1859
+ `query` or `aggregate` can no longer be read through `GET /:id`.
1860
+
1861
+ ### Update routes (update, replace)
1862
+
1863
+ Both routes share the input fields (the `update` operation config of the model), the policies, the `beforeUpdate`
1864
+ and `afterUpdate` hooks, the cache invalidation, and the `update` event:
1865
+
1866
+ - `PATCH /:id` (`service.update`) updates the given fields (`<Model>Update`, all optional).
1867
+ - `PUT /:id` (`service.replace`) replaces the resource (`<Model>Replace`, required fields as on create). Omitted fields
1868
+ are reset to their `default`, or `null` when optional. Hidden fields, files, and omitted optional relations stay
1869
+ untouched. The hooks receive the completed data, the reset fields included, so they see a replacement as an update
1870
+ of every field.
1871
+
1872
+ The `update` config applies to both routes, and `replace` overrides it for `PUT /:id` only, merged the same way as the
1873
+ [route defaults](#route-defaults). Setting `replace` alone never affects `PATCH /:id`.
1874
+
1875
+ ```ts
1876
+ createRoutes({
1877
+ modelName: 'Product',
1878
+ update: { roles: ['Admin', 'Editor'], rateLimit: { max: 50 } },
1879
+ replace: { roles: ['Admin'] } // PUT: Admin only, same rate limit
1880
+ });
1881
+
1882
+ createRoutes({ modelName: 'Setting', actions: ['find', 'query', 'create', 'update', 'delete'] }); // PATCH only
1883
+ createRoutes({ modelName: 'Profile', actions: ['find', 'query', 'create', 'replace', 'delete'] }); // PUT only
1884
+ ```
1885
+
1886
+ ### Optimistic concurrency (If-Match)
1887
+
1888
+ Without a precondition, the last of two concurrent updates of a field wins. A model with `updatedAt` (the default
1889
+ audit fields) answers `find`, `create`, `update` and `replace` with an `ETag`, its `updatedAt` quoted
1890
+ (`"2026-11-01T12:00:00.000Z"`). A client sending it back as `If-Match` on `PATCH`, `PUT` or `DELETE /:id` writes only
1891
+ the version it read: a record changed since answers `412 RESOURCE_PRECONDITION_FAILED`, with the `updatedAt` it has
1892
+ now in its details. `If-Match` also takes the `updatedAt` of the record as the client read it (with or without quotes),
1893
+ a list of them, or `*` for any version. A weak tag (`W/"..."`) never matches, `If-Match` comparing the tags strongly
1894
+ (RFC 9110). The write is made with the read `updatedAt` in its condition, so a concurrent write in between fails it
1895
+ too. The header is optional: a request without it writes as before. The bulk routes ignore `If-Match`: a bulk write
1896
+ has no precondition, so a client needing one writes the records one at a time.
1897
+
1898
+ ```ts
1899
+ const post = await client.post.find(1);
1900
+ await client.post.update(
1901
+ { id: 1, title: 'Renamed' },
1902
+ { headers: { 'If-Match': post.updatedAt } } // 412 if someone changed the post since
1903
+ );
1904
+ ```
1905
+
1906
+ In code, `update(id, data, { ifMatch })`, `replace` and `delete` take the same version (a `Date`, an ISO string or an
1907
+ `ETag`). A model without `updatedAt` matches only `*`.
1908
+
1909
+ ### Bulk routes (bulkCreate, bulkUpdate, bulkReplace, bulkDelete)
1910
+
1911
+ Registered when `actions` lists them (`bulkCreate`, `bulkUpdate`, `bulkReplace`, `bulkDelete`). Each bulk route
1912
+ inherits the config of its single route (`create`, `update`, `replace`, `delete`) and takes `maxItems` (default `RESOURCE_BULK_MAX_ITEMS`, `2000`) and `returnRecords`
1913
+ (default `RESOURCE_BULK_RETURN_RECORDS`, `true`).
1914
+
1915
+ `bulkReplace` inherits `update`, `replace`, then `bulkUpdate`, each overriding the previous one, and configures
1916
+ `PUT /bulk` alone.
1917
+ When `replace` and `bulkUpdate` set the same option group (i.e. `roles`), `bulkUpdate` wins for `PUT /bulk`, so set it
1918
+ on `bulkReplace` to keep the replace one.
1919
+
1920
+ | Route | Body | Service method |
1921
+ |----------------|----------------------------------|----------------------|
1922
+ | `POST /bulk` | `[<Model>Create]` | `bulkCreate(items)` |
1923
+ | `PATCH /bulk` | `[{ id, data: <Model>Update }]` | `bulkUpdate(items)` |
1924
+ | `PUT /bulk` | `[{ id, data: <Model>Replace }]` | `bulkReplace(items)` |
1925
+ | `DELETE /bulk` | `[id]` | `bulkDelete(ids)` |
1926
+
1927
+ All items run in one transaction (`RESOURCE_BULK_TRANSACTION_TIMEOUT`, `5000` ms) through the single-item service method
1928
+ (same policies, hooks, events, and cache invalidation). Any failure rolls back everything and returns that item's error;
1929
+ success returns the array of records, each the same as its single route responds with (generated ids, defaults, virtual
1930
+ fields), in the order of the items. With `returnRecords: false` it returns only `{ "success": true, "count": n }`
1931
+ instead, for callers that ignore the records or refetch them anyway. The `after*` hooks run before the commit, so keep
1932
+ side effects in resource events ([events.md](./events.md)). A bulk delete checks every id exists first, and skips ids
1933
+ removed by an earlier cascade, leaving them out of the records (its `count` still includes them). A request counts once
1934
+ for rate limiting.
1935
+
1936
+ ```ts
1937
+ createRoutes({
1938
+ modelName: 'Tag',
1939
+ actions: ['crud', 'bulkCreate', 'bulkDelete'],
1940
+ delete: { roles: ['Admin'] },
1941
+ bulkCreate: { roles: ['Admin'] },
1942
+ bulkDelete: { maxItems: 500, returnRecords: false } // inherits roles: ['Admin']
1943
+ });
1944
+ ```
1945
+
1946
+ ### Rate limit config
1947
+
1948
+ ```ts
1949
+ const config = {
1950
+ rateLimit: {
1951
+ max: 100,
1952
+ timeWindow: 60000,
1953
+ allowList: ['127.0.0.1'],
1954
+ keyGenerator: (req) => req.ip,
1955
+ secure: true
1956
+ }
1957
+ };
1958
+ ```
1959
+
1960
+ | Property | Type | Description |
1961
+ |----------------|------------------------------|-------------------------------------------------------------------------------------|
1962
+ | `max` | number \| function | Maximum requests per time window. Function: `(req, key) => number`. |
1963
+ | `timeWindow` | number \| string \| function | Window duration in ms. Function: `(req, key) => number`. |
1964
+ | `allowList` | string[] \| function | IPs exempt from limiting. Function: `(req, key) => boolean`. |
1965
+ | `keyGenerator` | function | Custom key generator. Signature: `(req) => string \| number`. |
1966
+ | `secure` | boolean | Respond `503 MEMORY_UNAVAILABLE` while Redis is down (login, OTP, expensive calls). |
1967
+ | `skipOnError` | boolean | Skip the limit while Redis is down, overriding the config and `secure`. |
1968
+
1969
+ ---
1970
+
1971
+ ## createPolicy
1972
+
1973
+ Creates row-level security policies for a resource. The service layer evaluates the policy on every CRUD operation to
1974
+ enforce fine-grained authorization beyond static role/permission checks (see
1975
+ [security.md](./security.md#authorization-check-order) for where it runs among them).
1976
+
1977
+ ```ts
1978
+ import { createPolicy } from '@appweaver/data';
1979
+
1980
+ export default createPolicy({
1981
+ modelName: 'Product',
1982
+ checkAccess: (user, resource, action) => resource.status === 'Draft',
1983
+ readRestrictions: (user, resource, action) => ({
1984
+ enabled: true
1985
+ }),
1986
+ files: {
1987
+ photo: { accessType: 'public' }
1988
+ }
1989
+ });
1990
+ ```
1991
+
1992
+ ### Configuration
1993
+
1994
+ ```ts
1995
+ function createPolicy(
1996
+ config: ResourcePolicyConfig,
1997
+ override?: boolean // replace the one defined for the model (default: false)
1998
+ ) {}
1999
+ ```
2000
+
2001
+ | Property | Type | Description |
2002
+ |---------------------|---------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
2003
+ | `modelName` | string | Model name to bind this policy to (required). |
2004
+ | `checkAccess` | `(user, resource, action) => boolean` | Dynamic access check against a resource instance. Return `true` to allow, `false` to deny. |
2005
+ | `readRestrictions` | `(user, resource, action) => filter` | Returns a Prisma filter object applied to all read queries (find, query, aggregate). Restricts which records are visible. |
2006
+ | `writeRestrictions` | `(user, resource, action) => data` | Returns data to merge or validate on create/update operations. |
2007
+ | `files` | Record\<string, FilePolicy> | Per-file field access policy. |
2008
+ | `events` | `(user, event) => boolean` | Returns `false` to keep a resource event from the realtime connection of a user, replacing the default `checkAccess` of a `find` and the matching of the `readRestrictions` ([realtime.md](./realtime.md#the-events-policy)). |
2009
+
2010
+ **Action types**: `'find'`, `'query'`, `'aggregate'`, `'create'`, `'update'`, `'delete'`
2011
+
2012
+ Every policy callback may be `async` (return a promise), e.g. to look up a team membership in the database. The
2013
+ `user` is `null` for an unauthenticated request.
2014
+
2015
+ The `readRestrictions` of a model also apply where another model includes its records (`output.type: 'always'` or
2016
+ `'single'`), called with the `query` action: a list relation and its count read only the records they let the user
2017
+ read, and a single relation they hide is `null` (matched in memory, or with one query per related model for a
2018
+ relation filter). Its `checkAccess` is not called for the included records. A filter through a relation matches the
2019
+ records they let the user read only, at every level: `author.posts._some.status` quantifies over the posts the user
2020
+ reads, so it cannot tell the hidden ones apart, and `_every` holds for those. A relation reading its records through a
2021
+ view (`output.view`) applies the `readRestrictions` of the policy of that view too
2022
+ (`createPolicy({ modelName: 'User', view: 'public' })`), in its list, count, single record, filter and resource events.
2023
+
2024
+ ### File policy
2025
+
2026
+ | Property | Type | Default | Description |
2027
+ |--------------|--------------------------------------------|---------------|--------------------------------------------------------------------------------------------------|
2028
+ | `accessType` | `'public'` \| `'protected'` \| `'private'` | `'protected'` | File access level. `public` = anyone, `protected` = authenticated users, `private` = owner only. |
2029
+ | `canAccess` | `(user, resource, file) => boolean` | - | Custom access check for reading files. |
2030
+ | `canCreate` | `(user, resource, file) => boolean` | - | Custom access check for uploading files. |
2031
+ | `canDelete` | `(user, resource, file) => boolean` | - | Custom access check for deleting files. |
2032
+
2033
+ The file checks may be `async` too, and run with a `null` user when the upload or delete route is public, so a policy
2034
+ can allow unauthenticated uploads. They are separate from the resource policy: changing a file does not run the
2035
+ `checkAccess` of the resource for the `update` action.
2036
+
2037
+ ### Skipping the policies
2038
+
2039
+ The policies apply to the calls of a request (HTTP, realtime, MCP) and to the calls run with `runAs(user, fn)`. The
2040
+ application's own calls, outside of a request and of `runAs` (a queue worker, a scheduled job, a seeder, a task, a
2041
+ test calling a service), run as the system: the access checks, the read and write restrictions and the file checks are
2042
+ skipped (`isSystemCall()` of `@appweaver/core`), so a policy receives a `null` user only for an anonymous request, or
2043
+ for `runAs(null, fn)`. To apply the policies of a user in a job, run it with `runAs(user, fn)`, which applies them
2044
+ even inside `withoutPolicies`, and `runAsSystem(fn)` of `@appweaver/core` runs a function as the application again,
2045
+ outside of the auth context of the call.
2046
+
2047
+ Inside a request, code acting on behalf of the system rather than the requesting user, such as a custom flow, runs
2048
+ resource and file service calls with `withoutPolicies`. The service hooks, validation, events, and cache invalidation
2049
+ still run. The framework's own authentication flows (login, sign-up, logout, password change, 2FA, email verification,
2050
+ and OAuth2 account linking) use it, so a policy on the auth model never blocks them.
2051
+
2052
+ ```ts
2053
+ import { injectService } from '@appweaver/core';
2054
+ import { withoutPolicies } from '@appweaver/data';
2055
+
2056
+ const pending = await withoutPolicies(() =>
2057
+ injectService('Order').query({ filter: { status: 'Pending' } })
2058
+ );
2059
+ ```
2060
+
2061
+ The internal access covers every call made while the function runs, including the calls made by the service hooks,
2062
+ until a `runAs(user, fn)` inside it. `arePoliciesSkipped()` tells whether the current call runs with it, or as the
2063
+ system. Both are exported by `@appweaver/core` too.
2064
+
2065
+ A test calling a service directly is the application's own call, so it skips the policies too. A test file of the
2066
+ policies calls `runTestsAsAnonymous()` of `@appweaver/testing` once at its top level: every `test` and `it` (with
2067
+ `.only`, `.skip` and `.each`) then runs as an anonymous request (`runAs(null, ...)`), a test sets its user with
2068
+ `runAs(user, fn)`, and one of the application's own calls runs it in `runAsSystem(fn)`.
2069
+
2070
+ ```ts
2071
+ import { injectService, runAs } from '@appweaver/core';
2072
+ import { runTestsAsAnonymous } from '@appweaver/testing';
2073
+
2074
+ runTestsAsAnonymous();
2075
+
2076
+ const admin = { id: 1, email: 'admin@example.com', roles: [adminRole] };
2077
+
2078
+ test('hides the drafts from an anonymous user', async () => {
2079
+ await expect(injectService('Post').query({})).resolves.toMatchObject({ total: 1 });
2080
+ await expect(runAs(admin, () => injectService('Post').query({}))).resolves.toMatchObject({ total: 2 });
2081
+ });
2082
+ ```
2083
+
2084
+ ---
2085
+
2086
+ ## Extending a model defined elsewhere
2087
+
2088
+ A model, service, policy or routes is defined once per model name: a second `createModel`, `createService`,
2089
+ `createPolicy` or `createRoutes` under a taken name fails at startup with `CONTEXT_DEFINITION_DUPLICATE`, naming the
2090
+ files of both (`override: true`, the last argument, replaces the first one entirely). A model of the framework or of a
2091
+ module (`ApiKey`, `File`, `Role`, `AuditLog`, ...) is extended instead, from a file the loaders find like any resource
2092
+ (`src/resources/api-key/model.ts`, `service.ts`, `policy.ts`, `routes.ts`):
2093
+
2094
+ ```ts
2095
+ import { extendModel, extendPolicy, extendService } from '@appweaver/data';
2096
+ import { extendRoutes } from '@appweaver/web';
2097
+
2098
+ // model.ts: new fields must be optional or have a default, since the framework creates these records
2099
+ export default extendModel('ApiKey', {
2100
+ scalars: { label: { type: 'string', required: false } },
2101
+ index: ['label'],
2102
+ read: { omit: ['createdById'] }
2103
+ });
2104
+
2105
+ // service.ts: the hooks run after the ones of the framework
2106
+ export default extendService('ApiKey', {
2107
+ afterCreate: async (key) => notifyOwner(key)
2108
+ });
2109
+
2110
+ // policy.ts: both policies must allow, so an extension never loosens the framework's
2111
+ export default extendPolicy('ApiKey', {
2112
+ checkAccess: (user) => !!user && hasRole(user, 'Integrator')
2113
+ });
2114
+
2115
+ // routes.ts: merged option by option over the framework's routes
2116
+ export default extendRoutes('ApiKey', {
2117
+ defaults: { roles: ['Admin', 'Integrator'] }
2118
+ });
2119
+ ```
2120
+
2121
+ | Function | Merges |
2122
+ |-----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
2123
+ | `extendModel` | Field by field: a new field is added (optional or with a default), the options of an existing one overridden (its `type` never changes); `index` and `unique` added; the `omit`/`pick` lists, the update `operations` and the `export` merged. A field cannot be removed. |
2124
+ | `extendService` | The hooks run after the ones of the service (before and after hooks alike); `textSearch` replaces its own. Without a service, the model gets one with the hooks. |
2125
+ | `extendPolicy` | `checkAccess`, `events` and the file and series checks must all pass; the `readRestrictions` of both apply (`AND`); the `writeRestrictions` of the extended policy win. Without a policy, the extension is the policy. |
2126
+ | `extendRoutes` | `defaults` and the config of every route merged option by option; `actions`, `path`, `mcp` and `events` replaced. Without routes (i.e. the key routes off), nothing is registered and a warning is logged: `createRoutes` creates routes. |
2127
+
2128
+ The extensions apply once every resource is loaded, in the order they were declared, so the files of the application
2129
+ extend the models of the modules loaded after them. An extension of a model the application does not have (i.e. of
2130
+ `ApiKey` with `security.apiKey.enabled` off) is skipped with a warning. The auth model keeps `createAuthModel`.
2131
+
2132
+ ---
2133
+
2134
+ ## registerRoute
2135
+
2136
+ Registers a custom Fastify route handler outside the resource system. Use this for endpoints that don't map to a
2137
+ standard CRUD resource. Its `body`, `querystring` and `params` schemas reject undeclared properties, unless an object
2138
+ sets `additionalProperties` explicitly (see the custom route section of SKILL.md).
2139
+
2140
+ ```ts
2141
+ import { registerRoute, Router } from '@appweaver/web';
2142
+ import { Type } from 'typebox';
2143
+
2144
+ registerRoute(
2145
+ async function (router: Router) {
2146
+ router.get('/search-result', {
2147
+ schema: {
2148
+ summary: 'Sample search result response route',
2149
+ response: { 200: Type.Ref('SearchResult') }
2150
+ },
2151
+ handler: async () => {
2152
+ return { message: 'Hello, world!' };
2153
+ }
2154
+ });
2155
+ },
2156
+ { public: true, cache: { ttl: 15000 } }
2157
+ );
2158
+ ```
2159
+
2160
+ ### Config options
2161
+
2162
+ | Property | Type | Description |
2163
+ |-------------------|--------------------------|--------------------------------------------------------------------------------------------------------|
2164
+ | `exclude` | boolean | Skip the registration of a file or series route, though `actions` lists it. |
2165
+ | `public` | boolean | No authentication required. |
2166
+ | `roles` | string[] | Required roles. |
2167
+ | `permissions` | string[] | Required permissions. |
2168
+ | `auth` | AuthType[] | Allowed authentication types. |
2169
+ | `rateLimit` | RateLimitConfig \| false | Rate limiting configuration. |
2170
+ | `compress` | boolean \| object | Response compression: `false`, or `{ threshold, encodings, levels }` over `server.compression`. |
2171
+ | `timeout` | integer | Milliseconds the route may take, `0` for none, over `server.requestTimeout`. |
2172
+ | `recaptcha` | boolean | Require reCAPTCHA verification. |
2173
+ | `recaptchaAction` | string | Expected reCAPTCHA action. |
2174
+ | `turnstile` | boolean | Require Cloudflare Turnstile verification. |
2175
+ | `turnstileAction` | string | Expected Turnstile action. |
2176
+ | `cache` | boolean \| object | Cache the responses: `true`, or `{ scope, ttl, key, skipInvalidation, modelName, relations }`. |
2177
+ | `apiPrefix` | boolean | Register under `server.apiPrefix` (`true`), or at the root (`false`, like the auth and health routes). |
2178
+
2179
+ The error codes a custom route responds with are listed in its `errorResponses`, see
2180
+ [errors.md](./errors.md#documenting-the-errors-of-a-route).
2181
+
2182
+ ---
2183
+
2184
+ ## registerModel
2185
+
2186
+ Registers a custom TypeBox schema as a named model in the schema registry. Registered models can be referenced using
2187
+ `Type.Ref('ModelName')` in route schemas.
2188
+
2189
+ ```ts
2190
+ import { registerModel } from '@appweaver/web';
2191
+ import { Nullable } from '@appweaver/common';
2192
+ import { Type } from 'typebox';
2193
+
2194
+ registerModel(
2195
+ Type.Object(
2196
+ {
2197
+ id: Type.Integer(),
2198
+ title: Type.String({ example: 'My Title' }),
2199
+ description: Nullable(Type.String({ maxLength: 512 })),
2200
+ score: Type.Number({ minimum: 0, maximum: 1 })
2201
+ },
2202
+ { $id: 'SearchResult' } // The preferred way for naming the model
2203
+ ),
2204
+ 'SearchResult' // Model name can be overridden as a second optional argument
2205
+ );
2206
+ ```
2207
+
2208
+ | Parameter | Type | Description |
2209
+ |-----------|---------|--------------------------------------------------------------|
2210
+ | `schema` | TObject | TypeBox object schema definition. |
2211
+ | `name` | string? | Override schema name identifier for `Type.Ref()` references. |
2212
+
2213
+ ---
2214
+
2215
+ ## registerPlugin
2216
+
2217
+ Registers a custom Fastify plugin. Plugins are wrapped with `fastify-plugin` so their decorators and hooks are scoped to
2218
+ the entire server instance.
2219
+
2220
+ ```ts
2221
+ import { registerPlugin } from '@appweaver/web';
2222
+
2223
+ registerPlugin(
2224
+ 'audit-log',
2225
+ async (server) => {
2226
+ server.addHook('onResponse', async (request, reply) => {
2227
+ logger.info(`${request.method} ${request.url} -> ${reply.statusCode}`);
2228
+ });
2229
+ },
2230
+ ['other-plugin'] // optional dependencies
2231
+ );
2232
+ ```
2233
+
2234
+ | Parameter | Type | Description |
2235
+ |----------------|-------------------------------------|-------------------------------------------------------|
2236
+ | `name` | string | Plugin name (used for dependency resolution). |
2237
+ | `plugin` | `(server) => void \| Promise<void>` | Fastify plugin function. |
2238
+ | `dependencies` | string[] | Optional list of plugin names this plugin depends on. |