@appweaver/skill 0.0.0-stage → 3.0.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,2228 @@
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 is `weaver generate`, `weaver migrate`, then `weaver generate`
1108
+ again; `weaver migration check` then reports no migration. A changed `dbType` or expression drops the column and adds it
1109
+ again (its indexes applied again with it); a column removed from a model stays until a SQL migration drops it. Query it with raw SQL:
1110
+
1111
+ ```ts
1112
+ const products = await injectService('Product').client.$queryRaw`
1113
+ SELECT id, name FROM "Product" WHERE search @@ plainto_tsquery('simple', ${text}) LIMIT 20`;
1114
+ ```
1115
+
1116
+ Every foreign key column (relation `<name>Id` columns, `createdById` and `deletedById`) is indexed automatically, since
1117
+ PostgreSQL and SQLite do not index them on their own. A foreign key is skipped when it is already unique (`oneToOne`
1118
+ relations and file fields) or when an explicit `index` or `unique` entry leads with it, so
1119
+ `index: [['categoryId', '-publishedAt']]` replaces the automatic `@@index([categoryId])`. Set `index: false` on a
1120
+ relation to leave its foreign key unindexed, i.e. for a rarely queried relation of a write-heavy model:
1121
+
1122
+ ```ts
1123
+ const config = {
1124
+ relations: {
1125
+ author: {
1126
+ model: 'User',
1127
+ type: 'manyToOne',
1128
+ index: false
1129
+ }
1130
+ }
1131
+ };
1132
+ ```
1133
+
1134
+ The audit columns `createdById` and `deletedById` are always indexed.
1135
+
1136
+ ### Unique config
1137
+
1138
+ `unique` takes the same shape as `index` and emits `@@unique` constraints. Use it for a combination of columns that must
1139
+ be unique together; a single column is better marked with the scalar's own `unique: true`:
1140
+
1141
+ ```ts
1142
+ unique: [['provider', 'providerAccountId']]; // @@unique([provider, providerAccountId])
1143
+ ```
1144
+
1145
+ A create or update breaking the constraint fails in the database, so handle the conflict where concurrent writes can
1146
+ race to insert the same combination.
1147
+
1148
+ A unique constraint of SQL Server holds a single NULL, so on SQL Server an optional unique column, i.e. a scalar with
1149
+ `unique: true` and `required: false`, the foreign key of an optional `oneToOne` relation or of a single file field, is
1150
+ generated as a unique index of its values instead, `@@unique([coverId], where: { coverId: { not: null } })`, with the
1151
+ `partialIndexes` preview feature of Prisma enabled in the generator block.
1152
+
1153
+ ### Generated models
1154
+
1155
+ `createModel` produces the following TypeBox schema models used internally by routes and services:
1156
+
1157
+ | Model | Purpose |
1158
+ |--------------------------|------------------------------------------------|
1159
+ | `readModel` | Full model with all visible fields |
1160
+ | `createModel` | Request body for create operations |
1161
+ | `updateModel` | Request body for update operations |
1162
+ | `relationsModel` | Relations-only subset |
1163
+ | `virtualModel` | Virtual fields-only subset |
1164
+ | `filesModel` | File fields-only subset |
1165
+ | `readOneModel` | Response for single-item reads |
1166
+ | `readManyModel` | Response for list reads |
1167
+ | `readOneNullableModel` | `readOneModel` or null, for optional relations |
1168
+ | `createOneModel` | Request for create endpoint |
1169
+ | `updateOneModel` | Request for update endpoint |
1170
+ | `fileUploadModel` | Request for file upload endpoint |
1171
+ | `fileDeleteModel` | Request for file delete endpoint |
1172
+ | `fileVersionDeleteModel` | Request for file version delete endpoint |
1173
+ | `seriesModel` | The values of the series fields |
1174
+
1175
+ ---
1176
+
1177
+ ## createService
1178
+
1179
+ Creates a resource service with lifecycle hooks and business logic. The service handles all database operations for a
1180
+ model and triggers hooks on each CRUD operation before/after.
1181
+
1182
+ ```ts
1183
+ import { createService } from '@appweaver/data';
1184
+
1185
+ export default createService({
1186
+ modelName: 'Product',
1187
+ afterCreate: (resource) => {
1188
+ logger.info(`Product created: ${resource.id}`);
1189
+ },
1190
+ textSearch: {
1191
+ title: { contains: '{input}', mode: 'insensitive' }
1192
+ }
1193
+ });
1194
+ ```
1195
+
1196
+ ### Configuration
1197
+
1198
+ ```ts
1199
+ function createService(
1200
+ config: ResourceServiceConfig,
1201
+ override?: boolean // replace the one defined for the model (default: false)
1202
+ ) {}
1203
+ ```
1204
+
1205
+ | Property | Type | Description |
1206
+ |-------------------|--------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
1207
+ | `modelName` | string | Model name to bind this service to (required). |
1208
+ | `beforeFind` | `(id) => void` | Hook called before finding a single resource. |
1209
+ | `beforeQuery` | `(options) => void` | Hook called before querying resources, with the query options as given. Mutate `options` to change the query. |
1210
+ | `beforeAggregate` | `(options) => void` | Hook called before aggregation, with the aggregation options as given. Mutate `options` to change the aggregation. |
1211
+ | `beforeCreate` | `(data) => void` | Hook called before creating a resource. Mutate `data` to modify input. |
1212
+ | `beforeUpdate` | `(id, data) => void` | Hook called before updating or replacing a resource. |
1213
+ | `beforeDelete` | `(id) => void` | Hook called before deleting a resource. |
1214
+ | `afterFind` | `(resource) => void` | Hook called after finding a resource. |
1215
+ | `afterQuery` | `(response) => void` | Hook called after querying resources. |
1216
+ | `afterAggregate` | `(response) => void` | Hook called after aggregation. |
1217
+ | `afterCreate` | `(resource) => void` | Hook called after creating a resource. |
1218
+ | `afterUpdate` | `(resource, previous) => void` | Hook called after updating or replacing a resource, with the state the resource had before the update. |
1219
+ | `afterDelete` | `(resource) => void` | Hook called after deleting a resource. |
1220
+ | `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`. |
1221
+
1222
+ All hooks can be synchronous or return a `Promise`. Every operation also emits a resource event once committed,
1223
+ received with `onResourceEvent` ([events.md](./events.md)), and the service calls made inside `runTransaction` commit
1224
+ together ([database.md](./database.md#transactions)).
1225
+
1226
+ ### Service methods
1227
+
1228
+ The created service exposes the following methods:
1229
+
1230
+ | Method | Signature | Description |
1231
+ |-------------|------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------|
1232
+ | `find` | `(id) => Promise<ReadOne>` | Find a single resource by ID. |
1233
+ | `single` | `(filter?, sort?) => Promise<ReadOne \| null>` | Find the first resource matching the filter, ordered by `sort` (default `-createdAt`), or `null` when none matches. |
1234
+ | `query` | `(options?) => Promise<QueryResponse>` | Query resources with filtering, pagination, and sorting (see [Query sorting](#query-sorting) and [Cursor pagination](#cursor-pagination)). |
1235
+ | `count` | `(filter?) => Promise<number>` | Count the resources matching the filter. |
1236
+ | `exists` | `(filter?) => Promise<boolean>` | Check whether any resource matches the filter. |
1237
+ | `aggregate` | `(options) => Promise<AggregateResponse>` | Aggregate resources with time-series grouping (see [Aggregate selection](#aggregate-selection)). |
1238
+ | `create` | `(data) => Promise<ReadOne>` | Create a new resource. |
1239
+ | `update` | `(id, data) => Promise<ReadOne>` | Update the given fields of a resource (`PATCH /:id`). |
1240
+ | `replace` | `(id, data) => Promise<ReadOne>` | Replace a resource as a whole (`PUT /:id`). |
1241
+ | `delete` | `(id) => Promise<ReadOne>` | Delete a resource. |
1242
+ | `client` | `ResourceClient` (property) | Database client of the model, for operations outside the model contract. |
1243
+
1244
+ `query` takes the options `filter`, `page` (default `1`), `size` (default `50`), `sort` (default `-createdAt`),
1245
+ `cursor`, and `totalCount` (default `false`), and `aggregate` the options `select` (required), `filter`, `dateField`
1246
+ (default `createdAt`), `from`, `to`, and `interval` (see [Aggregate selection](#aggregate-selection)). Both are the same shape as the bodies
1247
+ of the `POST /query` and `POST /aggregate` routes, and as the query parameters of their GET variants:
1248
+
1249
+ ```ts
1250
+ const posts = injectService('Post');
1251
+ const page = await posts.query({
1252
+ filter: { status: 'Published' },
1253
+ size: 20,
1254
+ sort: '-publishedAt'
1255
+ });
1256
+ const latest = await posts.single({ status: 'Published' }, '-publishedAt');
1257
+ const drafts = await posts.count({ status: 'Draft' });
1258
+ ```
1259
+
1260
+ ### Typed models
1261
+
1262
+ The types `weaver generate` emits register every model in the `ResourceRegistry` of `@appweaver/common`, so the
1263
+ factories and `injectService` infer the model types from a model name:
1264
+
1265
+ - `createService({ modelName: 'Post' })` and `createAuthService` type their hooks with `Post`, `PostCreate`, and
1266
+ `PostUpdate`, and the `replace` method of the service with `PostReplace`.
1267
+ - `createPolicy({ modelName: 'Post' })` types the records its callbacks receive as `Post` along with the foreign key
1268
+ columns of the database record.
1269
+ - `injectService('Post')` returns the `PostResourceService` alias.
1270
+ - The `modelName` of every factory, and the `model` of a relation, only accept registered model names, and the
1271
+ `mappedBy` of a relation suggests the relations of the target model.
1272
+
1273
+ ```ts
1274
+ import { injectService } from '@appweaver/core';
1275
+
1276
+ const posts = injectService('Post'); // PostResourceService
1277
+ ```
1278
+
1279
+ Never pass the model types as generic arguments. A model added since the last `weaver generate` is not registered
1280
+ yet, so run `weaver generate` after adding or renaming a model or a relation. The `--no-registry` flag of
1281
+ `weaver generate` skips the registration.
1282
+
1283
+ The `PostResourceService` alias is `IResourceService<Post, PostMultiple, PostCreate, PostUpdate, PostQuery>`, so the
1284
+ `<Model>Query`, `<Model>Sort`, and `<Model>Aggregate` aliases are exactly the inputs its methods accept.
1285
+
1286
+ The `create` and `update` inputs are the model's declared contracts, so a field an operation config omits, a hidden
1287
+ scalar, or a relation with `input: { type: 'none' }` is deliberately not part of them. A write outside the contract
1288
+ belongs on `service.client`, the database client of the model.
1289
+
1290
+ ### Query filters
1291
+
1292
+ The `filter` option of `query` and `aggregate`, and the `filter` argument of `single`, `count`, `exists`, and `export`
1293
+ mirror the WHERE part of a database query. The matching
1294
+ `POST /query`, `POST /aggregate`, and `POST /export` routes accept the same structure, validated against a generated
1295
+ per-model `<Model>QueryFilter` schema that rejects unknown and hidden fields with a `400` `VALIDATION_FAILED` error
1296
+ naming the field, i.e. `{ "field": "filter.titel", "rule": "additionalProperties", "message": "is not allowed" }`.
1297
+
1298
+ A filter is bounded, so one request cannot build a query the database takes seconds to plan: at most
1299
+ `resource.filterMaxConditions` conditions (every field and operator key, nested filters included, `1000`),
1300
+ `resource.filterMaxDepth` nesting levels (`10`) and `resource.filterMaxListValues` values in a list (`2000`). A filter
1301
+ beyond them is refused with `400` `RESOURCE_FILTER_TOO_COMPLEX`, the details naming the `limit` and its `max`, before the
1302
+ request is validated; the service methods check the same limits. A JSON body is limited to `server.jsonBodyMaxSize`
1303
+ (`10M`), apart from the uploads (`server.bodyMaxSize`).
1304
+
1305
+ **Logical operators** (filter level) — take a single filter object (each entry becomes one condition) or a list of them:
1306
+
1307
+ | Operator | Description |
1308
+ |----------|-------------------------------------------|
1309
+ | `_and` | All nested conditions must match. |
1310
+ | `_or` | At least one nested condition must match. |
1311
+ | `_not` | No nested condition may match. |
1312
+ | `_nor` | Alias of `_not`. |
1313
+
1314
+ **Comparison operators** (field level) — combined inside one object, all must match:
1315
+
1316
+ | Operator | Description |
1317
+ |---------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
1318
+ | `_eq` | Equal to the given value. |
1319
+ | `_ne` | Not equal to the given value. |
1320
+ | `_gt`, `_gte`, `_lt`, `_lte` | Greater/lower than (or equal to) the given value. |
1321
+ | `_in`, `_nin` | Included / not included in the given list. |
1322
+ | `_between` | Inside the inclusive `[min, max]` range. |
1323
+ | `_like` | SQL LIKE pattern with `%` wildcards (`Luk%` → starts with, `%avatar%` → contains, `%png` → ends with, no wildcard → equals). |
1324
+ | `_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. |
1325
+ | `_starts`, `_ends`, `_contains` | Starts with / ends with / contains the given string. |
1326
+ | `_exists` | Not null (`true`) or null (`false`). |
1327
+ | `_not` | Negates a nested operator object or plain value. |
1328
+
1329
+ **List (array scalar) operators**: `_has`, `_hasSome`, `_hasEvery`, `_isEmpty`.
1330
+
1331
+ **Relation operators**: `_some`, `_every`, `_none` take a filter of the related model; `_exists` maps to an `is`/`isNot`
1332
+ null check on a single relation and to `some`/`none` on a list relation.
1333
+
1334
+ **Plain value shorthands**: a bare value matches by equality, a list by inclusion, a two-value list on a numeric or date
1335
+ field as an inclusive range, a value or list on a relation by id, an array field uses `has`/`hasSome`, and `null`
1336
+ matches missing values or related records.
1337
+
1338
+ ```json
1339
+ {
1340
+ "filter": {
1341
+ "_and": {
1342
+ "firstName": {
1343
+ "_eq": "Luka",
1344
+ "_exists": true
1345
+ },
1346
+ "avatar": {
1347
+ "_or": {
1348
+ "title": {
1349
+ "_eq": "New user avatar"
1350
+ },
1351
+ "description": {
1352
+ "_like": "%avatar%"
1353
+ }
1354
+ },
1355
+ "originalName": {
1356
+ "_eq": "new_user_avatar.png"
1357
+ }
1358
+ }
1359
+ },
1360
+ "_or": [
1361
+ {
1362
+ "firstName": {
1363
+ "_like": "Luk%"
1364
+ }
1365
+ },
1366
+ {
1367
+ "lastName": "Matošević"
1368
+ }
1369
+ ],
1370
+ "tags": {
1371
+ "_some": {
1372
+ "name": {
1373
+ "_contains": "news"
1374
+ }
1375
+ }
1376
+ }
1377
+ },
1378
+ "page": 1,
1379
+ "size": 50,
1380
+ "sort": "-createdAt",
1381
+ "totalCount": true
1382
+ }
1383
+ ```
1384
+
1385
+ The `QueryFilter<T>` type from `@appweaver/common` provides code completion, and `weaver generate` emits a
1386
+ `<Model>Query = QueryFilter<Model>` alias per model:
1387
+
1388
+ ```ts
1389
+ import { QueryFilter } from '@appweaver/common';
1390
+ import { User, UserQuery } from '@/types/generated';
1391
+
1392
+ const filter: UserQuery = {
1393
+ _and: {
1394
+ firstName: { _eq: 'Luka' },
1395
+ loginAt: { _exists: true }
1396
+ }
1397
+ };
1398
+ const users = await userService.query({ filter });
1399
+ ```
1400
+
1401
+ ### Query sorting
1402
+
1403
+ The `sort` argument of `query` and `export` (and the `sort` property of the `POST /query` and `POST /export` request
1404
+ bodies) accepts two interchangeable forms, both applying their fields in the declared order:
1405
+
1406
+ ```json
1407
+ {
1408
+ "sort": "-author.createdAt,tagsCount,id"
1409
+ }
1410
+ ```
1411
+
1412
+ ```json
1413
+ {
1414
+ "sort": {
1415
+ "author": {
1416
+ "createdAt": "desc"
1417
+ },
1418
+ "tagsCount": "asc",
1419
+ "id": "asc"
1420
+ }
1421
+ }
1422
+ ```
1423
+
1424
+ In the string form a `-` prefix sorts descending (`+` or no prefix ascending) and a dot notation path targets a relation
1425
+ field. In the object form a relation takes a nested object, and the only accepted directions are the lower case `asc`
1426
+ and `desc`.
1427
+
1428
+ | Field | String form | Object form | Notes |
1429
+ |------------------------|---------------------|-------------------------------------|----------------------------------------------------------------------------------------|
1430
+ | Scalar, `id`, audit | `title`, `-id` | `{ title: 'asc' }` | Hidden scalars, array scalars, and virtual fields cannot be sorted by. |
1431
+ | To-one relation field | `-author.createdAt` | `{ author: { createdAt: 'desc' } }` | The relation must be included in the response of the action, at any nesting depth. |
1432
+ | To-many relation count | `-tagsCount` | `{ tagsCount: 'desc' }` | Sorts by the number of related records; the relation name alone (`-tags`) is an alias. |
1433
+
1434
+ Anything else — a relation the action does not include, a field of a to-many relation, a hidden or virtual field, an
1435
+ unknown sort direction — is rejected with a `400` error naming the offending field instead of reaching the database.
1436
+ Over HTTP the sort object is additionally validated against a generated per-model `<Model>QuerySort` schema, which
1437
+ rejects unknown fields the same way the query filter schema does.
1438
+
1439
+ The default sort is `-createdAt`. Every sort is terminated with the primary key when it does not already order by one,
1440
+ so paging stays deterministic, and the `createdAt` entry is dropped for models configured with
1441
+ `audit: { createdAt: false }`.
1442
+
1443
+ Sort inputs are typed by `QuerySort<T>` from `@appweaver/common`, and `weaver generate` emits a
1444
+ `<Model>Sort = QuerySort<<Model>Multiple>` alias per model, built from the query output model so it only offers the
1445
+ relations a query response includes:
1446
+
1447
+ ```ts
1448
+ import { PostSort } from '@/types/generated';
1449
+
1450
+ const sort: PostSort = { author: { lastName: 'asc' }, createdAt: 'desc' };
1451
+ const posts = await postService.query({ sort });
1452
+ ```
1453
+
1454
+ ### Query response
1455
+
1456
+ ```ts
1457
+ const config = {
1458
+ resultCount: 50, // Items in this page
1459
+ totalCount: 123, // Items matching the filter, up to resource.countLimit; null unless totalCount was asked
1460
+ totalCountExact: true, // false when the count stopped at resource.countLimit or a full-text search at resource.textSearchMaxMatches; null when not counted
1461
+ nextCursor: '...', // Cursor of the following page, absent on the last page
1462
+ prevCursor: '...', // Cursor of the preceding page, absent on the first page
1463
+ items: [] // Page data
1464
+ };
1465
+ ```
1466
+
1467
+ ### Cursor pagination
1468
+
1469
+ The response returns a `nextCursor` and a `prevCursor`; send one back as `cursor` to get that page. The direction is
1470
+ part of the cursor, so a request never names one. A cursor takes precedence over `page` and does not slow down on the
1471
+ later pages.
1472
+
1473
+ ```ts
1474
+ // First page counted, the following ones skipping the count
1475
+ let result = await postService.query({ size: 50, totalCount: true });
1476
+
1477
+ while (result.nextCursor) {
1478
+ result = await postService.query({ size: 50, cursor: result.nextCursor });
1479
+ }
1480
+ ```
1481
+
1482
+ ```json5
1483
+ // POST /posts/query
1484
+ {
1485
+ filter: {
1486
+ enabled: true
1487
+ },
1488
+ size: 50,
1489
+ sort: '-createdAt',
1490
+ cursor: 'eyJpIjo0MiwiZiI6IkhkQjVfa2VMTVlyNyJ9'
1491
+ }
1492
+ ```
1493
+
1494
+ `totalCount` defaults to `false` (returned as `null`): ask for it on the first page only, since it scans the matching
1495
+ records. The count stops at `resource.countLimit` (10,000), answering that number with `totalCountExact: false`. An
1496
+ offset page skipping more than `resource.maxOffset` records (10,000) is refused with `400 RESOURCE_OFFSET_TOO_LARGE`:
1497
+ page deeper with the cursors, which never slow down.
1498
+
1499
+ A cursor is opaque and bound to the query that issued it: reusing one under a different resource, filter, or sort is
1500
+ rejected with a 400.
1501
+
1502
+ ### Aggregate selection
1503
+
1504
+ The `select` argument of `aggregate` (and the required `select` property of the `POST /aggregate` request body) holds
1505
+ the operators to apply per field. Only the fields the database can aggregate are accepted, which are the numeric and
1506
+ date scalars of the model together with its numeric `id` and audit fields:
1507
+
1508
+ | Field kind | Operators |
1509
+ |------------------------------------|------------------------------------------------------|
1510
+ | Numeric (`int`, `bigInt`, `float`) | `count`, `sum`, `avg`, `min`, `max`, `first`, `last` |
1511
+ | Date (`dateTime`) | `count`, `min`, `max`, `first`, `last` |
1512
+
1513
+ ```json
1514
+ {
1515
+ "select": {
1516
+ "counter": {
1517
+ "count": true,
1518
+ "sum": true,
1519
+ "avg": true,
1520
+ "first": true,
1521
+ "last": true
1522
+ },
1523
+ "publishedAt": {
1524
+ "min": true,
1525
+ "max": true
1526
+ }
1527
+ },
1528
+ "dateField": "createdAt",
1529
+ "from": "2026-01-01T00:00:00.000Z",
1530
+ "to": "2026-01-08T00:00:00.000Z",
1531
+ "interval": "1d"
1532
+ }
1533
+ ```
1534
+
1535
+ **The range and the periods**: `from` is inclusive and `to` exclusive, on the `dateField`. Without them the aggregate
1536
+ covers every record of the filter. `interval` splits the range into periods, an amount and a unit of `s`, `m`, `h`,
1537
+ `d`, `w`, `mo` or `y` (`'15m'`, `'1d'`, `'3mo'`), the calendar units (`d` and longer) in the local time of the server,
1538
+ keeping the time of day across daylight saving time changes. Without `from` the periods start at the earliest record
1539
+ of the filter truncated to the unit, without `to` they end after the latest one, and a filter matching no record
1540
+ answers no period. Without `interval` the response holds the `total` only (`items: []`). A range of more than
1541
+ `resource.aggregateMaxPeriods` periods (1000, at most 10,000) is rejected with `RESOURCE_INVALID_AGGREGATE`.
1542
+
1543
+ **One statement**: the aggregate runs as one SQL statement, the records grouped by period, the total in a row of its
1544
+ own, and `first` and `last` taken with window functions. A filter it cannot express in SQL (a relation, a JSON or a list
1545
+ filter) falls back to one Prisma aggregation per period in a transaction, with up to two extra queries per non-empty
1546
+ period for `first` and `last`.
1547
+
1548
+ **`first` and `last`** take the value held by the earliest and the latest record of a period, ordered by the aggregated
1549
+ `dateField` (ties broken by `id`), or `null` for a period holding no record.
1550
+
1551
+ Any other field, an operator its field kind does not support, and an empty selection are rejected with a `400` error.
1552
+ Over HTTP the selection is also validated against a generated per-model `<Model>AggregateSelect` schema. The `dateField`
1553
+ must be a date field of the model (`createdAt` by default).
1554
+
1555
+ Selections are typed by `AggregateSelect<T>` from `@appweaver/common`, with a `<Model>Aggregate` alias emitted per
1556
+ model:
1557
+
1558
+ ```ts
1559
+ import { PostAggregate } from '@/types/generated';
1560
+
1561
+ const select: PostAggregate = {
1562
+ counter: { sum: true },
1563
+ createdAt: { max: true }
1564
+ };
1565
+ const stats = await postService.aggregate({ select });
1566
+ ```
1567
+
1568
+ `aggregate` infers the response type from the selection it is given, so a selection passed as an object literal, or
1569
+ declared with `satisfies`, narrows the response to the fields it names, while one annotated as `<Model>Aggregate` keeps
1570
+ every aggregatable field of the model:
1571
+
1572
+ ```ts
1573
+ const narrow = await postService.aggregate({
1574
+ select: { counter: { sum: true } }
1575
+ });
1576
+ narrow.total.counter?.sum; // typed
1577
+ narrow.total.createdAt; // compile error, the field was not selected
1578
+
1579
+ const select = { counter: { sum: true } } satisfies PostAggregate; // narrows and checks against the model
1580
+ const wide: PostAggregate = { counter: { sum: true } }; // keeps the whole model in the response type
1581
+ ```
1582
+
1583
+ ### Aggregate response
1584
+
1585
+ The response shape follows whatever was selected, and its type carries the fields of the selection (see
1586
+ [Aggregate selection](#aggregate-selection)). Each aggregated field holds one property per operator applied to it, and
1587
+ the operators the selection left out are `undefined`:
1588
+
1589
+ ```ts
1590
+ const resp = {
1591
+ total: AggregateValue, // Overall aggregation
1592
+ items: Array<AggregateResult> // Per-period results
1593
+ };
1594
+
1595
+ // Each AggregateResult:
1596
+ const result = {
1597
+ date: 'Date', // the start of the period
1598
+ result: {
1599
+ [field]: {
1600
+ count: 123,
1601
+ min: 123, // an ISO date string for a date field
1602
+ max: 123, // an ISO date string for a date field
1603
+ avg: 123, // numeric fields only
1604
+ sum: 123, // numeric fields only
1605
+ first: 123, // value of the earliest record of the period
1606
+ last: 123 // value of the latest record of the period
1607
+ }
1608
+ }
1609
+ };
1610
+ ```
1611
+
1612
+ ### Text search example
1613
+
1614
+ The full-text mode matches the `searchText` of a query with the full-text index of the database, set up when the
1615
+ application starts and by `weaver migrate` (with the user of `database.migrationUrl`), like the PostGIS triggers. Use it
1616
+ 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):
1617
+
1618
+ ```ts
1619
+ export default createService({
1620
+ modelName: 'Post',
1621
+ textSearch: {
1622
+ mode: 'fts',
1623
+ fields: ['title', 'excerpt', 'content'],
1624
+ language: 'english' // PostgreSQL text search configuration, SQL Server column language (default: simple)
1625
+ }
1626
+ });
1627
+ ```
1628
+
1629
+ - Every word of the text (a run of letters and digits, at most 16, the rest of the text ignored) must match the start
1630
+ of a word of one of the fields, the case ignored: `trail vele` matches "Walking the Velebit trail". The diacritics
1631
+ are ignored on SQLite, kept on PostgreSQL (unless the `language` is a configuration with `unaccent`), and compared
1632
+ by the collation on MySQL and the accent sensitivity of the catalog on SQL Server.
1633
+ - The query keeps the `resource.textSearchMaxMatches` (1,000) most relevant matches, then applies the rest of the
1634
+ filter, the policy and the sort, so a broad search may miss records the filter and the policy would keep. Its count
1635
+ stops there too, answered with `totalCountExact: false` when the search reached the limit.
1636
+ - The index, per database: an FTS5 table kept in line by triggers on SQLite (`<table>_fts_<hash>`, keyed by the
1637
+ integer id, or by a table of the keys `<table>_fts_<hash>_keys` for a string id, whose `rowid` a table copy
1638
+ renumbers), set up again when a Prisma migration redefining the table dropped its triggers, and left out of the
1639
+ migrations by `weaver migration new` and `weaver migration check`, a GIN index of the
1640
+ `to_tsvector` of the fields on PostgreSQL, a `FULLTEXT` index on MySQL (the words shorter than `innodb_ft_min_token_size`,
1641
+ 3 by default, and its stop words are not indexed, and Prisma sees it as a drift, see
1642
+ [database.md](./database.md)), and a full-text index of the primary key on SQL Server, which
1643
+ needs the Full-Text Search feature installed and fills the index in the background, a new record matching a moment
1644
+ later. A change of the fields replaces the index when the application starts; on SQL Server a change of the
1645
+ `language` alone is not detected, drop the index (`DROP FULLTEXT INDEX ON [Post]`) to have it created again.
1646
+ - The fields are string scalars of the model, not lists.
1647
+
1648
+ Object form with placeholder, replaced by the searched text wherever it appears in a string value:
1649
+
1650
+ ```ts
1651
+ const config = {
1652
+ textSearch: {
1653
+ title: {
1654
+ contains: '{input}',
1655
+ mode: 'insensitive'
1656
+ }
1657
+ }
1658
+ };
1659
+ ```
1660
+
1661
+ An `OR` given as an object is turned into a list, each entry becoming one condition, as the `_or` filter operator does:
1662
+
1663
+ ```ts
1664
+ const config = {
1665
+ textSearch: {
1666
+ OR: {
1667
+ title: { contains: '{input}' },
1668
+ excerpt: { contains: '{input}' }
1669
+ }
1670
+ }
1671
+ };
1672
+ ```
1673
+
1674
+ `mode: 'insensitive'` is supported on PostgreSQL and MongoDB only, the database rejects it on SQLite, MySQL, and SQL
1675
+ Server, where `contains` already ignores the case with the default collation (ASCII letters only on SQLite).
1676
+
1677
+ Function form for complex queries:
1678
+
1679
+ ```ts
1680
+ const config = {
1681
+ textSearch: (input) => ({
1682
+ OR: [
1683
+ { title: { contains: input, mode: 'insensitive' } },
1684
+ { description: { contains: input, mode: 'insensitive' } }
1685
+ ]
1686
+ })
1687
+ };
1688
+ ```
1689
+
1690
+ ---
1691
+
1692
+ ## createRoutes
1693
+
1694
+ Creates CRUD route definitions for a resource. Routes are automatically registered with Fastify and derive their
1695
+ request/response schemas from the resource model.
1696
+
1697
+ ```ts
1698
+ import { createRoutes } from '@appweaver/web';
1699
+
1700
+ export default createRoutes({
1701
+ modelName: 'Product',
1702
+ path: '/products',
1703
+ find: { roles: ['Admin', 'User'], rateLimit: { max: 100 } },
1704
+ actions: ['find', 'query', 'create', 'update', 'replace'], // no delete
1705
+ query: { cache: { ttl: 5000 } },
1706
+ create: { permissions: ['product:create'] }
1707
+ });
1708
+ ```
1709
+
1710
+ ### Configuration
1711
+
1712
+ ```ts
1713
+ function createRoutes(
1714
+ config: ResourceRoutesConfig,
1715
+ override?: boolean // replace the one defined for the model (default: false)
1716
+ ) {}
1717
+ ```
1718
+
1719
+ | Property | Type | Description |
1720
+ |---------------------|------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
1721
+ | `modelName` | string | Model name to bind routes to (required). |
1722
+ | `path` | string | Custom base URL path (default: derived from model name). |
1723
+ | `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)). |
1724
+ | `defaults` | QueryRouteConfig | Config applied to every route (see [Route defaults](#route-defaults)). |
1725
+ | `find` | ReadRouteConfig | `GET /:id` - Find single resource by ID. |
1726
+ | `query` | QueryRouteConfig | `POST /query` - Query resources with filters. |
1727
+ | `aggregate` | QueryRouteConfig | `POST /aggregate` - Aggregate resources. |
1728
+ | `create` | RouteConfig | `POST /` - Create a new resource. |
1729
+ | `update` | RouteConfig | `PATCH /:id` - Update a resource (inherited by `replace`). |
1730
+ | `replace` | RouteConfig | `PUT /:id` - Replace a resource (inherits `update`). |
1731
+ | `delete` | RouteConfig | `DELETE /:id` - Delete a resource. |
1732
+ | `export` | RouteConfig | `POST /export` - Export resources to CSV. |
1733
+ | `fileUpload` | RouteConfig | `POST /:id/files` - Upload files to a resource. |
1734
+ | `fileDelete` | RouteConfig | `POST /:id/delete-files` - Delete files from a resource. |
1735
+ | `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. |
1736
+ | `fileVersionDelete` | RouteConfig | `POST /:id/delete-file-versions` - Delete versions of files, `latest` restoring the previous version (inherits `fileDelete`). Registered like `fileVersions`. |
1737
+ | `seriesWrite` | SeriesWriteRouteConfig | `POST /:id/series`, `POST /series` - Write time series points ([timeseries.md](./timeseries.md)). |
1738
+ | `seriesQuery` | RouteConfig | `GET /:id/series`, `POST /series/query` - Query time series points. |
1739
+ | `seriesDelete` | RouteConfig | `POST /:id/delete-series` - Delete the time series points of a range. |
1740
+ | `bulkCreate` | BulkRouteConfig | `POST /bulk` - Create many (with the `bulkCreate` action). |
1741
+ | `bulkUpdate` | BulkRouteConfig | `PATCH /bulk` - Update many (with the `bulkUpdate` action). |
1742
+ | `bulkReplace` | BulkRouteConfig | `PUT /bulk` - Replace many (with the `bulkReplace` action, inherits `bulkUpdate`). |
1743
+ | `bulkDelete` | BulkRouteConfig | `DELETE /bulk` - Delete many (with the `bulkDelete` action). |
1744
+ | `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)). |
1745
+ | `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)). |
1746
+
1747
+ ### File and series routes
1748
+
1749
+ The routes of the file fields and of the time series fields are registered only when `actions` lists them, and only
1750
+ for a model having such fields: `['crud', 'files']`, or a single one, `['find', 'query', 'fileVersions']`. A route
1751
+ group without them, i.e. a read only one, has none, whatever the fields of its model. The routes of a view
1752
+ (`view`) serve the files only when the view reads (`fileVersions`) or writes (`fileUpload`, `fileDelete`,
1753
+ `fileVersionDelete`) every file field of the model, since these routes take any of them, and the time series routes
1754
+ are never registered for a view.
1755
+
1756
+ ```ts
1757
+ export default createRoutes({
1758
+ modelName: 'Product',
1759
+ actions: ['crud', 'files', 'series'],
1760
+ fileUpload: { roles: ['Admin'] }
1761
+ });
1762
+ ```
1763
+
1764
+ ### Route defaults
1765
+
1766
+ `defaults` takes any route option and applies it to every route, unless the route sets the option itself. Caching
1767
+ options reach only `find`, `query`, and `aggregate`, and `method` only `query` and `aggregate`. A route setting any of
1768
+ `public`, `roles`, `permissions`, or `auth` inherits none of them from the defaults, and the same holds for
1769
+ `recaptcha` and `recaptchaAction`, and for `turnstile` and `turnstileAction`.
1770
+
1771
+ ```ts
1772
+ export default createRoutes({
1773
+ modelName: 'Product',
1774
+ defaults: { roles: ['Admin'], cache: true, rateLimit: { max: 100 } },
1775
+ query: { public: true, cache: false } // public, not cached, rate limited
1776
+ });
1777
+ ```
1778
+
1779
+ ### Route config (all operations)
1780
+
1781
+ | Property | Type | Default | Description |
1782
+ |-------------------|--------------------------|---------|-------------------------------------------------------------------------------------------------------------------------------|
1783
+ | `public` | boolean | `false` | No authentication required. |
1784
+ | `roles` | string[] | - | Required roles (OR logic by default). |
1785
+ | `permissions` | string[] | - | Required permissions (OR logic by default). |
1786
+ | `auth` | AuthType[] | - | Allowed authentication types: `'jwt'`, `'apiKey'`, `'basic'`. |
1787
+ | `rateLimit` | RateLimitConfig \| false | - | Per-operation rate limiting. `false` disables. |
1788
+ | `compress` | boolean \| object | config | Response compression: `false`, or `{ threshold, encodings, levels }` over `server.compression`. |
1789
+ | `timeout` | integer | config | Milliseconds the route may take, `0` for none, over `server.requestTimeout` (`503 REQUEST_TIMEOUT`). |
1790
+ | `recaptcha` | boolean | `false` | Require reCAPTCHA verification. |
1791
+ | `recaptchaAction` | string | - | Expected reCAPTCHA action name for score validation. |
1792
+ | `turnstile` | boolean | `false` | Require Cloudflare Turnstile verification. |
1793
+ | `turnstileAction` | string | - | Expected Turnstile action name (enables the check). |
1794
+ | `errorCodes` | ErrorCode[] | - | Codes the route responds with besides the framework ones (a service hook throws them), listed in its OpenAPI error responses. |
1795
+
1796
+ `roles`, `permissions` and `auth` are checked as described in [security.md](./security.md#authorization), and the
1797
+ `errorCodes` are documented like the `errorResponses` of a custom route
1798
+ ([errors.md](./errors.md#documenting-the-errors-of-a-route)).
1799
+
1800
+ ### Read route config (find, query, aggregate)
1801
+
1802
+ Extends RouteConfig with caching options (the global TTL and invalidation strategy are in [cache.md](./cache.md)):
1803
+
1804
+ | Property | Type | Default | Description |
1805
+ |----------|-------------------|---------|-----------------------------------------------------------------------------|
1806
+ | `cache` | boolean \| object | `false` | Cache the responses: `true`, or `{ scope, ttl, skipInvalidation }` (below). |
1807
+
1808
+ | `cache` option | Type | Default | Description |
1809
+ |--------------------|--------------------------------------|----------------------------------------------|------------------------------------------------|
1810
+ | `scope` | `'public'` \| `'user'` \| `'shared'` | `public` on a public route, `user` otherwise | Who an entry is served to (below). |
1811
+ | `ttl` | number | `cache.defaultTtl` | Time to live in milliseconds. |
1812
+ | `skipInvalidation` | boolean | `false` | Skip the automatic invalidation on the writes. |
1813
+
1814
+ The scopes:
1815
+
1816
+ - `public`: a route without authentication (`public: true`), one entry for every request. Refused on an authenticated
1817
+ route, which would serve one user's response to another.
1818
+ - `user`: an entry per user, the default of an authenticated route.
1819
+ - `shared`: an authenticated route answering every user alike, one entry for all of them, served to every user the
1820
+ route lets in. A resource route accepts it only when neither the policy of its model (and of its `view`) nor the one
1821
+ of a model its responses include or count (and of the view a relation reads) has `readRestrictions` or `checkAccess`,
1822
+ failing at startup otherwise; a virtual field reading the
1823
+ current user must not be on it either. On a custom route the application is the judge.
1824
+
1825
+ The cache key of a resource route is built from the model, the route and the request (and the user in the `user`
1826
+ scope, with the API key it authenticated with, whose scope may narrow its roles), so the invalidation of the model's
1827
+ writes reaches it. A cached response replays only the headers describing its payload (`content-type`,
1828
+ `content-disposition`, `content-language`, `etag`, `last-modified`, `cache-control`, `vary`); the others, such as the
1829
+ CORS origin or the rate limit counters, are set again for every request. A custom `key`, with `modelName` and
1830
+ `relations`, is an option of the `cache` of the custom routes of [`registerRoute`](#registerroute) only: it replaces
1831
+ the request in the key, never the scope (the user in the `user` scope) nor the models evicting the entry.
1832
+
1833
+ ### Query route config (query, aggregate)
1834
+
1835
+ Extends ReadRouteConfig with the HTTP methods of the route:
1836
+
1837
+ | Property | Type | Default | Description |
1838
+ |----------|-------------|-------------------------------------------------------|---------------------------------------------------------------|
1839
+ | `method` | QueryMethod | `RESOURCE_QUERY_METHOD` / `RESOURCE_AGGREGATE_METHOD` | `'post'` (config default), `'get'`, or `'get-post'` for both. |
1840
+
1841
+ The GET route takes the request body properties as query parameters: `filter` and `select` JSON-encoded, `sort` as a
1842
+ field list or JSON object, the rest as plain values. It shares the settings and validation of the POST route.
1843
+
1844
+ ```
1845
+ GET /api/posts/query?filter={"viewCount":{"_gte":5}}&sort=-createdAt&size=20
1846
+ ```
1847
+
1848
+ Keep POST for large filters, since Node.js limits the request headers to 16 KB. With a string primary key, the id
1849
+ `query` or `aggregate` can no longer be read through `GET /:id`.
1850
+
1851
+ ### Update routes (update, replace)
1852
+
1853
+ Both routes share the input fields (the `update` operation config of the model), the policies, the `beforeUpdate`
1854
+ and `afterUpdate` hooks, the cache invalidation, and the `update` event:
1855
+
1856
+ - `PATCH /:id` (`service.update`) updates the given fields (`<Model>Update`, all optional).
1857
+ - `PUT /:id` (`service.replace`) replaces the resource (`<Model>Replace`, required fields as on create). Omitted fields
1858
+ are reset to their `default`, or `null` when optional. Hidden fields, files, and omitted optional relations stay
1859
+ untouched. The hooks receive the completed data, the reset fields included, so they see a replacement as an update
1860
+ of every field.
1861
+
1862
+ The `update` config applies to both routes, and `replace` overrides it for `PUT /:id` only, merged the same way as the
1863
+ [route defaults](#route-defaults). Setting `replace` alone never affects `PATCH /:id`.
1864
+
1865
+ ```ts
1866
+ createRoutes({
1867
+ modelName: 'Product',
1868
+ update: { roles: ['Admin', 'Editor'], rateLimit: { max: 50 } },
1869
+ replace: { roles: ['Admin'] } // PUT: Admin only, same rate limit
1870
+ });
1871
+
1872
+ createRoutes({ modelName: 'Setting', actions: ['find', 'query', 'create', 'update', 'delete'] }); // PATCH only
1873
+ createRoutes({ modelName: 'Profile', actions: ['find', 'query', 'create', 'replace', 'delete'] }); // PUT only
1874
+ ```
1875
+
1876
+ ### Optimistic concurrency (If-Match)
1877
+
1878
+ Without a precondition, the last of two concurrent updates of a field wins. A model with `updatedAt` (the default
1879
+ audit fields) answers `find`, `create`, `update` and `replace` with an `ETag`, its `updatedAt` quoted
1880
+ (`"2026-11-01T12:00:00.000Z"`). A client sending it back as `If-Match` on `PATCH`, `PUT` or `DELETE /:id` writes only
1881
+ the version it read: a record changed since answers `412 RESOURCE_PRECONDITION_FAILED`, with the `updatedAt` it has
1882
+ now in its details. `If-Match` also takes the `updatedAt` of the record as the client read it (with or without quotes),
1883
+ a list of them, or `*` for any version. A weak tag (`W/"..."`) never matches, `If-Match` comparing the tags strongly
1884
+ (RFC 9110). The write is made with the read `updatedAt` in its condition, so a concurrent write in between fails it
1885
+ too. The header is optional: a request without it writes as before. The bulk routes ignore `If-Match`: a bulk write
1886
+ has no precondition, so a client needing one writes the records one at a time.
1887
+
1888
+ ```ts
1889
+ const post = await client.post.find(1);
1890
+ await client.post.update(
1891
+ { id: 1, title: 'Renamed' },
1892
+ { headers: { 'If-Match': post.updatedAt } } // 412 if someone changed the post since
1893
+ );
1894
+ ```
1895
+
1896
+ In code, `update(id, data, { ifMatch })`, `replace` and `delete` take the same version (a `Date`, an ISO string or an
1897
+ `ETag`). A model without `updatedAt` matches only `*`.
1898
+
1899
+ ### Bulk routes (bulkCreate, bulkUpdate, bulkReplace, bulkDelete)
1900
+
1901
+ Registered when `actions` lists them (`bulkCreate`, `bulkUpdate`, `bulkReplace`, `bulkDelete`). Each bulk route
1902
+ inherits the config of its single route (`create`, `update`, `replace`, `delete`) and takes `maxItems` (default `RESOURCE_BULK_MAX_ITEMS`, `2000`) and `returnRecords`
1903
+ (default `RESOURCE_BULK_RETURN_RECORDS`, `true`).
1904
+
1905
+ `bulkReplace` inherits `update`, `replace`, then `bulkUpdate`, each overriding the previous one, and configures
1906
+ `PUT /bulk` alone.
1907
+ When `replace` and `bulkUpdate` set the same option group (i.e. `roles`), `bulkUpdate` wins for `PUT /bulk`, so set it
1908
+ on `bulkReplace` to keep the replace one.
1909
+
1910
+ | Route | Body | Service method |
1911
+ |----------------|----------------------------------|----------------------|
1912
+ | `POST /bulk` | `[<Model>Create]` | `bulkCreate(items)` |
1913
+ | `PATCH /bulk` | `[{ id, data: <Model>Update }]` | `bulkUpdate(items)` |
1914
+ | `PUT /bulk` | `[{ id, data: <Model>Replace }]` | `bulkReplace(items)` |
1915
+ | `DELETE /bulk` | `[id]` | `bulkDelete(ids)` |
1916
+
1917
+ All items run in one transaction (`RESOURCE_BULK_TRANSACTION_TIMEOUT`, `5000` ms) through the single-item service method
1918
+ (same policies, hooks, events, and cache invalidation). Any failure rolls back everything and returns that item's error;
1919
+ success returns the array of records, each the same as its single route responds with (generated ids, defaults, virtual
1920
+ fields), in the order of the items. With `returnRecords: false` it returns only `{ "success": true, "count": n }`
1921
+ instead, for callers that ignore the records or refetch them anyway. The `after*` hooks run before the commit, so keep
1922
+ side effects in resource events ([events.md](./events.md)). A bulk delete checks every id exists first, and skips ids
1923
+ removed by an earlier cascade, leaving them out of the records (its `count` still includes them). A request counts once
1924
+ for rate limiting.
1925
+
1926
+ ```ts
1927
+ createRoutes({
1928
+ modelName: 'Tag',
1929
+ actions: ['crud', 'bulkCreate', 'bulkDelete'],
1930
+ delete: { roles: ['Admin'] },
1931
+ bulkCreate: { roles: ['Admin'] },
1932
+ bulkDelete: { maxItems: 500, returnRecords: false } // inherits roles: ['Admin']
1933
+ });
1934
+ ```
1935
+
1936
+ ### Rate limit config
1937
+
1938
+ ```ts
1939
+ const config = {
1940
+ rateLimit: {
1941
+ max: 100,
1942
+ timeWindow: 60000,
1943
+ allowList: ['127.0.0.1'],
1944
+ keyGenerator: (req) => req.ip,
1945
+ secure: true
1946
+ }
1947
+ };
1948
+ ```
1949
+
1950
+ | Property | Type | Description |
1951
+ |----------------|------------------------------|-------------------------------------------------------------------------------------|
1952
+ | `max` | number \| function | Maximum requests per time window. Function: `(req, key) => number`. |
1953
+ | `timeWindow` | number \| string \| function | Window duration in ms. Function: `(req, key) => number`. |
1954
+ | `allowList` | string[] \| function | IPs exempt from limiting. Function: `(req, key) => boolean`. |
1955
+ | `keyGenerator` | function | Custom key generator. Signature: `(req) => string \| number`. |
1956
+ | `secure` | boolean | Respond `503 MEMORY_UNAVAILABLE` while Redis is down (login, OTP, expensive calls). |
1957
+ | `skipOnError` | boolean | Skip the limit while Redis is down, overriding the config and `secure`. |
1958
+
1959
+ ---
1960
+
1961
+ ## createPolicy
1962
+
1963
+ Creates row-level security policies for a resource. The service layer evaluates the policy on every CRUD operation to
1964
+ enforce fine-grained authorization beyond static role/permission checks (see
1965
+ [security.md](./security.md#authorization-check-order) for where it runs among them).
1966
+
1967
+ ```ts
1968
+ import { createPolicy } from '@appweaver/data';
1969
+
1970
+ export default createPolicy({
1971
+ modelName: 'Product',
1972
+ checkAccess: (user, resource, action) => resource.status === 'Draft',
1973
+ readRestrictions: (user, resource, action) => ({
1974
+ enabled: true
1975
+ }),
1976
+ files: {
1977
+ photo: { accessType: 'public' }
1978
+ }
1979
+ });
1980
+ ```
1981
+
1982
+ ### Configuration
1983
+
1984
+ ```ts
1985
+ function createPolicy(
1986
+ config: ResourcePolicyConfig,
1987
+ override?: boolean // replace the one defined for the model (default: false)
1988
+ ) {}
1989
+ ```
1990
+
1991
+ | Property | Type | Description |
1992
+ |---------------------|---------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
1993
+ | `modelName` | string | Model name to bind this policy to (required). |
1994
+ | `checkAccess` | `(user, resource, action) => boolean` | Dynamic access check against a resource instance. Return `true` to allow, `false` to deny. |
1995
+ | `readRestrictions` | `(user, resource, action) => filter` | Returns a Prisma filter object applied to all read queries (find, query, aggregate). Restricts which records are visible. |
1996
+ | `writeRestrictions` | `(user, resource, action) => data` | Returns data to merge or validate on create/update operations. |
1997
+ | `files` | Record\<string, FilePolicy> | Per-file field access policy. |
1998
+ | `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)). |
1999
+
2000
+ **Action types**: `'find'`, `'query'`, `'aggregate'`, `'create'`, `'update'`, `'delete'`
2001
+
2002
+ Every policy callback may be `async` (return a promise), e.g. to look up a team membership in the database. The
2003
+ `user` is `null` for an unauthenticated request.
2004
+
2005
+ The `readRestrictions` of a model also apply where another model includes its records (`output.type: 'always'` or
2006
+ `'single'`), called with the `query` action: a list relation and its count read only the records they let the user
2007
+ read, and a single relation they hide is `null` (matched in memory, or with one query per related model for a
2008
+ relation filter). Its `checkAccess` is not called for the included records. A filter through a relation matches the
2009
+ records they let the user read only, at every level: `author.posts._some.status` quantifies over the posts the user
2010
+ reads, so it cannot tell the hidden ones apart, and `_every` holds for those. A relation reading its records through a
2011
+ view (`output.view`) applies the `readRestrictions` of the policy of that view too
2012
+ (`createPolicy({ modelName: 'User', view: 'public' })`), in its list, count, single record, filter and resource events.
2013
+
2014
+ ### File policy
2015
+
2016
+ | Property | Type | Default | Description |
2017
+ |--------------|--------------------------------------------|---------------|--------------------------------------------------------------------------------------------------|
2018
+ | `accessType` | `'public'` \| `'protected'` \| `'private'` | `'protected'` | File access level. `public` = anyone, `protected` = authenticated users, `private` = owner only. |
2019
+ | `canAccess` | `(user, resource, file) => boolean` | - | Custom access check for reading files. |
2020
+ | `canCreate` | `(user, resource, file) => boolean` | - | Custom access check for uploading files. |
2021
+ | `canDelete` | `(user, resource, file) => boolean` | - | Custom access check for deleting files. |
2022
+
2023
+ The file checks may be `async` too, and run with a `null` user when the upload or delete route is public, so a policy
2024
+ can allow unauthenticated uploads. They are separate from the resource policy: changing a file does not run the
2025
+ `checkAccess` of the resource for the `update` action.
2026
+
2027
+ ### Skipping the policies
2028
+
2029
+ The policies apply to the calls of a request (HTTP, realtime, MCP) and to the calls run with `runAs(user, fn)`. The
2030
+ application's own calls, outside of a request and of `runAs` (a queue worker, a scheduled job, a seeder, a task, a
2031
+ test calling a service), run as the system: the access checks, the read and write restrictions and the file checks are
2032
+ skipped (`isSystemCall()` of `@appweaver/core`), so a policy receives a `null` user only for an anonymous request, or
2033
+ for `runAs(null, fn)`. To apply the policies of a user in a job, run it with `runAs(user, fn)`, which applies them
2034
+ even inside `withoutPolicies`, and `runAsSystem(fn)` of `@appweaver/core` runs a function as the application again,
2035
+ outside of the auth context of the call.
2036
+
2037
+ Inside a request, code acting on behalf of the system rather than the requesting user, such as a custom flow, runs
2038
+ resource and file service calls with `withoutPolicies`. The service hooks, validation, events, and cache invalidation
2039
+ still run. The framework's own authentication flows (login, sign-up, logout, password change, 2FA, email verification,
2040
+ and OAuth2 account linking) use it, so a policy on the auth model never blocks them.
2041
+
2042
+ ```ts
2043
+ import { injectService } from '@appweaver/core';
2044
+ import { withoutPolicies } from '@appweaver/data';
2045
+
2046
+ const pending = await withoutPolicies(() =>
2047
+ injectService('Order').query({ filter: { status: 'Pending' } })
2048
+ );
2049
+ ```
2050
+
2051
+ The internal access covers every call made while the function runs, including the calls made by the service hooks,
2052
+ until a `runAs(user, fn)` inside it. `arePoliciesSkipped()` tells whether the current call runs with it, or as the
2053
+ system. Both are exported by `@appweaver/core` too.
2054
+
2055
+ A test calling a service directly is the application's own call, so it skips the policies too. A test file of the
2056
+ policies calls `runTestsAsAnonymous()` of `@appweaver/testing` once at its top level: every `test` and `it` (with
2057
+ `.only`, `.skip` and `.each`) then runs as an anonymous request (`runAs(null, ...)`), a test sets its user with
2058
+ `runAs(user, fn)`, and one of the application's own calls runs it in `runAsSystem(fn)`.
2059
+
2060
+ ```ts
2061
+ import { injectService, runAs } from '@appweaver/core';
2062
+ import { runTestsAsAnonymous } from '@appweaver/testing';
2063
+
2064
+ runTestsAsAnonymous();
2065
+
2066
+ const admin = { id: 1, email: 'admin@example.com', roles: [adminRole] };
2067
+
2068
+ test('hides the drafts from an anonymous user', async () => {
2069
+ await expect(injectService('Post').query({})).resolves.toMatchObject({ total: 1 });
2070
+ await expect(runAs(admin, () => injectService('Post').query({}))).resolves.toMatchObject({ total: 2 });
2071
+ });
2072
+ ```
2073
+
2074
+ ---
2075
+
2076
+ ## Extending a model defined elsewhere
2077
+
2078
+ A model, service, policy or routes is defined once per model name: a second `createModel`, `createService`,
2079
+ `createPolicy` or `createRoutes` under a taken name fails at startup with `CONTEXT_DEFINITION_DUPLICATE`, naming the
2080
+ files of both (`override: true`, the last argument, replaces the first one entirely). A model of the framework or of a
2081
+ module (`ApiKey`, `File`, `Role`, `AuditLog`, ...) is extended instead, from a file the loaders find like any resource
2082
+ (`src/resources/api-key/model.ts`, `service.ts`, `policy.ts`, `routes.ts`):
2083
+
2084
+ ```ts
2085
+ import { extendModel, extendPolicy, extendService } from '@appweaver/data';
2086
+ import { extendRoutes } from '@appweaver/web';
2087
+
2088
+ // model.ts: new fields must be optional or have a default, since the framework creates these records
2089
+ export default extendModel('ApiKey', {
2090
+ scalars: { label: { type: 'string', required: false } },
2091
+ index: ['label'],
2092
+ read: { omit: ['createdById'] }
2093
+ });
2094
+
2095
+ // service.ts: the hooks run after the ones of the framework
2096
+ export default extendService('ApiKey', {
2097
+ afterCreate: async (key) => notifyOwner(key)
2098
+ });
2099
+
2100
+ // policy.ts: both policies must allow, so an extension never loosens the framework's
2101
+ export default extendPolicy('ApiKey', {
2102
+ checkAccess: (user) => !!user && hasRole(user, 'Integrator')
2103
+ });
2104
+
2105
+ // routes.ts: merged option by option over the framework's routes
2106
+ export default extendRoutes('ApiKey', {
2107
+ defaults: { roles: ['Admin', 'Integrator'] }
2108
+ });
2109
+ ```
2110
+
2111
+ | Function | Merges |
2112
+ |-----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
2113
+ | `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. |
2114
+ | `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. |
2115
+ | `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. |
2116
+ | `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. |
2117
+
2118
+ The extensions apply once every resource is loaded, in the order they were declared, so the files of the application
2119
+ extend the models of the modules loaded after them. An extension of a model the application does not have (i.e. of
2120
+ `ApiKey` with `security.apiKey.enabled` off) is skipped with a warning. The auth model keeps `createAuthModel`.
2121
+
2122
+ ---
2123
+
2124
+ ## registerRoute
2125
+
2126
+ Registers a custom Fastify route handler outside the resource system. Use this for endpoints that don't map to a
2127
+ standard CRUD resource. Its `body`, `querystring` and `params` schemas reject undeclared properties, unless an object
2128
+ sets `additionalProperties` explicitly (see the custom route section of SKILL.md).
2129
+
2130
+ ```ts
2131
+ import { registerRoute, Router } from '@appweaver/web';
2132
+ import { Type } from 'typebox';
2133
+
2134
+ registerRoute(
2135
+ async function (router: Router) {
2136
+ router.get('/search-result', {
2137
+ schema: {
2138
+ summary: 'Sample search result response route',
2139
+ response: { 200: Type.Ref('SearchResult') }
2140
+ },
2141
+ handler: async () => {
2142
+ return { message: 'Hello, world!' };
2143
+ }
2144
+ });
2145
+ },
2146
+ { public: true, cache: { ttl: 15000 } }
2147
+ );
2148
+ ```
2149
+
2150
+ ### Config options
2151
+
2152
+ | Property | Type | Description |
2153
+ |-------------------|--------------------------|--------------------------------------------------------------------------------------------------------|
2154
+ | `exclude` | boolean | Skip the registration of a file or series route, though `actions` lists it. |
2155
+ | `public` | boolean | No authentication required. |
2156
+ | `roles` | string[] | Required roles. |
2157
+ | `permissions` | string[] | Required permissions. |
2158
+ | `auth` | AuthType[] | Allowed authentication types. |
2159
+ | `rateLimit` | RateLimitConfig \| false | Rate limiting configuration. |
2160
+ | `compress` | boolean \| object | Response compression: `false`, or `{ threshold, encodings, levels }` over `server.compression`. |
2161
+ | `timeout` | integer | Milliseconds the route may take, `0` for none, over `server.requestTimeout`. |
2162
+ | `recaptcha` | boolean | Require reCAPTCHA verification. |
2163
+ | `recaptchaAction` | string | Expected reCAPTCHA action. |
2164
+ | `turnstile` | boolean | Require Cloudflare Turnstile verification. |
2165
+ | `turnstileAction` | string | Expected Turnstile action. |
2166
+ | `cache` | boolean \| object | Cache the responses: `true`, or `{ scope, ttl, key, skipInvalidation, modelName, relations }`. |
2167
+ | `apiPrefix` | boolean | Register under `server.apiPrefix` (`true`), or at the root (`false`, like the auth and health routes). |
2168
+
2169
+ The error codes a custom route responds with are listed in its `errorResponses`, see
2170
+ [errors.md](./errors.md#documenting-the-errors-of-a-route).
2171
+
2172
+ ---
2173
+
2174
+ ## registerModel
2175
+
2176
+ Registers a custom TypeBox schema as a named model in the schema registry. Registered models can be referenced using
2177
+ `Type.Ref('ModelName')` in route schemas.
2178
+
2179
+ ```ts
2180
+ import { registerModel } from '@appweaver/web';
2181
+ import { Nullable } from '@appweaver/common';
2182
+ import { Type } from 'typebox';
2183
+
2184
+ registerModel(
2185
+ Type.Object(
2186
+ {
2187
+ id: Type.Integer(),
2188
+ title: Type.String({ example: 'My Title' }),
2189
+ description: Nullable(Type.String({ maxLength: 512 })),
2190
+ score: Type.Number({ minimum: 0, maximum: 1 })
2191
+ },
2192
+ { $id: 'SearchResult' } // The preferred way for naming the model
2193
+ ),
2194
+ 'SearchResult' // Model name can be overridden as a second optional argument
2195
+ );
2196
+ ```
2197
+
2198
+ | Parameter | Type | Description |
2199
+ |-----------|---------|--------------------------------------------------------------|
2200
+ | `schema` | TObject | TypeBox object schema definition. |
2201
+ | `name` | string? | Override schema name identifier for `Type.Ref()` references. |
2202
+
2203
+ ---
2204
+
2205
+ ## registerPlugin
2206
+
2207
+ Registers a custom Fastify plugin. Plugins are wrapped with `fastify-plugin` so their decorators and hooks are scoped to
2208
+ the entire server instance.
2209
+
2210
+ ```ts
2211
+ import { registerPlugin } from '@appweaver/web';
2212
+
2213
+ registerPlugin(
2214
+ 'audit-log',
2215
+ async (server) => {
2216
+ server.addHook('onResponse', async (request, reply) => {
2217
+ logger.info(`${request.method} ${request.url} -> ${reply.statusCode}`);
2218
+ });
2219
+ },
2220
+ ['other-plugin'] // optional dependencies
2221
+ );
2222
+ ```
2223
+
2224
+ | Parameter | Type | Description |
2225
+ |----------------|-------------------------------------|-------------------------------------------------------|
2226
+ | `name` | string | Plugin name (used for dependency resolution). |
2227
+ | `plugin` | `(server) => void \| Promise<void>` | Fastify plugin function. |
2228
+ | `dependencies` | string[] | Optional list of plugin names this plugin depends on. |