@jskit-ai/crud-core 0.2.14 → 0.2.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/locales/en.json +1 -11
- package/package.json +19 -19
- package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
- package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
- package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
- package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
- package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
- package/src/server/createHooksToCollectChildren.js +56 -34
- package/src/server/crudContracts.js +54 -0
- package/src/server/defineCrudFeature.js +538 -0
- package/src/server/jsonApiModule/actions.js +117 -59
- package/src/server/jsonApiModule/routes.js +35 -11
- package/src/server/jsonApiModule/service.js +227 -32
- package/src/server/jsonApiResourceContract.js +41 -1
- package/src/server/listQueryValidators.js +1 -1
- package/src/server/removedApi.js +87 -0
- package/src/server/types.js +26 -50
- package/test/assistantActionConformance.test.js +20 -21
- package/test/assistantPagination.integration.test.js +32 -42
- package/test/createHooksToCollectChildren.test.js +61 -16
- package/test/crudFeaturePackagePattern.test.js +51 -0
- package/test/crudOnHandles.test.js +451 -0
- package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +451 -141
- package/test/errorCodes.test.js +11 -52
- package/test/hiddenFields.test.js +63 -0
- package/test/listQueryValidators.test.js +1 -1
- package/test/routeContracts.test.js +1 -1
- package/test/support/crudJsonApiActionOptions.js +3 -3
- package/test/unservedCrudAutomation.test.js +27 -22
- package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
- package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
- package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
- package/src/server/createCrudServiceFromResource.js +0 -63
- package/src/server/defineCrudJsonApiFeature.js +0 -346
- package/src/server/fieldAccess.js +0 -298
- package/src/server/jsonApiModule/repository.js +0 -355
- package/src/server/lookupPathSupport.js +0 -58
- package/src/server/lookups.js +0 -40
- package/src/server/repositorySupport.js +0 -528
- package/src/server/resourceRuntime/compiledRuntime.js +0 -284
- package/src/server/resourceRuntime/index.js +0 -659
- package/src/server/resourceRuntime/listControls.js +0 -333
- package/src/server/resourceRuntime/lookupHydration.js +0 -626
- package/src/server/resourceRuntime/operationStages.js +0 -140
- package/src/server/resourceRuntime/recordValidation.js +0 -65
- package/src/server/serviceMethods.js +0 -149
- package/test/createCrudServiceFromResource.test.js +0 -323
- package/test/fieldAccess.test.js +0 -86
- package/test/jsonApiRepository.test.js +0 -333
- package/test/jsonApiRepositoryDataCosts.test.js +0 -183
- package/test/jsonApiRepositoryPageLimits.test.js +0 -158
- package/test/jsonApiRepositoryRowLocks.test.js +0 -137
- package/test/jsonApiResourcePackagePattern.test.js +0 -20
- package/test/lookups.test.js +0 -111
- package/test/repositorySupport.test.js +0 -767
- package/test/resourceRuntime.test.js +0 -1014
- package/test/serviceMethods.test.js +0 -139
- /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
- /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Depends on json-rest-api 3.1.0 exactly (from 3.0.1), from the registry with its published integrity: `lockMode: "noKeyUpdate"`, ON CONFLICT on the matching unique index's exact columns, the PostgreSQL merge race on an uncommitted insert, and the `xid8` field type the change horizon reads.
|
|
6
|
+
- `defineCrudFeature` refuses a table resource with ownership `system`, which only a system context reaches: a CRUD surface serves requests, so the owner serves what a request may see through its own methods instead.
|
|
7
|
+
- The package's data tests run on `createPackageTestKnex`, so CI's `DB_CLIENT=pg` run proves the CRUD paths on PostgreSQL too.
|
|
8
|
+
- A CRUD feature builds its routes and its actions' definitions (their input schemas, channels, permissions and assistant extensions) once per `defineCrudFeature` definition, when a composition first needs them, and every later composition and boot reuses them; each CRUD contract's record and include shapes, which its services read, are worked out once per contract. They depend only on the definition and the frozen contract, so what a composition answers is unchanged, and a build that throws keeps nothing, so every composition that reaches it fails as the first did. Rebuilding them took most of each composition's time: an app of 24 CRUD features composed about six times faster after the first composition (around 84 ms each, from around 500 ms, on one host, back to back).
|
|
9
|
+
- **Security.** A CRUD feature's capability repository answers `joinSource({ alias, filters }, options)`, the table as a join source with the columns a read answers and never a hidden one, and, outside a system context, refuses any call whose `fields` names a hidden field, whatever the method, and any method answering another query builder: a join source `decorateRepository` built on `scopedQuery()`, which carried every column, becomes the handle's `joinSource`. A feature whose owned tables hide a field in one and show a field of that name in another fails to start (see `@jskit-ai/resource-runtime`).
|
|
10
|
+
- Depends on json-rest-api 3.0.1 (from 3.0.0), exactly, as `@jskit-ai/resource-runtime` does: see its CHANGELOG for the concurrent-merge fix.
|
|
11
|
+
- **Security.** A CRUD feature's capability repository answers without hidden fields through every method it holds, the ones `decorateRepository` adds included, for every table the feature owns, unless the call runs in a system context: a custom read that forwarded the caller's `fields` handed hidden values to other features.
|
|
12
|
+
- **Security.** A CRUD feature's capability repository (`resourceApi.repository`) on a table with hidden fields refuses another feature's `scopedQuery()` unless it runs in a system context, as it refuses a read naming a hidden field: the builder carries every column. An owner answers its rows to another owner's report through a join source method of its own.
|
|
13
|
+
- A custom action whose name breaks the action-name rule is refused with the rule itself: lower case, starting with a letter, with only letters, digits, `_`, `.` and `-` (`cancel-day`, not `cancelDay`). The error said only that the name was invalid.
|
|
14
|
+
- `@jskit-ai/resource-runtime` is a peer dependency, required and at the same version, where it was a dependency: every CRUD feature owns its table through it, and the app holds one copy of the table runtime that every package shares, as it does the kernel. npm installs a required peer as it installed the dependency, so an app installs the same packages and versions; a release whose versions disagree now fails the install with ERESOLVE instead of nesting a second copy.
|
|
15
|
+
- A CRUD feature's repository (`resourceApi.repository`), which other features and the feature's own actions call, refuses a read whose `fields` names a hidden field of the table unless it runs in a system context (resource-runtime's `withoutHiddenFields`). The handle `decorateRepository` receives answers hidden fields to the owner's own methods, and the CRUD service, the HTTP edge, answers JSON:API documents that never carry one. Before, no handle read answered a hidden field at all.
|
|
16
|
+
- The CRUD service hands its repository, or a `decorateRepository` over it, exactly `{ context, trx, format: "jsonapi" }`: no `missing: "skip"` on view or delete, which a decorator passing its options to another table turned into a null for a missing record. View answers the same 404 for a missing record by catching the not-found error, and delete answers null for one.
|
|
17
|
+
- A record a form saves back through the CRUD service as the service showed it keeps its link to a target the writer cannot see (json-rest-api 3.0.0): the `null` the read showed counts as unchanged.
|
|
18
|
+
- **Breaking (security).** The CRUD service answers records with only the attributes the CRUD contract's output names, on list, view, create and patch, where it answered every column json-rest-api returned whatever the contract said. The actions, routes and a `decorateService` built on the default service answer the same; server code calling the repository still gets whole records. An `include`d record shows only its id, its relation's `labelKey` and what the including contract lists in that field's `output.includeFields`: its fields, and, as `{ relationship: [...] }`, a record it links to with what that shows, at any depth (for example `petId: { output: { required: false, includeFields: ["name", { breed: ["name"] }] } }` for `?include=pet,pet.breed`); another table's contract, which another surface or permission may serve, never shapes it, so an admin contract that shows a person's email never shows it in a member feature's `?include=owner`. A relationship the contract does not name is left out, and an included record only that relationship reaches is not answered. `crud.contracts`, a registry crud-core's new `CrudContractsProvider` provides, holds the served contracts: each CRUD feature registers its contract during setup, the registry is sealed at boot, it refuses two different contracts under one namespace, saying so, and registers a contract served on several surfaces once. The internal `createCrudService` takes `{ repository, crud }` in place of `{ repository, resourceName }`. **Upgrading:** a package with a CRUD feature lists `crud.contracts` in its descriptor's `capabilities.requires`; a test runtime that starts CRUD features adds `CrudContractsProvider` (`@jskit-ai/crud-core/server/crudContracts`).
|
|
19
|
+
- The CRUD service no longer stamps `createdAt` and `updatedAt` itself, and `createCrudService` no longer takes `schema`: the handle stamps them on every write. A request cannot set them: a create body's `createdAt` or a patch body's `updatedAt` gives way to the server's time (the CRUD contract no longer takes them either).
|
|
20
|
+
- **Breaking.** `defineCrudFeature` fails at once on code written for the earlier CRUD API, naming the replacement, instead of ignoring it. It refuses an option it does not take (`ownershipFilter` is now `visibility`; `searchSchema`, `rowPolicy`, `queryFields` and `hooks` go in an `owns` entry; `resource` is now `crud`), a permission for an action the feature does not define (`patch` is the `update` action) or under any but the lower-case name it is read by, a decorated repository or service that still defines a method of the earlier API (such as `queryDocuments()` or `updateRecord()`), and a decorated service without its own method for an enabled operation. Reading `database`, `http`, `jsonRestApi` or `resource` from `decorateRepository`'s dependencies, `resource` from `decorateService`'s or from the feature's capability, or `trx` in a lifecycle hook throws, naming what replaced it (`repository` and `resources`, `crud`, `options`); spreading those objects leaves the names out. The CRUD service's `view()` refuses `forUpdate`, naming `lock()` inside `withTransaction`.
|
|
21
|
+
- `createHooksToCollectChildren` reading through a child repository's `queryAll()` now says which "in" filter the child table must declare for its foreign key when the table refuses the list of owner ids, instead of passing on json-rest-api's validation error.
|
|
22
|
+
- **Breaking.** `@jskit-ai/crud-core/server/fieldAccess` and `@jskit-ai/crud-core/server/lookups`, which nothing called since the CRUD runtime was removed, are gone, with the `crud.fieldAccess.writeDenied` message and the `CrudFieldAccess` and `CrudLookupRepository` types.
|
|
23
|
+
|
|
24
|
+
- **Breaking (data-access redesign).** The JSON:API CRUD runtime is removed, with no alias: `./server/defineCrudJsonApiFeature` (`defineCrudJsonApiFeature`), `./server/resourceRuntime` (`createCrudResourceRuntime`), `./server/jsonApiRepository` (`createCrudJsonApiRepository`), `./server/jsonApiService` (`createCrudJsonApiService`, `repositoryCallOptions`), `./server/createCrudServiceFromResource`, `./server/repositorySupport` and `./server/serviceMethods` (`createCrudServiceRuntime` and the `crudService*Record` helpers). A CRUD feature is `defineCrudFeature({ crud })` on a CRUD contract: its repository is its table's handle, which `decorateRepository` may wrap, and its service the one it builds, which `decorateService` may wrap. The JSON:API repository methods go with it (`queryDocuments`, `queryEveryDocument`, `getDocumentById`, `createDocument`, `createDocuments`, `patchDocumentById`): server code reads and writes through the handle (`query`, `queryAll`, `get`, `create`, `createMany`, `patch`, `lock`). The Before | Now table in the existing-application migration guide maps each one.
|
|
25
|
+
- New `./server/defineCrudFeature` exports `defineCrudFeature({ crud, surface, owns?, ownerRepository?, systemScope?, visibility?, permissions?, decorateRepository?, decorateService?, operationLifecycle?, actions?, ... })`: one feature serving a CRUD contract over HTTP and the action catalogue, owning its table (and those in `owns`) through `runtime.resources`. New `./server/crudContracts` exports `CrudContractsProvider`, which provides `crud.contracts`, the registry of the CRUD contracts an application serves, one per namespace and sealed at boot, and `createCrudContracts`. A package with a CRUD feature lists `crud.contracts` in its descriptor's `capabilities.requires`.
|
|
5
26
|
- Depends on json-rest-api 2.4.0 (from 2.1.0); see `@jskit-ai/json-rest-api-core`'s CHANGELOG for what it changes.
|
|
6
27
|
- A CRUD JSON:API repository's `createDocument` and `patchDocumentById` take `returning: "full"` (the default, unchanged), `"minimal"` (`{ data: { type, id } }`) or `"none"`, so server code that ignores the result skips the read-back: a get through the row policy and lookups, about four queries per written record. `createDocuments(payloads, { trx, context, returning })` creates several records in order in one transaction, all or none, returning `"minimal"` results unless asked for `"full"`.
|
|
7
28
|
- The actions of an `internal: true` or `routes: false` CRUD feature are left off the `automation` channel, so the assistant cannot call them, unless their permission names a permission (`require: "all"` or `"any"`), as workspace-scoped CRUD's defaults do. An additional action's own `channels` still decide for it.
|
package/locales/en.json
CHANGED
|
@@ -1,18 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"jskit": {
|
|
3
|
-
"errors": {
|
|
4
|
-
"INVALID_CURSOR": "Invalid cursor."
|
|
5
|
-
},
|
|
6
3
|
"crud": {
|
|
7
|
-
"record": {
|
|
8
|
-
"notFound": "Record not found."
|
|
9
|
-
},
|
|
10
4
|
"document": {
|
|
11
|
-
"notFound": "Document not found."
|
|
12
|
-
"lockVersionConflict": "This record changed. Reload and try again."
|
|
13
|
-
},
|
|
14
|
-
"fieldAccess": {
|
|
15
|
-
"writeDenied": "Write access denied for fields: {fields}."
|
|
5
|
+
"notFound": "Document not found."
|
|
16
6
|
},
|
|
17
7
|
"query": {
|
|
18
8
|
"includeInvalid": "include expects a comma-separated string such as \"{example}\".",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/crud-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.16",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.0.0"
|
|
@@ -9,17 +9,10 @@
|
|
|
9
9
|
"test": "jskit test"
|
|
10
10
|
},
|
|
11
11
|
"exports": {
|
|
12
|
-
"./server/repositorySupport": "./src/server/repositorySupport.js",
|
|
13
|
-
"./server/resourceRuntime": "./src/server/resourceRuntime/index.js",
|
|
14
12
|
"./server/createHooksToCollectChildren": "./src/server/createHooksToCollectChildren.js",
|
|
15
|
-
"./server/lookups": "./src/server/lookups.js",
|
|
16
13
|
"./server/serviceEvents": "./src/server/serviceEvents.js",
|
|
17
|
-
"./server/
|
|
18
|
-
"./server/
|
|
19
|
-
"./server/createCrudServiceFromResource": "./src/server/createCrudServiceFromResource.js",
|
|
20
|
-
"./server/defineCrudJsonApiFeature": "./src/server/defineCrudJsonApiFeature.js",
|
|
21
|
-
"./server/jsonApiRepository": "./src/server/jsonApiModule/repository.js",
|
|
22
|
-
"./server/jsonApiService": "./src/server/jsonApiModule/service.js",
|
|
14
|
+
"./server/crudContracts": "./src/server/crudContracts.js",
|
|
15
|
+
"./server/defineCrudFeature": "./src/server/defineCrudFeature.js",
|
|
23
16
|
"./server/listQueryValidators": "./src/server/listQueryValidators.js",
|
|
24
17
|
"./server/listFilters": "./src/server/listFilters.js",
|
|
25
18
|
"./server/routeContracts": "./src/server/routeContracts.js",
|
|
@@ -27,22 +20,28 @@
|
|
|
27
20
|
"./locales/en.json": "./locales/en.json"
|
|
28
21
|
},
|
|
29
22
|
"dependencies": {
|
|
30
|
-
"@jskit-ai/
|
|
31
|
-
"@jskit-ai/
|
|
32
|
-
"
|
|
33
|
-
"json-rest-schema": "^1.0.17"
|
|
34
|
-
"json-rest-api": "2.4.0"
|
|
23
|
+
"@jskit-ai/resource-core": "0.1.206",
|
|
24
|
+
"@jskit-ai/resource-crud-core": "0.1.206",
|
|
25
|
+
"json-rest-api": "3.1.0",
|
|
26
|
+
"json-rest-schema": "^1.0.17"
|
|
35
27
|
},
|
|
36
28
|
"description": "Shared server-side CRUD service, repository, route, and query helpers.",
|
|
37
29
|
"jskit": {
|
|
38
30
|
"kind": "runtime",
|
|
39
31
|
"capabilities": {
|
|
40
|
-
"provides": [
|
|
32
|
+
"provides": [
|
|
33
|
+
"crud.contracts"
|
|
34
|
+
],
|
|
41
35
|
"requires": []
|
|
42
36
|
},
|
|
43
37
|
"runtime": {
|
|
44
38
|
"server": {
|
|
45
|
-
"providers": [
|
|
39
|
+
"providers": [
|
|
40
|
+
{
|
|
41
|
+
"entrypoint": "src/server/crudContracts.js",
|
|
42
|
+
"export": "CrudContractsProvider"
|
|
43
|
+
}
|
|
44
|
+
]
|
|
46
45
|
},
|
|
47
46
|
"client": {
|
|
48
47
|
"providers": []
|
|
@@ -50,7 +49,8 @@
|
|
|
50
49
|
}
|
|
51
50
|
},
|
|
52
51
|
"peerDependencies": {
|
|
53
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
54
|
-
"@jskit-ai/kernel": "0.2.
|
|
52
|
+
"@jskit-ai/http-runtime": "0.2.15",
|
|
53
|
+
"@jskit-ai/kernel": "0.2.15",
|
|
54
|
+
"@jskit-ai/resource-runtime": "0.2.13"
|
|
55
55
|
}
|
|
56
56
|
}
|
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
---
|
|
2
|
-
id: crud/
|
|
3
|
-
title:
|
|
4
|
-
summary: Build a complete application-owned CRUD server package from a migration, resource contract, and one framework module declaration.
|
|
5
|
-
keywords: actions, crud, database, json-api, migration,
|
|
6
|
-
requires: @jskit-ai/crud-core, @jskit-ai/resource-crud-core
|
|
2
|
+
id: crud/crud-feature-package
|
|
3
|
+
title: CRUD feature package
|
|
4
|
+
summary: Build a complete application-owned CRUD server package from a migration, a table resource with its CRUD contract, and one framework module declaration.
|
|
5
|
+
keywords: actions, crud, database, defineCrudFeature, json-api, migration, owns, permissions, repository, routes, service, table resource
|
|
6
|
+
requires: @jskit-ai/crud-core, @jskit-ai/resource-core, @jskit-ai/resource-crud-core
|
|
7
7
|
---
|
|
8
8
|
|
|
9
|
-
#
|
|
9
|
+
# CRUD feature package
|
|
10
10
|
|
|
11
11
|
## Use when
|
|
12
12
|
|
|
13
13
|
Use this pattern when a product entity needs conventional JSON API list, view,
|
|
14
14
|
create, patch, and delete behavior. JSKIT owns the repeated repository, service,
|
|
15
15
|
action, route, and provider mechanics. The application owns the migration,
|
|
16
|
-
resource contract, access surface, ownership policy, and package
|
|
16
|
+
table resource, CRUD contract, access surface, ownership policy, and package
|
|
17
|
+
composition.
|
|
17
18
|
|
|
18
19
|
## Do not use when
|
|
19
20
|
|
|
@@ -30,8 +31,10 @@ from a generator questionnaire or treat a live table as the sole contract.
|
|
|
30
31
|
|
|
31
32
|
## Invariants
|
|
32
33
|
|
|
33
|
-
-
|
|
34
|
-
|
|
34
|
+
- The migration and the table resource's storage metadata describe the same
|
|
35
|
+
table, and that table has no other table resource.
|
|
36
|
+
- The CRUD contract's `apiAccess`, surface access, and the table resource's
|
|
37
|
+
`ownership` agree.
|
|
35
38
|
- Public routes use public ownership only.
|
|
36
39
|
- Workspace routes receive explicit scope validators and route-to-action input:
|
|
37
40
|
workspaces-core's `WORKSPACE_CRUD_SCOPE`, never a copied scope literal.
|
|
@@ -55,10 +58,15 @@ from a generator questionnaire or treat a live table as the sole contract.
|
|
|
55
58
|
|
|
56
59
|
## Framework APIs
|
|
57
60
|
|
|
58
|
-
Use `
|
|
59
|
-
`
|
|
60
|
-
|
|
61
|
-
|
|
61
|
+
Use `defineTableResource()` from `@jskit-ai/resource-core`,
|
|
62
|
+
`defineCrudContract()` from `@jskit-ai/resource-crud-core` and
|
|
63
|
+
`defineCrudFeature()` from `@jskit-ai/crud-core`. The feature takes the CRUD
|
|
64
|
+
contract as `crud` and owns its table resource: its repository is the table's
|
|
65
|
+
handle, and it composes the CRUD service, standard CRUD actions with their
|
|
66
|
+
record-changed events, route contracts, access policy, and HTTP routes. The
|
|
67
|
+
routes' visibility and the rows each call reaches follow the table resource's
|
|
68
|
+
`ownership`. More tables the feature owns go in `owns`, and so do the CRUD
|
|
69
|
+
table's server-only extras (`{ resource: bookResource, rowPolicy, hooks }`).
|
|
62
70
|
|
|
63
71
|
## Example files
|
|
64
72
|
|
|
@@ -80,8 +88,8 @@ For a package-owned migration instead, declare its actual directory in
|
|
|
80
88
|
`package.json#jskit.migrations.directories`, as described in the database-layer
|
|
81
89
|
guide.
|
|
82
90
|
|
|
83
|
-
`BooksFeature.js` is deliberately tiny: it binds the
|
|
84
|
-
|
|
91
|
+
`BooksFeature.js` is deliberately tiny: it binds the `bookCrud` contract to the
|
|
92
|
+
framework module and exports the resulting provider.
|
|
85
93
|
`types.js` declares the type of the `app.books` capability, for features that
|
|
86
94
|
require it.
|
|
87
95
|
|
|
@@ -104,18 +112,17 @@ an unfiltered collection can satisfy a matching-row-only assertion.
|
|
|
104
112
|
|
|
105
113
|
## Variation points
|
|
106
114
|
|
|
107
|
-
Change the package name, resource fields, table,
|
|
115
|
+
Change the package name, resource fields, table, ownership, surface,
|
|
108
116
|
relative route, messages, and migration. Supply explicit permissions when the
|
|
109
117
|
surface uses named policy. For workspace ownership, pass `scope:
|
|
110
118
|
WORKSPACE_CRUD_SCOPE` (`@jskit-ai/workspaces-core/server/support/workspaceCrud`):
|
|
111
119
|
the `/w/:workspaceSlug` route base, the workspace route and action validators
|
|
112
|
-
and the slug input. A repository method of such a feature
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
hand-written workspace route's path is
|
|
120
|
+
and the slug input. A repository method of such a feature passes the call's
|
|
121
|
+
`options` on to its handle, which scopes every read and write to the caller's
|
|
122
|
+
workspace, and a hand-written workspace route's path is
|
|
116
123
|
`resolveWorkspaceRoutePath("relative-path")`
|
|
117
124
|
(`@jskit-ai/workspaces-core/server/support/workspaceRoutePaths`). The feature exposes the
|
|
118
|
-
operations declared by the
|
|
125
|
+
operations declared by the CRUD contract. Use `operations` only to narrow that
|
|
119
126
|
surface further; do not register unused mutation actions and routes. Use
|
|
120
127
|
`routes: false` only for an internal
|
|
121
128
|
capability/action surface that deliberately has no HTTP API.
|
|
@@ -140,24 +147,29 @@ function of the action execution.
|
|
|
140
147
|
|
|
141
148
|
When otherwise-standard CRUD earns product behavior, name the exact
|
|
142
149
|
capabilities in `requires` and provide `decorateService({ service, repository,
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
such as `confirmBooking()` or
|
|
146
|
-
|
|
147
|
-
|
|
150
|
+
crud, ...dependencies })`. Retain the standard methods (`list`, `view`,
|
|
151
|
+
`create`, `patch`, `delete`), override only the methods whose CRUD behavior
|
|
152
|
+
changes, and add resource-related domain methods such as `confirmBooking()` or
|
|
153
|
+
`sendReminder()` directly to that service. Those additional methods remain
|
|
154
|
+
available through the resource capability. An overridden `create()` returns
|
|
155
|
+
the created record, with its id, as a
|
|
148
156
|
tagged JSON:API result: a document result (`returnJsonApiDocument`), as the
|
|
149
157
|
standard one does, or a data result (`returnJsonApiData(record)`). The create
|
|
150
158
|
action's created and `record.changed` events read the record's id from it, and
|
|
151
159
|
a create whose service returns an untagged document or record, or a result
|
|
152
160
|
without the record's id, fails in every channel. When the
|
|
153
161
|
product needs only a few additional queries or locking operations, provide
|
|
154
|
-
`decorateRepository({ repository,
|
|
155
|
-
|
|
156
|
-
|
|
162
|
+
`decorateRepository({ repository, resources, crud, ...dependencies })`, where
|
|
163
|
+
`repository` is the CRUD table's handle and `resources` holds the handle of
|
|
164
|
+
every table the feature owns; return the handle's methods plus only those
|
|
165
|
+
unique persistence operations, each taking the call's `options` last and
|
|
166
|
+
passing them on untouched.
|
|
157
167
|
|
|
158
168
|
Use `operationLifecycle` for behavior surrounding a standard operation. Its
|
|
159
169
|
per-operation `before`, `execute`, and `after` phases share one repository
|
|
160
|
-
transaction for create, update, and delete
|
|
170
|
+
transaction for create, update, and delete: each receives `options`, the call
|
|
171
|
+
options carrying the action context and that transaction, to pass on to every
|
|
172
|
+
repository or service call it makes. An `execute` hook receives
|
|
161
173
|
`standard(nextInput)` so it can retain the framework write while adjusting its
|
|
162
174
|
input or coordinating other repository work, and returns what `standard()`
|
|
163
175
|
returns: the operation's tagged JSON:API result (null for delete). A create's
|
|
@@ -173,7 +185,10 @@ service and repository its hooks call. Put durable external delivery behind an
|
|
|
173
185
|
outbox written inside the transaction; do not make an email or webhook the
|
|
174
186
|
arbiter of whether an already-committed request appears successful.
|
|
175
187
|
|
|
176
|
-
Declare resource-related non-CRUD commands in `actions`. Each
|
|
188
|
+
Declare resource-related non-CRUD commands in `actions`. Each key is the
|
|
189
|
+
action's name: lower case, starting with a letter, with only letters, digits,
|
|
190
|
+
`_`, `.` and `-` (`cancel-day`, never `cancelDay`); its id is
|
|
191
|
+
`crud.<namespace>.<name>`. Each named action has
|
|
177
192
|
a normal JSKIT input, permission, audit, events, and `execute({ input, context,
|
|
178
193
|
service, repository, ...dependencies })` contract. Type that argument with
|
|
179
194
|
`CrudCustomActionInvocation` from `@jskit-ai/crud-core/server/types`. Its first
|
|
@@ -183,13 +198,15 @@ by local name; its third is the repository the action calls, when
|
|
|
183
198
|
`decorateRepository` adds the method. Its optional `route`
|
|
184
199
|
declares an HTTP method, path below the resource base, explicit route contract,
|
|
185
200
|
status code, and optional request-to-action input mapper. This is the normal
|
|
186
|
-
home for `confirm`, `publish`, `cancel`, `reorder`, or `
|
|
201
|
+
home for `confirm`, `publish`, `cancel`, `reorder`, or `send-reminder`. Move to a
|
|
187
202
|
separate explicit feature only when the operation belongs to another domain or
|
|
188
203
|
the resource is no longer principally CRUD.
|
|
189
204
|
|
|
190
205
|
If a product-specific list filter needs additional transport validation and
|
|
191
206
|
JSON API search mapping, pass its validator as `listFilterQueryValidator` and
|
|
192
|
-
its storage mapping
|
|
207
|
+
put its storage mapping in the table resource's `searchSchema` (or, when it is
|
|
208
|
+
server-only, in the CRUD table's `owns` entry); keep that contract next to the
|
|
209
|
+
feature.
|
|
193
210
|
Use `operationInputs.create` or `operationInputs.update` when a standard CRUD
|
|
194
211
|
operation intentionally accepts a small virtual product field that is handled
|
|
195
212
|
by the service decorator rather than stored on the resource row.
|
|
@@ -234,15 +251,15 @@ function decorateBookingsService({ service, repository }) {
|
|
|
234
251
|
```
|
|
235
252
|
|
|
236
253
|
```js
|
|
237
|
-
const BookingsFeature =
|
|
238
|
-
|
|
254
|
+
const BookingsFeature = defineCrudFeature({
|
|
255
|
+
crud: bookingCrud,
|
|
239
256
|
surface: "app",
|
|
240
257
|
decorateRepository: decorateBookingsRepository,
|
|
241
258
|
decorateService: decorateBookingsService,
|
|
242
259
|
operationLifecycle: {
|
|
243
260
|
update: {
|
|
244
|
-
async before({ input, service,
|
|
245
|
-
await service.assertUpdateAllowed(input.recordId,
|
|
261
|
+
async before({ input, service, options }) {
|
|
262
|
+
await service.assertUpdateAllowed(input.recordId, options);
|
|
246
263
|
},
|
|
247
264
|
async afterCommit({ result, service, context }) {
|
|
248
265
|
await service.recordUpdateCompleted(result.value.data.id, { context });
|
|
@@ -266,6 +283,21 @@ const BookingsFeature = defineCrudJsonApiFeature({
|
|
|
266
283
|
});
|
|
267
284
|
```
|
|
268
285
|
|
|
286
|
+
An action's `input` is one schema definition, `{ schema, mode }`, for
|
|
287
|
+
everything it validates; its route contract names each part of the request it
|
|
288
|
+
reads, `params`, `query` or `body`, each a schema definition, and the route
|
|
289
|
+
hands the action their fields merged. A workspace scope adds `workspaceSlug` to
|
|
290
|
+
both itself.
|
|
291
|
+
|
|
292
|
+
```js
|
|
293
|
+
import { createSchema } from "json-rest-schema";
|
|
294
|
+
import { composeSchemaDefinitions, recordIdParamsValidator } from "@jskit-ai/kernel/shared/validators";
|
|
295
|
+
|
|
296
|
+
const confirmBookingBody = { schema: createSchema({ note: { type: "string", maxLength: 500 } }), mode: "patch" };
|
|
297
|
+
const confirmBookingInput = composeSchemaDefinitions([recordIdParamsValidator, confirmBookingBody], { mode: "patch" });
|
|
298
|
+
const confirmBookingRouteContract = { params: recordIdParamsValidator, body: confirmBookingBody };
|
|
299
|
+
```
|
|
300
|
+
|
|
269
301
|
## Verification
|
|
270
302
|
|
|
271
303
|
- Rebuild the table from migrations in disposable MySQL and PostgreSQL databases
|
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
"./shared": "./src/shared/index.js"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@jskit-ai/crud-core": "0.2.
|
|
13
|
-
"@jskit-ai/resource-
|
|
12
|
+
"@jskit-ai/crud-core": "0.2.16",
|
|
13
|
+
"@jskit-ai/resource-core": "0.1.206",
|
|
14
|
+
"@jskit-ai/resource-crud-core": "0.1.206"
|
|
14
15
|
},
|
|
15
16
|
"jskit": {
|
|
16
17
|
"kind": "runtime",
|
|
@@ -19,10 +20,10 @@
|
|
|
19
20
|
"app.books"
|
|
20
21
|
],
|
|
21
22
|
"requires": [
|
|
23
|
+
"crud.contracts",
|
|
22
24
|
"runtime.http",
|
|
23
|
-
"runtime.json-rest-api",
|
|
24
25
|
"runtime.actions",
|
|
25
|
-
"runtime.
|
|
26
|
+
"runtime.resources"
|
|
26
27
|
]
|
|
27
28
|
},
|
|
28
29
|
"runtime": {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { defineCrudFeature } from "@jskit-ai/crud-core/server/defineCrudFeature";
|
|
2
|
+
import { bookCrud } from "../shared/bookResource.js";
|
|
3
|
+
|
|
4
|
+
// Owns the books table and serves its CRUD contract.
|
|
5
|
+
const BooksFeature = defineCrudFeature({
|
|
6
|
+
crud: bookCrud,
|
|
7
|
+
id: "app.books",
|
|
8
|
+
capability: "app.books",
|
|
9
|
+
surface: "app",
|
|
10
|
+
relativePath: "/books"
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
export { BooksFeature };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
2
|
+
import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
|
|
3
|
+
|
|
4
|
+
const bookResource = defineTableResource({
|
|
5
|
+
name: "books",
|
|
6
|
+
tableName: "books",
|
|
7
|
+
ownership: "user",
|
|
8
|
+
schema: {
|
|
9
|
+
userId: {
|
|
10
|
+
type: "id",
|
|
11
|
+
required: true,
|
|
12
|
+
hidden: true
|
|
13
|
+
},
|
|
14
|
+
title: {
|
|
15
|
+
type: "string",
|
|
16
|
+
maxLength: 255,
|
|
17
|
+
required: true,
|
|
18
|
+
search: true
|
|
19
|
+
},
|
|
20
|
+
author: {
|
|
21
|
+
type: "string",
|
|
22
|
+
maxLength: 255,
|
|
23
|
+
required: true,
|
|
24
|
+
search: true
|
|
25
|
+
},
|
|
26
|
+
notes: {
|
|
27
|
+
type: "string",
|
|
28
|
+
maxLength: 65535,
|
|
29
|
+
nullable: true,
|
|
30
|
+
search: true
|
|
31
|
+
},
|
|
32
|
+
createdAt: {
|
|
33
|
+
type: "dateTime",
|
|
34
|
+
temporalPrecision: 0,
|
|
35
|
+
storage: { writeSerializer: "datetime-utc" }
|
|
36
|
+
},
|
|
37
|
+
updatedAt: {
|
|
38
|
+
type: "dateTime",
|
|
39
|
+
temporalPrecision: 0,
|
|
40
|
+
storage: { writeSerializer: "datetime-utc" }
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
searchSchema: {
|
|
44
|
+
q: {
|
|
45
|
+
type: "string",
|
|
46
|
+
oneOf: ["title", "author", "notes"],
|
|
47
|
+
filterOperator: "like",
|
|
48
|
+
splitBy: " ",
|
|
49
|
+
matchAll: true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
defaultSort: ["-createdAt"]
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const bookCrud = defineCrudContract(bookResource, {
|
|
56
|
+
namespace: "books",
|
|
57
|
+
apiAccess: "authenticated",
|
|
58
|
+
fields: {
|
|
59
|
+
title: { output: "required", create: "required", patch: "optional" },
|
|
60
|
+
author: { output: "required", create: "required", patch: "optional" },
|
|
61
|
+
notes: { output: "required", create: "optional", patch: "optional" },
|
|
62
|
+
createdAt: { output: "required" },
|
|
63
|
+
updatedAt: { output: "required" }
|
|
64
|
+
},
|
|
65
|
+
messages: {
|
|
66
|
+
validation: "Fix invalid values and try again.",
|
|
67
|
+
saveSuccess: "Book saved.",
|
|
68
|
+
saveError: "Unable to save this book.",
|
|
69
|
+
deleteSuccess: "Book deleted.",
|
|
70
|
+
deleteError: "Unable to delete this book."
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
export { bookCrud, bookResource };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { bookCrud, bookResource } from "./bookResource.js";
|
|
@@ -22,16 +22,31 @@ function readParentId(record) {
|
|
|
22
22
|
return record?.id;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
30
|
-
if (Object.hasOwn(callOptions, "visibilityContext")) {
|
|
31
|
-
nextOptions.visibilityContext = callOptions.visibilityContext;
|
|
32
|
-
}
|
|
25
|
+
// The children are read with the page's own options: its context, which scopes the read, and its transaction.
|
|
26
|
+
function passCallOptions({ callOptions = {} } = {}) {
|
|
27
|
+
return callOptions;
|
|
28
|
+
}
|
|
33
29
|
|
|
34
|
-
|
|
30
|
+
/**
|
|
31
|
+
* The children are read with one filter that lists every owner id, which the child table
|
|
32
|
+
* accepts only when it declares that filter as an "in" search. Without it, json-rest-api
|
|
33
|
+
* answers a validation error on the filter; name the declaration that fixes it.
|
|
34
|
+
* @param {unknown} error
|
|
35
|
+
* @param {string} context
|
|
36
|
+
* @param {string} childForeignKey
|
|
37
|
+
*/
|
|
38
|
+
function explainForeignKeyFilterError(error, context, childForeignKey) {
|
|
39
|
+
const field = `queryParams.filters.${childForeignKey}`;
|
|
40
|
+
if (error?.code !== "REST_API_VALIDATION" || !error.details?.fields?.includes(field)) {
|
|
41
|
+
return error;
|
|
42
|
+
}
|
|
43
|
+
return new TypeError(
|
|
44
|
+
`${context} reads the children of a page with one ${childForeignKey} filter listing every owner id, ` +
|
|
45
|
+
`which the child table refused (${error.message}). Declare the filter in the child table resource's schema, ` +
|
|
46
|
+
`${childForeignKey}: { ..., search: { type: "array", filterOperator: "in" } }, or in its owns entry, ` +
|
|
47
|
+
`searchSchema: { ${childForeignKey}: { type: "array", actualField: "${childForeignKey}", filterOperator: "in" } }.`,
|
|
48
|
+
{ cause: error }
|
|
49
|
+
);
|
|
35
50
|
}
|
|
36
51
|
|
|
37
52
|
function resolveListChildrenHandler(options = {}, { context = "createHooksToCollectChildren" } = {}) {
|
|
@@ -41,7 +56,7 @@ function resolveListChildrenHandler(options = {}, { context = "createHooksToColl
|
|
|
41
56
|
}
|
|
42
57
|
|
|
43
58
|
const childRepository = options.childRepository;
|
|
44
|
-
const childListMethod = normalizeText(options.childListMethod)
|
|
59
|
+
const childListMethod = normalizeText(options.childListMethod);
|
|
45
60
|
const childForeignKey = normalizeText(options.childForeignKey);
|
|
46
61
|
if (!childRepository || typeof childRepository !== "object" || Array.isArray(childRepository)) {
|
|
47
62
|
throw new TypeError(
|
|
@@ -49,30 +64,32 @@ function resolveListChildrenHandler(options = {}, { context = "createHooksToColl
|
|
|
49
64
|
);
|
|
50
65
|
}
|
|
51
66
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
if (childListMethod === "listByIds") {
|
|
67
|
+
if (!childListMethod) {
|
|
68
|
+
// readable-check: allow method-probe - input validation: the child table's repository, a CRUD feature's handle, must read with queryAll()
|
|
69
|
+
if (typeof childRepository.queryAll !== "function") {
|
|
70
|
+
throw new TypeError(`${context} requires childRepository.queryAll to be a function, or a childListMethod.`);
|
|
71
|
+
}
|
|
58
72
|
if (!childForeignKey) {
|
|
59
|
-
throw new TypeError(`${context} requires childForeignKey when
|
|
73
|
+
throw new TypeError(`${context} requires childForeignKey when it reads childRepository.queryAll.`);
|
|
60
74
|
}
|
|
61
|
-
|
|
62
|
-
return (ids = [], childCallOptions = {}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
75
|
+
// Every child of the page's owners in one read through the child table's own repository.
|
|
76
|
+
return async (ids = [], childCallOptions = {}) => {
|
|
77
|
+
try {
|
|
78
|
+
return await childRepository.queryAll({ filters: { [childForeignKey]: ids } }, childCallOptions);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
throw explainForeignKeyFilterError(error, context, childForeignKey);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
67
83
|
}
|
|
68
84
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
}
|
|
85
|
+
const listChildren = childRepository[childListMethod];
|
|
86
|
+
// readable-check: allow method-probe - input validation: the named childListMethod must be a method of childRepository
|
|
87
|
+
if (typeof listChildren !== "function") {
|
|
88
|
+
throw new TypeError(`${context} requires childRepository.${childListMethod} to be a function.`);
|
|
89
|
+
}
|
|
73
90
|
|
|
74
|
-
|
|
75
|
-
|
|
91
|
+
if (childListMethod === "listByForeignIds" && !childForeignKey) {
|
|
92
|
+
throw new TypeError(`${context} requires childForeignKey when using childRepository.listByForeignIds.`);
|
|
76
93
|
}
|
|
77
94
|
|
|
78
95
|
return (ids = [], childCallOptions = {}, hookContext = {}) => {
|
|
@@ -128,9 +145,13 @@ function resolveChildrenContainerKey(hookContext = {}, options = {}) {
|
|
|
128
145
|
* @param {string} options.childKey The key the children are attached under.
|
|
129
146
|
* @param {string} [options.context] The name errors give the hooks.
|
|
130
147
|
* @param {(ids: unknown[], callOptions: object, hookContext: object) => Promise<object[]>} [options.listChildren]
|
|
131
|
-
* Lists the children of the owner ids; otherwise childRepository
|
|
132
|
-
* @param {object} [options.childRepository]
|
|
133
|
-
*
|
|
148
|
+
* Lists the children of the owner ids; otherwise childRepository does.
|
|
149
|
+
* @param {object} [options.childRepository] The child table's repository: without childListMethod, its
|
|
150
|
+
* queryAll() reads the children whose childForeignKey is one of the owner ids, as a CRUD feature's repository does.
|
|
151
|
+
* The child table must declare that filter as an "in" search, e.g. in its schema
|
|
152
|
+
* `ownerId: { type: "integer", search: { type: "array", filterOperator: "in" } }`; the first read says so otherwise.
|
|
153
|
+
* @param {string} [options.childListMethod] A repository method to call instead, with the owner ids, childForeignKey
|
|
154
|
+
* when it is given, the call options and the hook context.
|
|
134
155
|
* @param {string} [options.childForeignKey]
|
|
135
156
|
* @param {(child: object, hookContext: object) => unknown} [options.getChildOwnerId]
|
|
136
157
|
* Reads a child's owner id; otherwise childOwnerIdKey or childForeignKey names it.
|
|
@@ -138,7 +159,8 @@ function resolveChildrenContainerKey(hookContext = {}, options = {}) {
|
|
|
138
159
|
* @param {(record: object, hookContext: object) => unknown} [options.getParentId] Reads a record's id.
|
|
139
160
|
* @param {(value: unknown) => string} [options.normalizeOwnerKey] Turns an owner id into a map key.
|
|
140
161
|
* @param {(input: { callOptions: object, records: object[], ownerIds: unknown[], context: object }) => object} [options.buildChildCallOptions]
|
|
141
|
-
* The options the children are listed with; by default the
|
|
162
|
+
* The options the children are listed with; by default the page's own call options, untouched: its context and
|
|
163
|
+
* transaction.
|
|
142
164
|
* @param {(record: object, children: object[], hookContext: object) => object} [options.attachChildren]
|
|
143
165
|
* Returns the record with its children; by default under childKey in the lookup container, or on
|
|
144
166
|
* the record itself when attachToLookupContainer is false.
|
|
@@ -159,7 +181,7 @@ function createHooksToCollectChildren(options = {}) {
|
|
|
159
181
|
const {
|
|
160
182
|
getParentId = readParentId,
|
|
161
183
|
normalizeOwnerKey: normalizeCollectionOwnerKey = normalizeOwnerKey,
|
|
162
|
-
buildChildCallOptions =
|
|
184
|
+
buildChildCallOptions = passCallOptions,
|
|
163
185
|
attachChildren = attachChildrenToRecord
|
|
164
186
|
} = options;
|
|
165
187
|
const getChildOwnerId = resolveGetChildOwnerId(options, {
|