@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
|
@@ -1,74 +1,152 @@
|
|
|
1
1
|
import { isActionAllowedInState } from '@stonecrop/schema';
|
|
2
2
|
/**
|
|
3
|
-
* Apply a workflow action
|
|
3
|
+
* Apply a workflow action on the server, enforcing `allowedStates`.
|
|
4
4
|
*
|
|
5
5
|
* The server owns the transition: it reads the record's authoritative current state,
|
|
6
|
-
* rejects the action when `isActionAllowedInState` denies it, then
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* same predicate.
|
|
6
|
+
* rejects the action when `isActionAllowedInState` denies it, then applies the outcome.
|
|
7
|
+
* Storage access is injected via `io` so this one guard serves every backend and can never
|
|
8
|
+
* disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.
|
|
10
9
|
*
|
|
11
|
-
*
|
|
10
|
+
* **The doctype decides whether an action may run and what state results; the adapter decides
|
|
11
|
+
* what actually happens.** `allowedStates`, `nextState` and `selfTransition` are authored in the
|
|
12
|
+
* doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever
|
|
13
|
+
* owns the database. Neither names the other: an action never carries a handler name, and a
|
|
14
|
+
* handler never overrides the guard.
|
|
15
|
+
*
|
|
16
|
+
* There are four action shapes this distinguishes:
|
|
12
17
|
* - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.
|
|
13
18
|
* - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current
|
|
14
19
|
* state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
20
|
+
* When the target record does not exist the same write creates it — saving a record is one
|
|
21
|
+
* request whether or not the row is there yet, so there is no separate create action, no create
|
|
22
|
+
* mutation, and no second write path for it.
|
|
23
|
+
* - A **stateless command** (neither of the above) with an `io.runEffect`: the handler is the whole
|
|
24
|
+
* outcome. Still guarded by `allowedStates`, and still forbidden from moving the record.
|
|
25
|
+
* - Anything else — no `nextState`, no `selfTransition`, no registered effect — is either a genuine
|
|
26
|
+
* authoring mistake or a command whose handler was never wired. It fails loudly before touching
|
|
27
|
+
* the backend rather than reporting a false success.
|
|
19
28
|
*
|
|
20
29
|
* @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`
|
|
21
|
-
* @param io - Backend read/write closures
|
|
30
|
+
* @param io - Backend read/write closures, plus the optional adapter-owned effect
|
|
22
31
|
* @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)
|
|
23
|
-
* @returns Action result envelope — the
|
|
32
|
+
* @returns Action result envelope — the freshest record the backend produced, or the resulting state
|
|
24
33
|
* @public
|
|
25
34
|
*/
|
|
26
35
|
export async function applyGuardedTransition(actionDef, io, data) {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
36
|
+
const label = actionDef.label ?? 'unknown';
|
|
37
|
+
const isSelfTransition = actionDef.selfTransition === true;
|
|
38
|
+
const hasStateOutcome = isSelfTransition || actionDef.nextState != null;
|
|
39
|
+
// Nothing to apply and no effect registered — fail loudly WITHOUT touching the backend.
|
|
40
|
+
// This is the honest report for both causes: an action authored with no outcome, and a
|
|
41
|
+
// command whose server handler the adapter never registered.
|
|
42
|
+
if (!hasStateOutcome && !io.runEffect) {
|
|
30
43
|
return {
|
|
31
44
|
success: false,
|
|
32
45
|
data: null,
|
|
33
|
-
error: `Action "${
|
|
46
|
+
error: `Action "${label}" has no workflow transition and no server-side effect is wired — nothing was executed. Give it a nextState or selfTransition in the doctype, or register a server-side handler for it on the adapter.`,
|
|
34
47
|
};
|
|
35
48
|
}
|
|
36
|
-
|
|
37
|
-
|
|
49
|
+
// A self-transition exists to persist data; with no way at all to do that — no data write, no
|
|
50
|
+
// create, no effect — reject before running anything rather than half-applying.
|
|
51
|
+
if (isSelfTransition && !io.writeData && !io.runEffect) {
|
|
52
|
+
return {
|
|
53
|
+
success: false,
|
|
54
|
+
data: null,
|
|
55
|
+
error: `Action "${label}" persists record data in place, which this backend does not support.`,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
// Read the authoritative state only when something actually consumes it: the guard, or a
|
|
59
|
+
// state outcome that the caller's readState is paired with. A handler-only command on a
|
|
60
|
+
// doctype with no `status` column must not be forced through a read it never uses.
|
|
61
|
+
const isGuarded = (actionDef.allowedStates?.length ?? 0) > 0;
|
|
62
|
+
let currentState;
|
|
63
|
+
if (isGuarded || hasStateOutcome) {
|
|
64
|
+
const state = await io.readState();
|
|
65
|
+
// A missing record is reported, never guarded around. Reaching the guard with a state of
|
|
66
|
+
// `''` produced two wrong answers depending only on whether the action declared
|
|
67
|
+
// `allowedStates`: a misleading "not allowed from state: (unknown)" when it did, and a
|
|
68
|
+
// silent `{ success: true }` writing nothing when it did not.
|
|
69
|
+
if (state === null) {
|
|
70
|
+
// A self-transition against a record that is not there is a create — the same write,
|
|
71
|
+
// against a row that does not exist yet. The guard is deliberately skipped:
|
|
72
|
+
// `allowedStates` constrains movement between states, and a record being created is not
|
|
73
|
+
// in one; its initial state is the backend's to set.
|
|
74
|
+
//
|
|
75
|
+
// A registered effect does NOT run here. An effect is written against an existing row,
|
|
76
|
+
// and firing it against a just-created one is a different contract than the one it was
|
|
77
|
+
// registered under; making creation observable to effects is deferred rather than
|
|
78
|
+
// guessed at.
|
|
79
|
+
if (isSelfTransition && io.writeData) {
|
|
80
|
+
const created = await io.writeData(data ?? {}, false);
|
|
81
|
+
// A backend that only knows how to patch returns nothing here, having matched no
|
|
82
|
+
// row. Reporting that as success is the exact bug the `null` answer above exists to
|
|
83
|
+
// kill, so it must not come back through the create path.
|
|
84
|
+
if (!created || Object.keys(created).length === 0) {
|
|
85
|
+
return {
|
|
86
|
+
success: false,
|
|
87
|
+
data: null,
|
|
88
|
+
error: `Action "${label}" targets a record that does not exist, and the backend did not create it.`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return { success: true, data: created, error: null };
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
success: false,
|
|
95
|
+
data: null,
|
|
96
|
+
error: `Action "${label}" targets a record that does not exist — nothing was executed.`,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
currentState = state ?? '';
|
|
100
|
+
}
|
|
101
|
+
if (!isActionAllowedInState(actionDef, currentState ?? '')) {
|
|
38
102
|
return {
|
|
39
103
|
success: false,
|
|
40
104
|
data: null,
|
|
41
105
|
error: `Action not allowed from state: ${currentState || '(unknown)'}`,
|
|
42
106
|
};
|
|
43
107
|
}
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
|
|
48
|
-
|
|
108
|
+
// The effect runs after the guard and before any write, so a handler that rejects cannot
|
|
109
|
+
// leave the record in the target state. Its throw is attributed to the action by name —
|
|
110
|
+
// the adapter's handler is code the doctype author cannot see, so an anonymous failure
|
|
111
|
+
// would be undebuggable from either side.
|
|
112
|
+
let effectResult;
|
|
113
|
+
if (io.runEffect) {
|
|
114
|
+
try {
|
|
115
|
+
effectResult = await io.runEffect(currentState);
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
49
118
|
return {
|
|
50
119
|
success: false,
|
|
51
120
|
data: null,
|
|
52
|
-
error: `Action "${
|
|
121
|
+
error: `Action "${label}" failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
53
122
|
};
|
|
54
123
|
}
|
|
55
|
-
|
|
56
|
-
|
|
124
|
+
}
|
|
125
|
+
// Self-transition: mutate record data in place, keep the current state. The full updated
|
|
126
|
+
// record is returned so the client writeback reflects the new data. When the backend has no
|
|
127
|
+
// data-write path the effect above already did the persisting (guarded at the top).
|
|
128
|
+
if (isSelfTransition) {
|
|
129
|
+
const record = io.writeData ? await io.writeData(data ?? {}, true) : effectResult;
|
|
130
|
+
return { success: true, data: record ?? null, error: null };
|
|
57
131
|
}
|
|
58
132
|
// NON-ATOMIC: the current state is read above and nextState written here as two
|
|
59
|
-
// separate statements
|
|
60
|
-
// the guard before either writes, so both
|
|
61
|
-
// them to be mutually exclusive. Closing this
|
|
62
|
-
//
|
|
63
|
-
//
|
|
133
|
+
// separate statements — and a registered effect runs between them. Two concurrent
|
|
134
|
+
// transitions on the same record can both pass the guard before either writes, so both
|
|
135
|
+
// "succeed" even when the workflow intended them to be mutually exclusive. Closing this
|
|
136
|
+
// requires guarding and writing in one statement — an atomic
|
|
137
|
+
// `UPDATE ... SET status = nextState WHERE status = ANY(allowedStates)` — and reporting
|
|
138
|
+
// "no rows updated" as a rejected transition. Deferred for now.
|
|
64
139
|
if (actionDef.nextState == null) {
|
|
65
|
-
//
|
|
66
|
-
|
|
140
|
+
// A stateless command: the effect (guaranteed present by the top guard) is the whole
|
|
141
|
+
// outcome. It must not move the record — that is the doctype's call, not the handler's.
|
|
142
|
+
return { success: true, data: effectResult ?? null, error: null };
|
|
67
143
|
}
|
|
68
144
|
await io.writeState(actionDef.nextState);
|
|
145
|
+
// The freshest thing the backend produced wins: a handler that returned a record describes
|
|
146
|
+
// the row better than the state alone, which is all a bare transition knows.
|
|
69
147
|
return {
|
|
70
148
|
success: true,
|
|
71
|
-
data: { state: actionDef.nextState },
|
|
149
|
+
data: effectResult ?? { state: actionDef.nextState },
|
|
72
150
|
error: null,
|
|
73
151
|
};
|
|
74
152
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { DoctypeField, TableField, ValueField } from '@stonecrop/schema';
|
|
2
|
+
/**
|
|
3
|
+
* Recursively flatten Fieldset containers into a flat array of non-container fields.
|
|
4
|
+
* Fieldset entries are replaced by their children; all other fields pass through.
|
|
5
|
+
*
|
|
6
|
+
* A fieldset is a layout grouping, not a scope: every field inside one is a field of the doctype,
|
|
7
|
+
* with a column of its own and a name a link can bind to. Anything asking "what does this doctype
|
|
8
|
+
* declare" must therefore descend, and the two ways to get that wrong point opposite ways — the
|
|
9
|
+
* SELECT builder would omit real columns, while a validator would report a working declaration as
|
|
10
|
+
* broken.
|
|
11
|
+
*
|
|
12
|
+
* Lives here rather than beside either caller because it now has three of them across two modules
|
|
13
|
+
* (`getSqlColumns` and `knownFields` in the plugin, `validateReferences` in the registry), and a
|
|
14
|
+
* second copy is how the plugin and the registry would come to disagree about what a doctype
|
|
15
|
+
* declares. Internal — not re-exported from the package index.
|
|
16
|
+
*/
|
|
17
|
+
export declare function flattenFields(fields: readonly DoctypeField[]): (ValueField | TableField)[];
|
|
18
|
+
/**
|
|
19
|
+
* The fields that have a database column of their own — the one definition of that question.
|
|
20
|
+
*
|
|
21
|
+
* Two properties disqualify a field, and both are the field saying so itself: a `computed` field is
|
|
22
|
+
* declared precisely to state it has no column, and a container (a table field) is a relation
|
|
23
|
+
* rather than a value. Everything else names a column.
|
|
24
|
+
*
|
|
25
|
+
* This is deliberately **not** the same question as "does this column belong in a record payload".
|
|
26
|
+
* An *expanding* link's foreign key has a real column that this returns, while `collectColumns`
|
|
27
|
+
* omits it from the SELECT on purpose because the relation is fetched separately. Conflating the
|
|
28
|
+
* two is how the read path came to drop the very column its expansion needed. Callers wanting the
|
|
29
|
+
* payload projection filter this further by render mode; callers asking whether a column exists —
|
|
30
|
+
* link validation, and the write path deciding what it may set — want it unfiltered.
|
|
31
|
+
*
|
|
32
|
+
* Extracted because the rule had grown three statements across two modules, one of them a comment
|
|
33
|
+
* reading "mirrors `collectColumns`". A rule that has to be mirrored by hand is one edit away from
|
|
34
|
+
* the read path and the validator disagreeing about what a doctype declares.
|
|
35
|
+
*/
|
|
36
|
+
export declare function columnBackedFields(fields: readonly DoctypeField[]): ValueField[];
|
|
37
|
+
//# sourceMappingURL=fields.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fields.d.ts","sourceRoot":"","sources":["../../src/fields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAE7E;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,CAAC,UAAU,GAAG,UAAU,CAAC,EAAE,CAU1F;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,UAAU,EAAE,CAEhF"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recursively flatten Fieldset containers into a flat array of non-container fields.
|
|
3
|
+
* Fieldset entries are replaced by their children; all other fields pass through.
|
|
4
|
+
*
|
|
5
|
+
* A fieldset is a layout grouping, not a scope: every field inside one is a field of the doctype,
|
|
6
|
+
* with a column of its own and a name a link can bind to. Anything asking "what does this doctype
|
|
7
|
+
* declare" must therefore descend, and the two ways to get that wrong point opposite ways — the
|
|
8
|
+
* SELECT builder would omit real columns, while a validator would report a working declaration as
|
|
9
|
+
* broken.
|
|
10
|
+
*
|
|
11
|
+
* Lives here rather than beside either caller because it now has three of them across two modules
|
|
12
|
+
* (`getSqlColumns` and `knownFields` in the plugin, `validateReferences` in the registry), and a
|
|
13
|
+
* second copy is how the plugin and the registry would come to disagree about what a doctype
|
|
14
|
+
* declares. Internal — not re-exported from the package index.
|
|
15
|
+
*/
|
|
16
|
+
export function flattenFields(fields) {
|
|
17
|
+
const result = [];
|
|
18
|
+
for (const f of fields) {
|
|
19
|
+
if (f.kind === 'fieldset') {
|
|
20
|
+
result.push(...flattenFields(f.schema));
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
result.push(f);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The fields that have a database column of their own — the one definition of that question.
|
|
30
|
+
*
|
|
31
|
+
* Two properties disqualify a field, and both are the field saying so itself: a `computed` field is
|
|
32
|
+
* declared precisely to state it has no column, and a container (a table field) is a relation
|
|
33
|
+
* rather than a value. Everything else names a column.
|
|
34
|
+
*
|
|
35
|
+
* This is deliberately **not** the same question as "does this column belong in a record payload".
|
|
36
|
+
* An *expanding* link's foreign key has a real column that this returns, while `collectColumns`
|
|
37
|
+
* omits it from the SELECT on purpose because the relation is fetched separately. Conflating the
|
|
38
|
+
* two is how the read path came to drop the very column its expansion needed. Callers wanting the
|
|
39
|
+
* payload projection filter this further by render mode; callers asking whether a column exists —
|
|
40
|
+
* link validation, and the write path deciding what it may set — want it unfiltered.
|
|
41
|
+
*
|
|
42
|
+
* Extracted because the rule had grown three statements across two modules, one of them a comment
|
|
43
|
+
* reading "mirrors `collectColumns`". A rule that has to be mirrored by hand is one edit away from
|
|
44
|
+
* the read path and the validator disagreeing about what a doctype declares.
|
|
45
|
+
*/
|
|
46
|
+
export function columnBackedFields(fields) {
|
|
47
|
+
return flattenFields(fields).filter((f) => f.kind === 'field' && !f.computed);
|
|
48
|
+
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
export type { DoctypeMeta, ValidationError } from '@stonecrop/schema';
|
|
2
|
-
export { loadDoctypes, loadDoctypesFromObject, getMeta, getAllMeta, hasMeta, clearRegistry,
|
|
2
|
+
export { loadDoctypes, loadDoctypesFromObject, getMeta, getAllMeta, hasMeta, clearRegistry, DoctypeValidationError, } from './registry/doctypes';
|
|
3
3
|
export type { LoadDoctypesOptions } from './registry/doctypes';
|
|
4
4
|
export { registerFetchHandler, getFetchHandler, clearFetchHandlers } from './registry/fetchHandlers';
|
|
5
5
|
export type { FetchHandler } from './registry/fetchHandlers';
|
|
6
6
|
export { applyGuardedTransition } from './dispatch/transition';
|
|
7
7
|
export type { GuardedTransitionIO } from './dispatch/transition';
|
|
8
8
|
export { createStonecropPlugin } from './plugin/postgraphile';
|
|
9
|
-
export type { StonecropPluginOptions } from './plugin/postgraphile';
|
|
9
|
+
export type { StonecropPluginOptions, ActionHandler, ActionHandlerContext } from './plugin/postgraphile';
|
|
10
10
|
export { createDebugPlugin } from './debug';
|
|
11
11
|
export type { DebugPluginOptions } from './debug';
|
|
12
12
|
export { typeDefs } from './typeDefs';
|
package/dist/src/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAGrE,OAAO,EACN,YAAY,EACZ,sBAAsB,EACtB,OAAO,EACP,UAAU,EACV,OAAO,EACP,aAAa,EACb,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAGrE,OAAO,EACN,YAAY,EACZ,sBAAsB,EACtB,OAAO,EACP,UAAU,EACV,OAAO,EACP,aAAa,EACb,sBAAsB,GACtB,MAAM,qBAAqB,CAAA;AAE5B,YAAY,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAA;AAG9D,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AACpG,YAAY,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAG5D,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAA;AAC9D,YAAY,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAGhE,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAA;AAC7D,YAAY,EAAE,sBAAsB,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAA;AAGxG,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAC3C,YAAY,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAEjD,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAGrC,OAAO,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AACjE,YAAY,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA"}
|
package/dist/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Doctype registry
|
|
2
|
-
export { loadDoctypes, loadDoctypesFromObject, getMeta, getAllMeta, hasMeta, clearRegistry,
|
|
2
|
+
export { loadDoctypes, loadDoctypesFromObject, getMeta, getAllMeta, hasMeta, clearRegistry, DoctypeValidationError, } from './registry/doctypes';
|
|
3
3
|
// Fetch handlers
|
|
4
4
|
export { registerFetchHandler, getFetchHandler, clearFetchHandlers } from './registry/fetchHandlers';
|
|
5
5
|
// Server-owned workflow transition (guarded by allowedStates)
|
|
@@ -1,5 +1,67 @@
|
|
|
1
1
|
import type { DoctypeMeta } from '@stonecrop/schema';
|
|
2
|
+
import type { PgClient } from '@dataplan/pg';
|
|
2
3
|
import { GraphileConfig } from 'postgraphile/graphile-build';
|
|
4
|
+
/**
|
|
5
|
+
* Everything a server-side action handler is given when `stonecropAction` dispatches to it.
|
|
6
|
+
*
|
|
7
|
+
* A context object rather than positional parameters so the set can grow without breaking
|
|
8
|
+
* registered handlers — the adapters that supply these live in consumer repositories.
|
|
9
|
+
* @public
|
|
10
|
+
*/
|
|
11
|
+
export interface ActionHandlerContext {
|
|
12
|
+
/**
|
|
13
|
+
* Active database client for the current request. **It is inside the action's transaction.**
|
|
14
|
+
*
|
|
15
|
+
* The guard read, this handler, and the state write all run on this client inside one
|
|
16
|
+
* transaction, so the action is atomic: throw, and everything this handler wrote is rolled
|
|
17
|
+
* back along with the state change. Returning normally commits the lot.
|
|
18
|
+
*
|
|
19
|
+
* Do **not** open your own `BEGIN`/`COMMIT` around these statements. A `COMMIT` here would
|
|
20
|
+
* close the action's transaction early, committing work the guard may still reject. If you
|
|
21
|
+
* need to undo part of your own work without failing the action, use a `SAVEPOINT`.
|
|
22
|
+
*
|
|
23
|
+
* Work sent to a *different* connection is outside all of this and will not be rolled back —
|
|
24
|
+
* so use this client rather than opening one of your own.
|
|
25
|
+
*
|
|
26
|
+
* Rows from a raw `pgClient.query()` carry snake_case **column** names, while the middleware's
|
|
27
|
+
* own read paths alias them to camelCase fieldnames at the SQL layer (ADR 0004). A handler that
|
|
28
|
+
* returns raw rows therefore leaks snake_case keys to the client. Alias in SQL
|
|
29
|
+
* (`"display_name" AS "displayName"`) or convert with `snakeToCamel` from `@stonecrop/schema`.
|
|
30
|
+
*/
|
|
31
|
+
pgClient: PgClient;
|
|
32
|
+
/** The doctype the action was dispatched against, as the client sent it. */
|
|
33
|
+
doctype: string;
|
|
34
|
+
/** The action's key in `workflow.actions` — the same string the handler was registered under. */
|
|
35
|
+
action: string;
|
|
36
|
+
/** The resolved doctype metadata, for field names, the primary key, and the workflow. */
|
|
37
|
+
meta: DoctypeMeta;
|
|
38
|
+
/** The target record's identity, taken from the first argument envelope. Absent for a record-less command. */
|
|
39
|
+
recordId?: string | number;
|
|
40
|
+
/**
|
|
41
|
+
* The record field data the client sent (`args[0].data`).
|
|
42
|
+
*
|
|
43
|
+
* Unvalidated: `args` is an opaque `JSON` scalar, so this is browser-supplied input that has
|
|
44
|
+
* passed through no schema. Treat it as untrusted — parameterize it into SQL and whitelist
|
|
45
|
+
* the fields the action is allowed to touch.
|
|
46
|
+
*/
|
|
47
|
+
data: Record<string, unknown>;
|
|
48
|
+
/** The full argument envelope, for the actions that need more than the first record. */
|
|
49
|
+
args: unknown[];
|
|
50
|
+
/** The state the guard read, or `undefined` when nothing about the action required reading it. */
|
|
51
|
+
currentState?: string;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* A server-side effect for one doctype action, supplied by whoever owns the database.
|
|
55
|
+
*
|
|
56
|
+
* Throwing rejects the action and no state is written. Returning the updated record makes it the
|
|
57
|
+
* client writeback payload; returning `undefined` leaves the doctype's own outcome to decide.
|
|
58
|
+
*
|
|
59
|
+
* The return value is passed through verbatim as `StonecropActionResult.data`, so it must be
|
|
60
|
+
* API-layer data — camelCase fieldname keys, not raw snake_case columns. See `pgClient` above and
|
|
61
|
+
* ADR 0007.
|
|
62
|
+
* @public
|
|
63
|
+
*/
|
|
64
|
+
export type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>;
|
|
3
65
|
/**
|
|
4
66
|
* Options for creating a Stonecrop PostGraphile plugin.
|
|
5
67
|
* @public
|
|
@@ -17,6 +79,67 @@ export interface StonecropPluginOptions {
|
|
|
17
79
|
* When absent for a doctype, the table name is derived as `camelToSnake(doctype.name)`.
|
|
18
80
|
*/
|
|
19
81
|
tables?: Record<string, string>;
|
|
82
|
+
/**
|
|
83
|
+
* Server-side effects for workflow actions, keyed `[doctype name][action key]`.
|
|
84
|
+
*
|
|
85
|
+
* This is the seam that makes a stateless Command executable. `applyGuardedTransition` can
|
|
86
|
+
* apply a doctype's own outcome — a `nextState` transition, or a `selfTransition` data write —
|
|
87
|
+
* but an action that is neither has nothing to apply and fails loudly. Registering a handler
|
|
88
|
+
* here supplies the missing half.
|
|
89
|
+
*
|
|
90
|
+
* **The doctype never names a handler, and a handler never overrides the guard.** The two are
|
|
91
|
+
* authored by different people: a doctype is runtime data edited in DocBuilder by whoever
|
|
92
|
+
* models the workflow, while these run behind the GraphQL surface and belong to whoever owns
|
|
93
|
+
* the database. So the doctype keeps `allowedStates` (may this run) and `nextState` (what state
|
|
94
|
+
* results), and this keeps the effect (what actually happens). Routing between them is
|
|
95
|
+
* resolved here, on the server, and is never published to the client.
|
|
96
|
+
*
|
|
97
|
+
* Handlers are looked up by `meta.name` — the doctype's canonical name, not its slug. An
|
|
98
|
+
* unregistered action is not an error in itself: a transition needs no handler. It fails only
|
|
99
|
+
* when the doctype gave the action no outcome either, and the error then names the action and
|
|
100
|
+
* both ways to fix it, so a typo'd key reports as a missing effect rather than a silent no-op.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```ts
|
|
104
|
+
* createStonecropPlugin({
|
|
105
|
+
* actionHandlers: {
|
|
106
|
+
* Order: {
|
|
107
|
+
* async recalculateTotal({ pgClient, recordId }) {
|
|
108
|
+
* const { rows } = await pgClient.query({
|
|
109
|
+
* text: 'UPDATE "order" SET total = (SELECT COALESCE(SUM(amount), 0) FROM order_item WHERE order_id = $1) WHERE id = $1 RETURNING *',
|
|
110
|
+
* values: [recordId],
|
|
111
|
+
* })
|
|
112
|
+
* return rows[0]
|
|
113
|
+
* },
|
|
114
|
+
* },
|
|
115
|
+
* },
|
|
116
|
+
* })
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
actionHandlers?: Record<string, Record<string, ActionHandler>>;
|
|
120
|
+
/**
|
|
121
|
+
* Row cap applied when nothing else names one: to `stonecropRecords` when the caller requests
|
|
122
|
+
* no `limit`, and to a many-side link when its declaration carries no `fetch.limit`. Defaults
|
|
123
|
+
* to 200.
|
|
124
|
+
*
|
|
125
|
+
* A row cap is a statement about what this database can afford to serve, so it belongs to
|
|
126
|
+
* whoever owns the database — not to a doctype (which describes the API surface, not the
|
|
127
|
+
* table) and not to a page (which cannot know the size of an arbitrary table). Callers stay
|
|
128
|
+
* free to ask for less; they cannot ask for an unbounded scan by omission.
|
|
129
|
+
*
|
|
130
|
+
* One number covers both reads because a link *is* a list, fetched a different way. It used to
|
|
131
|
+
* be capped at a hard-coded 50 that no option could reach, which is how an operator watching a
|
|
132
|
+
* slow query found there was no knob to turn.
|
|
133
|
+
*
|
|
134
|
+
* Truncation is always reported — `hasMore` for a list, `truncatedLinks` for a record — so a
|
|
135
|
+
* partial answer is distinguishable from a complete one without asking for a count. That
|
|
136
|
+
* matters more for a link than for a list: a link cannot be paged, so a client that writes
|
|
137
|
+
* back a truncated relation deletes the rows it was never sent.
|
|
138
|
+
*
|
|
139
|
+
* Set to `null` for no default cap. That is the pre-0.17 behaviour for lists, and it means an
|
|
140
|
+
* unqualified list query returns the whole table and a link returns the whole relation.
|
|
141
|
+
*/
|
|
142
|
+
defaultRecordLimit?: number | null;
|
|
20
143
|
}
|
|
21
144
|
/**
|
|
22
145
|
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgraphile.d.ts","sourceRoot":"","sources":["../../../src/plugin/postgraphile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"postgraphile.d.ts","sourceRoot":"","sources":["../../../src/plugin/postgraphile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,WAAW,EAAiD,MAAM,mBAAmB,CAAA;AAGjH,OAAO,KAAK,EAAE,QAAQ,EAAc,MAAM,cAAc,CAAA;AAExD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAS5D;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACpC;;;;;;;;;;;;;;;;;;OAkBG;IACH,QAAQ,EAAE,QAAQ,CAAA;IAClB,4EAA4E;IAC5E,OAAO,EAAE,MAAM,CAAA;IACf,iGAAiG;IACjG,MAAM,EAAE,MAAM,CAAA;IACd,yFAAyF;IACzF,IAAI,EAAE,WAAW,CAAA;IACjB,8GAA8G;IAC9G,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IAC1B;;;;;;OAMG;IACH,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,wFAAwF;IACxF,IAAI,EAAE,OAAO,EAAE,CAAA;IACf,kGAAkG;IAClG,YAAY,CAAC,EAAE,MAAM,CAAA;CACrB;AAED;;;;;;;;;;GAUG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,oBAAoB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;AAE/E;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACtC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IACf;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAoCG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAA;IAC9D;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAClC;AAmCD;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GAAI,UAAS,sBAA2B,KAAG,cAAc,CAAC,MAgqB3F,CAAA;AA0BD;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,CAQvD"}
|