@stonecrop/graphql-middleware 0.16.6 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -2
- package/dist/graphql-middleware.d.ts +197 -27
- package/dist/index.js +519 -295
- package/dist/index.js.map +1 -1
- package/dist/src/dispatch/transition.d.ts +73 -20
- package/dist/src/dispatch/transition.d.ts.map +1 -1
- package/dist/src/dispatch/transition.js +112 -34
- package/dist/src/fields.d.ts +37 -0
- package/dist/src/fields.d.ts.map +1 -0
- package/dist/src/fields.js +48 -0
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/plugin/postgraphile.d.ts +123 -0
- package/dist/src/plugin/postgraphile.d.ts.map +1 -1
- package/dist/src/plugin/postgraphile.js +479 -81
- package/dist/src/registry/doctypes.d.ts +29 -3
- package/dist/src/registry/doctypes.d.ts.map +1 -1
- package/dist/src/registry/doctypes.js +85 -7
- package/dist/src/typeDefs.d.ts.map +1 -1
- package/dist/src/typeDefs.js +26 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -135,7 +135,7 @@ Fields with `computed: true` have no backing database column and are excluded fr
|
|
|
135
135
|
|
|
136
136
|
## Actions
|
|
137
137
|
|
|
138
|
-
Actions are declared per doctype in `workflow.actions
|
|
138
|
+
Actions are declared per doctype in `workflow.actions`. Each action names the states it may run from (`allowedStates`) and the state the record moves to (`nextState`):
|
|
139
139
|
|
|
140
140
|
```json
|
|
141
141
|
"workflow": {
|
|
@@ -147,7 +147,19 @@ Actions are declared per doctype in `workflow.actions` — there is no separate
|
|
|
147
147
|
}
|
|
148
148
|
```
|
|
149
149
|
|
|
150
|
-
The `stonecropAction(doctype, action, args)` mutation dispatches through `applyGuardedTransition`: it reads the record's `status`, rejects the action if the current state is not in `allowedStates` (`isActionAllowedInState`), then writes `nextState`. The record is identified by `args[0].id`.
|
|
150
|
+
The `stonecropAction(doctype, action, args)` mutation dispatches through `applyGuardedTransition`: it reads the record's `status`, rejects the action if the current state is not in `allowedStates` (`isActionAllowedInState`), then writes `nextState`. The record is identified by `args[0].id`. Self-transitions (`selfTransition: true`) have no state target and no data-write path on this backend, so they are rejected rather than silently succeeding.
|
|
151
|
+
|
|
152
|
+
An action against a record that does not exist is reported as such, before the guard runs. This depends on the backend distinguishing the two things `undefined` used to mean — `GuardedTransitionIO.readState` returns `null` for a lookup that missed, and `undefined` only for a row that exists with no workflow state. A backend that returns `undefined` for both makes a bad id look like a workflow violation, or, when the action declares no `allowedStates`, makes it look like a success.
|
|
153
|
+
|
|
154
|
+
### Creating a record
|
|
155
|
+
|
|
156
|
+
There is no create mutation, no create action, and no separate create write. **Saving a record that does not exist creates it**, because "persist this record's data" is one request whether or not the row is there yet. `GuardedTransitionIO.writeData` is an upsert: it receives an `exists` flag the dispatcher already knows, having read the record's state to run the guard. A backend that omits `writeData` declines both saving and creating, which is the Postgres adapter's position today; the two nuxt hosts implement it.
|
|
157
|
+
|
|
158
|
+
`allowedStates` is deliberately not consulted on creation — it constrains movement between states, and a record being created is not in one. Its initial state is the backend's to set. Only a self-transition creates: a `nextState` transition against a missing record is a bad id, not a request to create one.
|
|
159
|
+
|
|
160
|
+
Identity belongs to `writeData`, not the dispatcher. Read the declared `primaryKey` out of the submitted data for a natural-keyed doctype — that value is a field the user filled in — and mint one only when the doctype is surrogate-keyed. The New Record flow dispatches with **no** `id` in the envelope, because an unsaved record has no identity to send; the created record comes back carrying the one the backend assigned.
|
|
161
|
+
|
|
162
|
+
A `writeData` that only knows how to patch will match no row and return nothing. The dispatcher treats an empty return on the create path as exactly that and fails loudly, rather than letting a save that stored nothing report success.
|
|
151
163
|
|
|
152
164
|
## Custom fetch handlers
|
|
153
165
|
|
|
@@ -7,27 +7,99 @@ import type { PgClient } from '@dataplan/pg';
|
|
|
7
7
|
import { ValidationError } from '@stonecrop/schema';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
10
|
+
* A server-side effect for one doctype action, supplied by whoever owns the database.
|
|
11
|
+
*
|
|
12
|
+
* Throwing rejects the action and no state is written. Returning the updated record makes it the
|
|
13
|
+
* client writeback payload; returning `undefined` leaves the doctype's own outcome to decide.
|
|
14
|
+
*
|
|
15
|
+
* The return value is passed through verbatim as `StonecropActionResult.data`, so it must be
|
|
16
|
+
* API-layer data — camelCase fieldname keys, not raw snake_case columns. See `pgClient` above and
|
|
17
|
+
* ADR 0007.
|
|
18
|
+
* @public
|
|
19
|
+
*/
|
|
20
|
+
export declare type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Everything a server-side action handler is given when `stonecropAction` dispatches to it.
|
|
24
|
+
*
|
|
25
|
+
* A context object rather than positional parameters so the set can grow without breaking
|
|
26
|
+
* registered handlers — the adapters that supply these live in consumer repositories.
|
|
27
|
+
* @public
|
|
28
|
+
*/
|
|
29
|
+
export declare interface ActionHandlerContext {
|
|
30
|
+
/**
|
|
31
|
+
* Active database client for the current request. **It is inside the action's transaction.**
|
|
32
|
+
*
|
|
33
|
+
* The guard read, this handler, and the state write all run on this client inside one
|
|
34
|
+
* transaction, so the action is atomic: throw, and everything this handler wrote is rolled
|
|
35
|
+
* back along with the state change. Returning normally commits the lot.
|
|
36
|
+
*
|
|
37
|
+
* Do **not** open your own `BEGIN`/`COMMIT` around these statements. A `COMMIT` here would
|
|
38
|
+
* close the action's transaction early, committing work the guard may still reject. If you
|
|
39
|
+
* need to undo part of your own work without failing the action, use a `SAVEPOINT`.
|
|
40
|
+
*
|
|
41
|
+
* Work sent to a *different* connection is outside all of this and will not be rolled back —
|
|
42
|
+
* so use this client rather than opening one of your own.
|
|
43
|
+
*
|
|
44
|
+
* Rows from a raw `pgClient.query()` carry snake_case **column** names, while the middleware's
|
|
45
|
+
* own read paths alias them to camelCase fieldnames at the SQL layer (ADR 0004). A handler that
|
|
46
|
+
* returns raw rows therefore leaks snake_case keys to the client. Alias in SQL
|
|
47
|
+
* (`"display_name" AS "displayName"`) or convert with `snakeToCamel` from `@stonecrop/schema`.
|
|
48
|
+
*/
|
|
49
|
+
pgClient: PgClient;
|
|
50
|
+
/** The doctype the action was dispatched against, as the client sent it. */
|
|
51
|
+
doctype: string;
|
|
52
|
+
/** The action's key in `workflow.actions` — the same string the handler was registered under. */
|
|
53
|
+
action: string;
|
|
54
|
+
/** The resolved doctype metadata, for field names, the primary key, and the workflow. */
|
|
55
|
+
meta: DoctypeMeta;
|
|
56
|
+
/** The target record's identity, taken from the first argument envelope. Absent for a record-less command. */
|
|
57
|
+
recordId?: string | number;
|
|
58
|
+
/**
|
|
59
|
+
* The record field data the client sent (`args[0].data`).
|
|
60
|
+
*
|
|
61
|
+
* Unvalidated: `args` is an opaque `JSON` scalar, so this is browser-supplied input that has
|
|
62
|
+
* passed through no schema. Treat it as untrusted — parameterize it into SQL and whitelist
|
|
63
|
+
* the fields the action is allowed to touch.
|
|
64
|
+
*/
|
|
65
|
+
data: Record<string, unknown>;
|
|
66
|
+
/** The full argument envelope, for the actions that need more than the first record. */
|
|
67
|
+
args: unknown[];
|
|
68
|
+
/** The state the guard read, or `undefined` when nothing about the action required reading it. */
|
|
69
|
+
currentState?: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Apply a workflow action on the server, enforcing `allowedStates`.
|
|
11
74
|
*
|
|
12
75
|
* The server owns the transition: it reads the record's authoritative current state,
|
|
13
|
-
* rejects the action when `isActionAllowedInState` denies it, then
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
76
|
+
* rejects the action when `isActionAllowedInState` denies it, then applies the outcome.
|
|
77
|
+
* Storage access is injected via `io` so this one guard serves every backend and can never
|
|
78
|
+
* disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.
|
|
79
|
+
*
|
|
80
|
+
* **The doctype decides whether an action may run and what state results; the adapter decides
|
|
81
|
+
* what actually happens.** `allowedStates`, `nextState` and `selfTransition` are authored in the
|
|
82
|
+
* doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever
|
|
83
|
+
* owns the database. Neither names the other: an action never carries a handler name, and a
|
|
84
|
+
* handler never overrides the guard.
|
|
17
85
|
*
|
|
18
|
-
* There are
|
|
86
|
+
* There are four action shapes this distinguishes:
|
|
19
87
|
* - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.
|
|
20
88
|
* - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current
|
|
21
89
|
* state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
90
|
+
* When the target record does not exist the same write creates it — saving a record is one
|
|
91
|
+
* request whether or not the row is there yet, so there is no separate create action, no create
|
|
92
|
+
* mutation, and no second write path for it.
|
|
93
|
+
* - A **stateless command** (neither of the above) with an `io.runEffect`: the handler is the whole
|
|
94
|
+
* outcome. Still guarded by `allowedStates`, and still forbidden from moving the record.
|
|
95
|
+
* - Anything else — no `nextState`, no `selfTransition`, no registered effect — is either a genuine
|
|
96
|
+
* authoring mistake or a command whose handler was never wired. It fails loudly before touching
|
|
97
|
+
* the backend rather than reporting a false success.
|
|
26
98
|
*
|
|
27
99
|
* @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`
|
|
28
|
-
* @param io - Backend read/write closures
|
|
100
|
+
* @param io - Backend read/write closures, plus the optional adapter-owned effect
|
|
29
101
|
* @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)
|
|
30
|
-
* @returns Action result envelope — the
|
|
102
|
+
* @returns Action result envelope — the freshest record the backend produced, or the resulting state
|
|
31
103
|
* @public
|
|
32
104
|
*/
|
|
33
105
|
export declare function applyGuardedTransition(actionDef: {
|
|
@@ -186,21 +258,65 @@ export declare function getMeta(name: string): DoctypeMeta | undefined;
|
|
|
186
258
|
/**
|
|
187
259
|
* Backend IO the dispatch layer injects so the transition logic stays storage-agnostic.
|
|
188
260
|
* The same guard runs whether the record lives in Postgres, a mock executor, or an
|
|
189
|
-
* in-memory Map — only these
|
|
261
|
+
* in-memory Map — only these closures change per backend.
|
|
190
262
|
* @public
|
|
191
263
|
*/
|
|
192
264
|
export declare interface GuardedTransitionIO {
|
|
193
|
-
/**
|
|
194
|
-
|
|
265
|
+
/**
|
|
266
|
+
* Read the record's current workflow state — the value of its `status` field.
|
|
267
|
+
*
|
|
268
|
+
* Three answers, and the difference between the last two matters:
|
|
269
|
+
* - a string — the record's current state
|
|
270
|
+
* - `undefined` — the record exists but carries no workflow state
|
|
271
|
+
* - `null` — **there is no such record**
|
|
272
|
+
*
|
|
273
|
+
* Collapsing those two into `undefined` is what let an action against a missing record report
|
|
274
|
+
* success: the state read as `''`, an action declaring no `allowedStates` passed the guard, and
|
|
275
|
+
* the write then found nothing to write. Backends must return `null` when the lookup misses.
|
|
276
|
+
*/
|
|
277
|
+
readState: () => Promise<string | null | undefined>;
|
|
195
278
|
/** Persist the record's new workflow state, written verbatim. */
|
|
196
279
|
writeState: (nextState: string) => Promise<void>;
|
|
197
280
|
/**
|
|
198
|
-
* Persist record field data for a
|
|
199
|
-
*
|
|
200
|
-
*
|
|
201
|
-
*
|
|
281
|
+
* Persist a record's field data for a self-transition, returning the full record as it now
|
|
282
|
+
* stands (so the client writeback reflects it).
|
|
283
|
+
*
|
|
284
|
+
* **This is an upsert, and it is the create path.** Saving a record is one request whether or
|
|
285
|
+
* not the row is there yet, so there is no create action and no create mutation — `exists` says
|
|
286
|
+
* which case you are in, and the second argument exists only because the dispatcher already
|
|
287
|
+
* knows: it read the record's state to run the guard. When `exists` is false, mint or derive the
|
|
288
|
+
* identity here and return the created record; identity is the backend's business, not the
|
|
289
|
+
* dispatcher's. Read the declared `primaryKey` out of `data` for a natural-keyed doctype — that
|
|
290
|
+
* value is a field the user filled in — and mint one only when the doctype is surrogate-keyed.
|
|
291
|
+
*
|
|
292
|
+
* Never return an empty object for a creation: the dispatcher treats that as a backend that
|
|
293
|
+
* only knows how to patch, and fails loudly rather than reporting a save that stored nothing.
|
|
294
|
+
*
|
|
295
|
+
* Optional. A backend with no data-write path omits it, which is how it declines both saving
|
|
296
|
+
* and creating; a self-transition is then rejected loudly rather than silently dropped — unless
|
|
297
|
+
* `runEffect` is supplied, in which case the handler is the persistence path.
|
|
202
298
|
*/
|
|
203
|
-
writeData?: (patch: Record<string, unknown
|
|
299
|
+
writeData?: (patch: Record<string, unknown>, exists: boolean) => Promise<Record<string, unknown>>;
|
|
300
|
+
/**
|
|
301
|
+
* Run the adapter's side effect for this action, after the guard has passed and before any
|
|
302
|
+
* state is written. This is the seam a **database author** wires — see
|
|
303
|
+
* `StonecropPluginOptions.actionHandlers` for the Postgres adapter's registration surface.
|
|
304
|
+
*
|
|
305
|
+
* It is what makes a stateless Command (no `nextState`, no `selfTransition`) executable at
|
|
306
|
+
* all: without one, such an action has nothing to apply and fails loudly.
|
|
307
|
+
*
|
|
308
|
+
* Throwing rejects the action, so the dispatcher writes neither data nor state. It does **not**
|
|
309
|
+
* undo writes the handler already made: this guard is storage-agnostic and owns no transaction,
|
|
310
|
+
* and the Postgres adapter in particular dispatches outside one. A handler whose own statements
|
|
311
|
+
* must be all-or-nothing has to wrap them itself.
|
|
312
|
+
*
|
|
313
|
+
* Returning a full record makes it the client writeback payload; returning `undefined` leaves
|
|
314
|
+
* the doctype's own outcome to decide what comes back.
|
|
315
|
+
*
|
|
316
|
+
* @param currentState - The state the guard read, or `undefined` when nothing required reading it
|
|
317
|
+
* @returns The updated record, or `undefined` to leave the result payload to the state outcome
|
|
318
|
+
*/
|
|
319
|
+
runEffect?: (currentState: string | undefined) => Promise<unknown>;
|
|
204
320
|
}
|
|
205
321
|
|
|
206
322
|
/**
|
|
@@ -263,6 +379,67 @@ export declare interface StonecropPluginOptions {
|
|
|
263
379
|
* When absent for a doctype, the table name is derived as `camelToSnake(doctype.name)`.
|
|
264
380
|
*/
|
|
265
381
|
tables?: Record<string, string>;
|
|
382
|
+
/**
|
|
383
|
+
* Server-side effects for workflow actions, keyed `[doctype name][action key]`.
|
|
384
|
+
*
|
|
385
|
+
* This is the seam that makes a stateless Command executable. `applyGuardedTransition` can
|
|
386
|
+
* apply a doctype's own outcome — a `nextState` transition, or a `selfTransition` data write —
|
|
387
|
+
* but an action that is neither has nothing to apply and fails loudly. Registering a handler
|
|
388
|
+
* here supplies the missing half.
|
|
389
|
+
*
|
|
390
|
+
* **The doctype never names a handler, and a handler never overrides the guard.** The two are
|
|
391
|
+
* authored by different people: a doctype is runtime data edited in DocBuilder by whoever
|
|
392
|
+
* models the workflow, while these run behind the GraphQL surface and belong to whoever owns
|
|
393
|
+
* the database. So the doctype keeps `allowedStates` (may this run) and `nextState` (what state
|
|
394
|
+
* results), and this keeps the effect (what actually happens). Routing between them is
|
|
395
|
+
* resolved here, on the server, and is never published to the client.
|
|
396
|
+
*
|
|
397
|
+
* Handlers are looked up by `meta.name` — the doctype's canonical name, not its slug. An
|
|
398
|
+
* unregistered action is not an error in itself: a transition needs no handler. It fails only
|
|
399
|
+
* when the doctype gave the action no outcome either, and the error then names the action and
|
|
400
|
+
* both ways to fix it, so a typo'd key reports as a missing effect rather than a silent no-op.
|
|
401
|
+
*
|
|
402
|
+
* @example
|
|
403
|
+
* ```ts
|
|
404
|
+
* createStonecropPlugin({
|
|
405
|
+
* actionHandlers: {
|
|
406
|
+
* Order: {
|
|
407
|
+
* async recalculateTotal({ pgClient, recordId }) {
|
|
408
|
+
* const { rows } = await pgClient.query({
|
|
409
|
+
* text: 'UPDATE "order" SET total = (SELECT COALESCE(SUM(amount), 0) FROM order_item WHERE order_id = $1) WHERE id = $1 RETURNING *',
|
|
410
|
+
* values: [recordId],
|
|
411
|
+
* })
|
|
412
|
+
* return rows[0]
|
|
413
|
+
* },
|
|
414
|
+
* },
|
|
415
|
+
* },
|
|
416
|
+
* })
|
|
417
|
+
* ```
|
|
418
|
+
*/
|
|
419
|
+
actionHandlers?: Record<string, Record<string, ActionHandler>>;
|
|
420
|
+
/**
|
|
421
|
+
* Row cap applied when nothing else names one: to `stonecropRecords` when the caller requests
|
|
422
|
+
* no `limit`, and to a many-side link when its declaration carries no `fetch.limit`. Defaults
|
|
423
|
+
* to 200.
|
|
424
|
+
*
|
|
425
|
+
* A row cap is a statement about what this database can afford to serve, so it belongs to
|
|
426
|
+
* whoever owns the database — not to a doctype (which describes the API surface, not the
|
|
427
|
+
* table) and not to a page (which cannot know the size of an arbitrary table). Callers stay
|
|
428
|
+
* free to ask for less; they cannot ask for an unbounded scan by omission.
|
|
429
|
+
*
|
|
430
|
+
* One number covers both reads because a link *is* a list, fetched a different way. It used to
|
|
431
|
+
* be capped at a hard-coded 50 that no option could reach, which is how an operator watching a
|
|
432
|
+
* slow query found there was no knob to turn.
|
|
433
|
+
*
|
|
434
|
+
* Truncation is always reported — `hasMore` for a list, `truncatedLinks` for a record — so a
|
|
435
|
+
* partial answer is distinguishable from a complete one without asking for a count. That
|
|
436
|
+
* matters more for a link than for a list: a link cannot be paged, so a client that writes
|
|
437
|
+
* back a truncated relation deletes the rows it was never sent.
|
|
438
|
+
*
|
|
439
|
+
* Set to `null` for no default cap. That is the pre-0.17 behaviour for lists, and it means an
|
|
440
|
+
* unqualified list query returns the whole table and a link returns the whole relation.
|
|
441
|
+
*/
|
|
442
|
+
defaultRecordLimit?: number | null;
|
|
266
443
|
}
|
|
267
444
|
|
|
268
445
|
/**
|
|
@@ -291,13 +468,6 @@ export declare const StonecropPreset: GraphileConfig.Preset;
|
|
|
291
468
|
*/
|
|
292
469
|
export declare const typeDefs: DocumentNode;
|
|
293
470
|
|
|
294
|
-
/**
|
|
295
|
-
* Validate cross-doctype references (Link fields, inherits, etc.)
|
|
296
|
-
* Call after all doctypes are loaded.
|
|
297
|
-
* @public
|
|
298
|
-
*/
|
|
299
|
-
export declare function validateReferences(): ValidationError[];
|
|
300
|
-
|
|
301
471
|
export { ValidationError }
|
|
302
472
|
|
|
303
473
|
export { }
|