@stonecrop/graphql-middleware 0.51.0 → 0.53.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 +5 -3
- package/dist/graphql-middleware.d.ts +60 -134
- package/dist/index.js +71 -44
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -153,17 +153,19 @@ Actions are declared per doctype in `workflow.actions`. Each action names the st
|
|
|
153
153
|
}
|
|
154
154
|
```
|
|
155
155
|
|
|
156
|
-
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`. A self-transition (`selfTransition: true`) keeps the state and writes the record's data instead: the Postgres adapter sets each declared field that has a column, except `status` and any column the database fills itself (a generated column, or an identity generated always), and lists each key it left out in `droppedFields`.
|
|
156
|
+
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`. A self-transition (`selfTransition: true`) keeps the state and writes the record's data instead: the Postgres adapter sets each declared field that has a column, except `status` and any column the database fills itself (a generated column, or an identity generated always), and lists each key it left out in `droppedFields`. When a server-side handler is registered for the self-transition (`actionHandlers`), the handler does that write instead, creating the record too, and must return the record it saved.
|
|
157
157
|
|
|
158
158
|
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.
|
|
159
159
|
|
|
160
160
|
### Creating a record
|
|
161
161
|
|
|
162
|
-
There is no create mutation, no create action, and no separate create write. **Saving a record
|
|
162
|
+
There is no create mutation, no create action, and no separate create write. **Saving a record not created yet 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, unless server code is registered for the Save (`runEffect`), which then does both; the Postgres adapter and the two nuxt hosts implement it.
|
|
163
|
+
|
|
164
|
+
A Save sent with an id that matches no record is not a create: the record was deleted since the client read it, and creating it would report a lost update as a success. For a self-transition, `readState` throws in that case instead of returning `null`, so nothing is created.
|
|
163
165
|
|
|
164
166
|
`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.
|
|
165
167
|
|
|
166
|
-
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.
|
|
168
|
+
Identity belongs to `writeData`, or to a Save's handler when one is registered, 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.
|
|
167
169
|
|
|
168
170
|
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.
|
|
169
171
|
|
|
@@ -7,15 +7,11 @@ import type { PgClient } from '@dataplan/pg';
|
|
|
7
7
|
import { ValidationError } from '@stonecrop/schema';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* A server-side
|
|
10
|
+
* A server-side handler for one doctype action, registered in `actionHandlers`.
|
|
11
11
|
*
|
|
12
|
-
* Throwing
|
|
13
|
-
*
|
|
14
|
-
* doctype's
|
|
15
|
-
*
|
|
16
|
-
* The return value is passed through verbatim as `StonecropActionResult.data`, so it must be
|
|
17
|
-
* API-layer data — camelCase fieldname keys, not raw snake_case columns. See `pgClient` above and
|
|
18
|
-
* ADR 0007.
|
|
12
|
+
* Throwing fails the action and rolls back what it wrote. The return becomes the result's `data`,
|
|
13
|
+
* so use camelCase field names (ADR 0007). The client stores the record read back afterwards, by
|
|
14
|
+
* the doctype's key in this return or else by the request's id.
|
|
19
15
|
* @public
|
|
20
16
|
*/
|
|
21
17
|
export declare type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>;
|
|
@@ -29,23 +25,13 @@ export declare type ActionHandler = (context: ActionHandlerContext) => Promise<u
|
|
|
29
25
|
*/
|
|
30
26
|
export declare interface ActionHandlerContext {
|
|
31
27
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* The guard read, this handler, and the state write all run on this client inside one
|
|
35
|
-
* transaction, so the action is atomic: throw, and everything this handler wrote is rolled
|
|
36
|
-
* back along with the state change. Returning normally commits the lot.
|
|
37
|
-
*
|
|
38
|
-
* Do **not** open your own `BEGIN`/`COMMIT` around these statements. A `COMMIT` here would
|
|
39
|
-
* close the action's transaction early, committing work the guard may still reject. If you
|
|
40
|
-
* need to undo part of your own work without failing the action, use a `SAVEPOINT`.
|
|
41
|
-
*
|
|
42
|
-
* Work sent to a *different* connection is outside all of this and will not be rolled back —
|
|
43
|
-
* so use this client rather than opening one of your own.
|
|
28
|
+
* The database client for this action, inside the action's transaction: throwing rolls back
|
|
29
|
+
* everything the handler wrote, and returning commits it.
|
|
44
30
|
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
31
|
+
* Never run `BEGIN` or `COMMIT` on it, which would commit work the action may still reject (a
|
|
32
|
+
* `SAVEPOINT` undoes part of your work), and never open another connection, whose work would
|
|
33
|
+
* not roll back. Its rows carry snake_case column names: return camelCase field names, by
|
|
34
|
+
* aliasing in SQL or with `snakeToCamel` from `@stonecrop/schema` (ADR 0004).
|
|
49
35
|
*/
|
|
50
36
|
pgClient: PgClient;
|
|
51
37
|
/** The doctype the action was dispatched against, as the client sent it. */
|
|
@@ -54,7 +40,7 @@ export declare interface ActionHandlerContext {
|
|
|
54
40
|
action: string;
|
|
55
41
|
/** The resolved doctype metadata, for field names, the primary key, and the workflow. */
|
|
56
42
|
meta: DoctypeMeta;
|
|
57
|
-
/** The
|
|
43
|
+
/** The record's key from the request. Absent for a record not created yet, and for a command on no record. */
|
|
58
44
|
recordId?: string | number;
|
|
59
45
|
/**
|
|
60
46
|
* The record field data the client sent (`args[0].data`).
|
|
@@ -66,45 +52,31 @@ export declare interface ActionHandlerContext {
|
|
|
66
52
|
data: Record<string, unknown>;
|
|
67
53
|
/** The full argument envelope, for the actions that need more than the first record. */
|
|
68
54
|
args: unknown[];
|
|
69
|
-
/** The state the guard read, or `undefined` when nothing
|
|
55
|
+
/** The state the guard read (`''` for a record with no state), or `undefined` when nothing required reading it or the record does not exist yet. */
|
|
70
56
|
currentState?: string;
|
|
71
57
|
}
|
|
72
58
|
|
|
73
59
|
/**
|
|
74
|
-
*
|
|
60
|
+
* Run a workflow action on the server: check `allowedStates`, then apply the action through `io`.
|
|
75
61
|
*
|
|
76
|
-
*
|
|
77
|
-
* rejects the action when `isActionAllowedInState` denies it, then applies the outcome.
|
|
78
|
-
* Storage access is injected via `io` so this one guard serves every backend and can never
|
|
79
|
-
* disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.
|
|
62
|
+
* - A **transition** (`nextState`) runs `io.runEffect` if supplied, then writes the new state.
|
|
80
63
|
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
* doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever
|
|
84
|
-
* owns the database. Neither names the other: an action never carries a handler name, and a
|
|
85
|
-
* handler never overrides the guard.
|
|
64
|
+
* - A **self-transition** (`selfTransition`, such as Save) saves the record's data and keeps its
|
|
65
|
+
* state, through `io.runEffect` if supplied and `io.writeData` otherwise.
|
|
86
66
|
*
|
|
87
|
-
*
|
|
67
|
+
* - A **stateless command** (neither) runs `io.runEffect` and leaves the state alone.
|
|
88
68
|
*
|
|
89
|
-
*
|
|
69
|
+
* - Anything else fails without touching the backend.
|
|
90
70
|
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
* mutation, and no second write path for it.
|
|
71
|
+
* On a record that does not exist yet, a self-transition creates it without checking
|
|
72
|
+
* `allowedStates`, a command with no `allowedStates` runs, and anything else fails: the actions
|
|
73
|
+
* `isActionAllowedOnNewRecord` allows. On a saved record the check is the same rule the client's
|
|
74
|
+
* `getAvailableTransitions` uses.
|
|
96
75
|
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
* authoring mistake or a command whose handler was never wired. It fails loudly before touching
|
|
102
|
-
* the backend rather than reporting a false success.
|
|
103
|
-
*
|
|
104
|
-
* @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`
|
|
105
|
-
* @param io - Backend read/write closures, plus the optional adapter-owned effect
|
|
106
|
-
* @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)
|
|
107
|
-
* @returns Action result envelope — the freshest record the backend produced, or the resulting state
|
|
76
|
+
* @param actionDef - The action's `label`, `allowedStates`, and `nextState` or `selfTransition`
|
|
77
|
+
* @param io - The backend's storage calls
|
|
78
|
+
* @param data - The record's field data, for a self-transition
|
|
79
|
+
* @returns Whether the action succeeded, the record or state it produced, and any error
|
|
108
80
|
* @public
|
|
109
81
|
*/
|
|
110
82
|
export declare function applyGuardedTransition(actionDef: {
|
|
@@ -264,65 +236,42 @@ export declare function getFetchHandler(name: string): FetchHandler | undefined;
|
|
|
264
236
|
export declare function getMeta(name: string): DoctypeMeta | undefined;
|
|
265
237
|
|
|
266
238
|
/**
|
|
267
|
-
*
|
|
268
|
-
* The same guard runs whether the record lives in Postgres, a mock executor, or an
|
|
269
|
-
* in-memory Map — only these closures change per backend.
|
|
239
|
+
* The storage calls `applyGuardedTransition` makes. Each backend supplies its own.
|
|
270
240
|
* @public
|
|
271
241
|
*/
|
|
272
242
|
export declare interface GuardedTransitionIO {
|
|
273
243
|
/**
|
|
274
|
-
* Read the record's
|
|
244
|
+
* Read the record's workflow state: its state, `undefined` when it exists with no state, or
|
|
245
|
+
* `null` when there is no such record. Return `null`, not `undefined`, for a missing record, or
|
|
246
|
+
* an action on it can report success while writing nothing.
|
|
275
247
|
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
* means **there is no such record**.
|
|
279
|
-
*
|
|
280
|
-
* Collapsing those two into `undefined` is what let an action against a missing record report
|
|
281
|
-
* success: the state read as `''`, an action declaring no `allowedStates` passed the guard, and
|
|
282
|
-
* the write then found nothing to write. Backends must return `null` when the lookup misses.
|
|
248
|
+
* For a self-transition sent with an id that matches no record, throw instead: the record was
|
|
249
|
+
* deleted since it was read, and creating it would report a lost update as a success.
|
|
283
250
|
*/
|
|
284
251
|
readState: () => Promise<string | null | undefined>;
|
|
285
|
-
/**
|
|
252
|
+
/** Write the record's new workflow state. */
|
|
286
253
|
writeState: (nextState: string) => Promise<void>;
|
|
287
254
|
/**
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
* **This is an upsert, and it is the create path.** Saving a record is one request whether or
|
|
292
|
-
* not the row is there yet, so there is no create action and no create mutation — `exists` says
|
|
293
|
-
* which case you are in, and the second argument exists only because the dispatcher already
|
|
294
|
-
* knows: it read the record's state to run the guard. When `exists` is false, mint or derive the
|
|
295
|
-
* identity here and return the created record; identity is the backend's business, not the
|
|
296
|
-
* dispatcher's. Read the declared `primaryKey` out of `data` for a natural-keyed doctype — that
|
|
297
|
-
* value is a field the user filled in — and mint one only when the doctype is surrogate-keyed.
|
|
255
|
+
* Save a self-transition's field data and return the whole record, including its key. When
|
|
256
|
+
* `exists` is false, create the record: take its key from `patch` for a natural-keyed doctype,
|
|
257
|
+
* or mint one. An empty return for a create fails the action.
|
|
298
258
|
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
*
|
|
302
|
-
* Optional. A backend with no data-write path omits it, which is how it declines both saving
|
|
303
|
-
* and creating; a self-transition is then rejected loudly rather than silently dropped — unless
|
|
304
|
-
* `runEffect` is supplied, in which case the handler is the persistence path.
|
|
259
|
+
* Optional: without it, a self-transition fails unless `runEffect` is supplied. Never called
|
|
260
|
+
* when `runEffect` is supplied.
|
|
305
261
|
*/
|
|
306
262
|
writeData?: (patch: Record<string, unknown>, exists: boolean) => Promise<Record<string, unknown>>;
|
|
307
263
|
/**
|
|
308
|
-
* Run the
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
* It is what makes a stateless Command (no `nextState`, no `selfTransition`) executable at
|
|
313
|
-
* all: without one, such an action has nothing to apply and fails loudly.
|
|
264
|
+
* Run the server-side handler registered for this action, once it passes its `allowedStates`
|
|
265
|
+
* check (a self-transition creating a record skips that check), and before the state is
|
|
266
|
+
* written. A stateless command fails without one.
|
|
314
267
|
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
*
|
|
268
|
+
* Its return becomes the result's `data`. On a self-transition it is the whole save, on a record
|
|
269
|
+
* not created yet too, and must return the record it saved or the action fails. Throwing fails
|
|
270
|
+
* the action; undoing what it wrote is the backend's job (the Postgres adapter runs each action
|
|
271
|
+
* in a transaction).
|
|
319
272
|
*
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
* never this.
|
|
323
|
-
*
|
|
324
|
-
* @param currentState - The state the guard read, or `undefined` when nothing required reading it
|
|
325
|
-
* @returns The updated record, or `undefined` to leave the result payload to the state outcome
|
|
273
|
+
* @param currentState - The state `readState` returned (`''` for a record with no state), or
|
|
274
|
+
* `undefined` when it was not read or the record does not exist yet
|
|
326
275
|
*/
|
|
327
276
|
runEffect?: (currentState: string | undefined) => Promise<unknown>;
|
|
328
277
|
}
|
|
@@ -390,24 +339,14 @@ export declare interface StonecropPluginOptions {
|
|
|
390
339
|
*/
|
|
391
340
|
tables?: Record<string, string>;
|
|
392
341
|
/**
|
|
393
|
-
* Server-side
|
|
394
|
-
*
|
|
395
|
-
*
|
|
396
|
-
*
|
|
397
|
-
* but an action that is neither has nothing to apply and fails loudly. Registering a handler
|
|
398
|
-
* here supplies the missing half.
|
|
342
|
+
* Server-side handlers for workflow actions, keyed by the doctype's `name` (not its slug), then
|
|
343
|
+
* the action's key. A handler runs only once the action passes its `allowedStates` check, which a
|
|
344
|
+
* Save creating a record skips. A stateless command (no `nextState`, no `selfTransition`) fails
|
|
345
|
+
* without one, and a transition's runs before the new state is written.
|
|
399
346
|
*
|
|
400
|
-
*
|
|
401
|
-
*
|
|
402
|
-
*
|
|
403
|
-
* the database. So the doctype keeps `allowedStates` (may this run) and `nextState` (what state
|
|
404
|
-
* results), and this keeps the effect (what actually happens). Routing between them is
|
|
405
|
-
* resolved here, on the server, and is never published to the client.
|
|
406
|
-
*
|
|
407
|
-
* Handlers are looked up by `meta.name` — the doctype's canonical name, not its slug. An
|
|
408
|
-
* unregistered action is not an error in itself: a transition needs no handler. It fails only
|
|
409
|
-
* when the doctype gave the action no outcome either, and the error then names the action and
|
|
410
|
-
* both ways to fix it, so a typo'd key reports as a missing effect rather than a silent no-op.
|
|
347
|
+
* A Save's (`selfTransition`) handler is the whole save: it runs on a record not created yet
|
|
348
|
+
* too, with no `recordId`, and must return the record it saved, with its key, or the save
|
|
349
|
+
* fails. A Save sent with an id that matches no row is refused before the handler runs.
|
|
411
350
|
*
|
|
412
351
|
* @example
|
|
413
352
|
* ```ts
|
|
@@ -428,26 +367,13 @@ export declare interface StonecropPluginOptions {
|
|
|
428
367
|
*/
|
|
429
368
|
actionHandlers?: Record<string, Record<string, ActionHandler>>;
|
|
430
369
|
/**
|
|
431
|
-
* Row cap
|
|
432
|
-
*
|
|
433
|
-
*
|
|
434
|
-
*
|
|
435
|
-
* A row cap is a statement about what this database can afford to serve, so it belongs to
|
|
436
|
-
* whoever owns the database — not to a doctype (which describes the API surface, not the
|
|
437
|
-
* table) and not to a page (which cannot know the size of an arbitrary table). Callers stay
|
|
438
|
-
* free to ask for less; they cannot ask for an unbounded scan by omission.
|
|
439
|
-
*
|
|
440
|
-
* One number covers both reads because a link *is* a list, fetched a different way. It used to
|
|
441
|
-
* be capped at a hard-coded 50 that no option could reach, which is how an operator watching a
|
|
442
|
-
* slow query found there was no knob to turn.
|
|
443
|
-
*
|
|
444
|
-
* Truncation is always reported — `hasMore` for a list, `truncatedLinks` for a record — so a
|
|
445
|
-
* partial answer is distinguishable from a complete one without asking for a count. That
|
|
446
|
-
* matters more for a link than for a list: a link cannot be paged, so a client that writes
|
|
447
|
-
* back a truncated relation deletes the rows it was never sent.
|
|
370
|
+
* Row cap when nothing else names one: for `stonecropRecords` called without a `limit`, and for
|
|
371
|
+
* a many-side link whose declaration has no `fetch.limit`. Defaults to 200; `null` removes it,
|
|
372
|
+
* so an unqualified list returns the whole table and a link the whole relation.
|
|
448
373
|
*
|
|
449
|
-
*
|
|
450
|
-
*
|
|
374
|
+
* A truncated answer is always reported: `hasMore` for a list, `truncatedLinks` for a record.
|
|
375
|
+
* A link cannot be paged, so a client that writes back a truncated link deletes the rows it was
|
|
376
|
+
* never sent.
|
|
451
377
|
*/
|
|
452
378
|
defaultRecordLimit?: number | null;
|
|
453
379
|
}
|
package/dist/index.js
CHANGED
|
@@ -274,46 +274,64 @@ function clearFetchHandlers() {
|
|
|
274
274
|
//#endregion
|
|
275
275
|
//#region src/dispatch/transition.ts
|
|
276
276
|
/**
|
|
277
|
-
*
|
|
277
|
+
* Run a workflow action on the server: check `allowedStates`, then apply the action through `io`.
|
|
278
278
|
*
|
|
279
|
-
*
|
|
280
|
-
* rejects the action when `isActionAllowedInState` denies it, then applies the outcome.
|
|
281
|
-
* Storage access is injected via `io` so this one guard serves every backend and can never
|
|
282
|
-
* disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.
|
|
279
|
+
* - A **transition** (`nextState`) runs `io.runEffect` if supplied, then writes the new state.
|
|
283
280
|
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
* doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever
|
|
287
|
-
* owns the database. Neither names the other: an action never carries a handler name, and a
|
|
288
|
-
* handler never overrides the guard.
|
|
281
|
+
* - A **self-transition** (`selfTransition`, such as Save) saves the record's data and keeps its
|
|
282
|
+
* state, through `io.runEffect` if supplied and `io.writeData` otherwise.
|
|
289
283
|
*
|
|
290
|
-
*
|
|
284
|
+
* - A **stateless command** (neither) runs `io.runEffect` and leaves the state alone.
|
|
291
285
|
*
|
|
292
|
-
*
|
|
286
|
+
* - Anything else fails without touching the backend.
|
|
293
287
|
*
|
|
294
|
-
*
|
|
295
|
-
*
|
|
296
|
-
*
|
|
297
|
-
*
|
|
298
|
-
* mutation, and no second write path for it.
|
|
288
|
+
* On a record that does not exist yet, a self-transition creates it without checking
|
|
289
|
+
* `allowedStates`, a command with no `allowedStates` runs, and anything else fails: the actions
|
|
290
|
+
* `isActionAllowedOnNewRecord` allows. On a saved record the check is the same rule the client's
|
|
291
|
+
* `getAvailableTransitions` uses.
|
|
299
292
|
*
|
|
300
|
-
*
|
|
301
|
-
*
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
* authoring mistake or a command whose handler was never wired. It fails loudly before touching
|
|
305
|
-
* the backend rather than reporting a false success.
|
|
306
|
-
*
|
|
307
|
-
* @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`
|
|
308
|
-
* @param io - Backend read/write closures, plus the optional adapter-owned effect
|
|
309
|
-
* @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)
|
|
310
|
-
* @returns Action result envelope — the freshest record the backend produced, or the resulting state
|
|
293
|
+
* @param actionDef - The action's `label`, `allowedStates`, and `nextState` or `selfTransition`
|
|
294
|
+
* @param io - The backend's storage calls
|
|
295
|
+
* @param data - The record's field data, for a self-transition
|
|
296
|
+
* @returns Whether the action succeeded, the record or state it produced, and any error
|
|
311
297
|
* @public
|
|
312
298
|
*/
|
|
313
299
|
async function applyGuardedTransition(actionDef, io, data) {
|
|
314
300
|
const label = actionDef.label ?? "unknown";
|
|
315
301
|
const isSelfTransition = actionDef.selfTransition === true;
|
|
316
302
|
const hasStateOutcome = isSelfTransition || actionDef.nextState != null;
|
|
303
|
+
const runEffect = async (effect, currentState) => {
|
|
304
|
+
try {
|
|
305
|
+
return {
|
|
306
|
+
ran: true,
|
|
307
|
+
result: await effect(currentState)
|
|
308
|
+
};
|
|
309
|
+
} catch (err) {
|
|
310
|
+
return {
|
|
311
|
+
ran: false,
|
|
312
|
+
failure: {
|
|
313
|
+
success: false,
|
|
314
|
+
data: null,
|
|
315
|
+
error: `Action "${label}" failed: ${err instanceof Error ? err.message : String(err)}`
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
const saveThroughEffect = async (effect, currentState) => {
|
|
321
|
+
const effectOutcome = await runEffect(effect, currentState);
|
|
322
|
+
if (!effectOutcome.ran) return effectOutcome.failure;
|
|
323
|
+
const record = effectOutcome.result;
|
|
324
|
+
if (record === null || typeof record !== "object" || Array.isArray(record) || Object.keys(record).length === 0) return {
|
|
325
|
+
success: false,
|
|
326
|
+
data: null,
|
|
327
|
+
error: `${label} failed: the server did not return the saved record.`
|
|
328
|
+
};
|
|
329
|
+
return {
|
|
330
|
+
success: true,
|
|
331
|
+
data: record,
|
|
332
|
+
error: null
|
|
333
|
+
};
|
|
334
|
+
};
|
|
317
335
|
if (!hasStateOutcome && !io.runEffect) return {
|
|
318
336
|
success: false,
|
|
319
337
|
data: null,
|
|
@@ -329,6 +347,7 @@ async function applyGuardedTransition(actionDef, io, data) {
|
|
|
329
347
|
if (isGuarded || hasStateOutcome) {
|
|
330
348
|
const state = await io.readState();
|
|
331
349
|
if (state === null) {
|
|
350
|
+
if (isSelfTransition && io.runEffect) return saveThroughEffect(io.runEffect, void 0);
|
|
332
351
|
if (isSelfTransition && io.writeData) {
|
|
333
352
|
const created = await io.writeData(data ?? {}, false);
|
|
334
353
|
if (!created || Object.keys(created).length === 0) return {
|
|
@@ -355,21 +374,20 @@ async function applyGuardedTransition(actionDef, io, data) {
|
|
|
355
374
|
data: null,
|
|
356
375
|
error: `Action not allowed from state: ${currentState || "(unknown)"}`
|
|
357
376
|
};
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
effectResult = await io.runEffect(currentState);
|
|
361
|
-
} catch (err) {
|
|
377
|
+
if (isSelfTransition) {
|
|
378
|
+
if (io.runEffect) return saveThroughEffect(io.runEffect, currentState);
|
|
362
379
|
return {
|
|
363
|
-
success:
|
|
364
|
-
data: null,
|
|
365
|
-
error:
|
|
380
|
+
success: true,
|
|
381
|
+
data: await io.writeData?.(data ?? {}, true) ?? null,
|
|
382
|
+
error: null
|
|
366
383
|
};
|
|
367
384
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
385
|
+
let effectResult;
|
|
386
|
+
if (io.runEffect) {
|
|
387
|
+
const effect = await runEffect(io.runEffect, currentState);
|
|
388
|
+
if (!effect.ran) return effect.failure;
|
|
389
|
+
effectResult = effect.result;
|
|
390
|
+
}
|
|
373
391
|
if (actionDef.nextState == null) return {
|
|
374
392
|
success: true,
|
|
375
393
|
data: effectResult ?? null,
|
|
@@ -1113,13 +1131,17 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
1113
1131
|
return await pgClient.withTransaction(async (tx) => {
|
|
1114
1132
|
const outcome = await applyGuardedTransition(actionDef, {
|
|
1115
1133
|
readState: async () => {
|
|
1134
|
+
if (actionDef.selfTransition === true) pkColumn();
|
|
1116
1135
|
if (recordId == null) return null;
|
|
1117
1136
|
const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
|
|
1118
1137
|
const { rows } = await debugSql(tx, {
|
|
1119
1138
|
text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
|
|
1120
1139
|
values: [String(recordId)]
|
|
1121
1140
|
});
|
|
1122
|
-
if (rows.length === 0)
|
|
1141
|
+
if (rows.length === 0) {
|
|
1142
|
+
if (actionDef.selfTransition === true) throw new Error(`${actionDef.label ?? spec.action} failed: record ${String(recordId)} no longer exists.`);
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1123
1145
|
if (!declaresState) return void 0;
|
|
1124
1146
|
return rows[0][STATE_COLUMN] ?? void 0;
|
|
1125
1147
|
},
|
|
@@ -1133,7 +1155,6 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
1133
1155
|
const { cols, values } = partitionPatch(patch);
|
|
1134
1156
|
const returning = columns.select(meta.name, getColumnSelections(meta));
|
|
1135
1157
|
if (!exists) {
|
|
1136
|
-
if (recordId != null) throw new Error(`Action "${actionDef.label ?? spec.action}" targets ${meta.name} "${String(recordId)}", which no longer exists. Nothing was created — a record dispatched with an identity is an update, and creating one is what dispatching no identity means.`);
|
|
1137
1158
|
const text = cols.length ? `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(", ")}) RETURNING ${returning.list}` : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`;
|
|
1138
1159
|
const { rows } = await debugSql(tx, {
|
|
1139
1160
|
text,
|
|
@@ -1170,16 +1191,22 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
1170
1191
|
}) : void 0
|
|
1171
1192
|
}, recordData);
|
|
1172
1193
|
if (!outcome.success) throw new ActionRolledBack(outcome);
|
|
1194
|
+
const pkField = getPkMeta(meta)?.fieldname;
|
|
1195
|
+
const repliedId = pkField !== void 0 && outcome.data !== null && typeof outcome.data === "object" ? Reflect.get(outcome.data, pkField) : void 0;
|
|
1173
1196
|
if (outcome.success && outcome.data !== null && typeof outcome.data === "object") {
|
|
1174
1197
|
const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === "object");
|
|
1175
1198
|
await enrichLinkDisplayFields(tx, meta, written, columns, debugSql);
|
|
1176
1199
|
}
|
|
1177
|
-
const
|
|
1178
|
-
const readId = (pkField !== void 0 && outcome.data !== null && typeof outcome.data === "object" ? Reflect.get(outcome.data, pkField) : void 0) ?? recordId;
|
|
1200
|
+
const readId = repliedId ?? recordId;
|
|
1179
1201
|
const record = readId == null ? null : (await readRecords(tx, [{
|
|
1180
1202
|
doctype: meta.name,
|
|
1181
1203
|
id: readId
|
|
1182
1204
|
}]))[0]?.data ?? null;
|
|
1205
|
+
if (actionDef.selfTransition === true && record === null) throw new ActionRolledBack({
|
|
1206
|
+
success: false,
|
|
1207
|
+
data: null,
|
|
1208
|
+
error: `${actionDef.label ?? spec.action} failed: the server did not say which record it saved.`
|
|
1209
|
+
});
|
|
1183
1210
|
const reply = {
|
|
1184
1211
|
...outcome,
|
|
1185
1212
|
record
|