@stonecrop/graphql-middleware 0.16.6 → 0.17.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 +189 -27
- package/dist/index.js +420 -304
- 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/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 +115 -0
- package/dist/src/plugin/postgraphile.d.ts.map +1 -1
- package/dist/src/plugin/postgraphile.js +256 -47
- package/dist/src/registry/doctypes.d.ts +18 -3
- package/dist/src/registry/doctypes.d.ts.map +1 -1
- package/dist/src/registry/doctypes.js +21 -6
- package/dist/src/typeDefs.d.ts.map +1 -1
- package/dist/src/typeDefs.js +11 -1
- package/package.json +2 -2
|
@@ -1,11 +1,27 @@
|
|
|
1
|
-
import { camelToSnake,
|
|
1
|
+
import { camelToSnake, getRecordIdField, pascalToSnake, resolveLinkRenderMode } from '@stonecrop/schema';
|
|
2
2
|
import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
|
|
3
3
|
import { constant, lambda, object } from 'postgraphile/grafast';
|
|
4
4
|
import { extendSchema } from 'postgraphile/utils';
|
|
5
5
|
import { getFetchHandler } from '../registry/fetchHandlers';
|
|
6
|
-
import { getMeta, getAllMeta } from '../registry/doctypes';
|
|
6
|
+
import { getMeta, getAllMeta, validateReferences } from '../registry/doctypes';
|
|
7
7
|
import { applyGuardedTransition } from '../dispatch/transition';
|
|
8
8
|
import { typeDefs } from '../typeDefs';
|
|
9
|
+
/**
|
|
10
|
+
* Carries a reported failure out through a `throw`, purely so the transaction rolls back.
|
|
11
|
+
*
|
|
12
|
+
* `applyGuardedTransition` reports every failure as a return value, and a value returned from
|
|
13
|
+
* inside `withTransaction` commits. This is the adapter between "the action failed" and "undo it"
|
|
14
|
+
* that does not also turn a refused guard into a GraphQL error: the dispatcher unwraps it and
|
|
15
|
+
* answers with the original envelope.
|
|
16
|
+
*/
|
|
17
|
+
class ActionRolledBack extends Error {
|
|
18
|
+
outcome;
|
|
19
|
+
constructor(outcome) {
|
|
20
|
+
super(outcome.error ?? 'Action failed');
|
|
21
|
+
this.outcome = outcome;
|
|
22
|
+
this.name = 'ActionRolledBack';
|
|
23
|
+
}
|
|
24
|
+
}
|
|
9
25
|
/**
|
|
10
26
|
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
|
|
11
27
|
*
|
|
@@ -37,6 +53,11 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
37
53
|
if (!executor) {
|
|
38
54
|
throw new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured');
|
|
39
55
|
}
|
|
56
|
+
// Schema build is the one point where both the registry and the plugin's options are in
|
|
57
|
+
// hand, so it is where a stale registration can be caught before it silently no-ops.
|
|
58
|
+
if (options.actionHandlers)
|
|
59
|
+
assertActionHandlersResolve(options.actionHandlers);
|
|
60
|
+
assertReferencesResolve();
|
|
40
61
|
return {
|
|
41
62
|
typeDefs,
|
|
42
63
|
objects: {
|
|
@@ -69,12 +90,11 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
69
90
|
results[i] = { data: null, doctype };
|
|
70
91
|
continue;
|
|
71
92
|
}
|
|
93
|
+
// Not `data: null` — that is the answer for a record that does not exist, and a
|
|
94
|
+
// doctype nobody can look up is a misconfiguration, not an empty result.
|
|
72
95
|
const pkMeta = getPkMeta(meta);
|
|
73
|
-
if (!pkMeta)
|
|
74
|
-
|
|
75
|
-
results[i] = { data: null, doctype };
|
|
76
|
-
continue;
|
|
77
|
-
}
|
|
96
|
+
if (!pkMeta)
|
|
97
|
+
throw unresolvableIdentityError(doctype);
|
|
78
98
|
const pkColumn = camelToSnake(pkMeta.fieldname);
|
|
79
99
|
const columns = getSqlColumns(meta);
|
|
80
100
|
const ids = indices.map(i => String(specs[i].id));
|
|
@@ -87,6 +107,21 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
87
107
|
});
|
|
88
108
|
// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
|
|
89
109
|
const rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]));
|
|
110
|
+
// A declared key the database does not actually enforce as unique collapses several
|
|
111
|
+
// rows into that Map, and it keeps whichever came last — one arbitrary record,
|
|
112
|
+
// returned as though it were *the* record, with nothing to say so. Refuse instead.
|
|
113
|
+
//
|
|
114
|
+
// This is exact rather than a proxy for the problem: `ANY` matches each requested id
|
|
115
|
+
// once, so a shortfall here means two distinct rows genuinely share a key value. A
|
|
116
|
+
// `pg_index` check would instead ask whether a unique constraint exists, which is the
|
|
117
|
+
// cause rather than the harm — and would flag a column that is unique in practice but
|
|
118
|
+
// unconstrained, which is a real and common shape.
|
|
119
|
+
if (rows.length !== rowByPk.size) {
|
|
120
|
+
throw new Error(`Doctype "${doctype}" declares "${pkMeta.fieldname}" as its identity, but that column ` +
|
|
121
|
+
`is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows ` +
|
|
122
|
+
`matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. ` +
|
|
123
|
+
`Declare a field that uniquely identifies a record, or add a unique constraint.`);
|
|
124
|
+
}
|
|
90
125
|
for (const i of indices) {
|
|
91
126
|
const specId = String(specs[i].id);
|
|
92
127
|
const row = rowByPk.get(specId);
|
|
@@ -152,9 +187,12 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
152
187
|
rowData[linkName] = null;
|
|
153
188
|
continue;
|
|
154
189
|
}
|
|
190
|
+
// `continue` here would drop the link from the payload, which reads to the
|
|
191
|
+
// client as "this record has no such relation" rather than "its target
|
|
192
|
+
// cannot be identified".
|
|
155
193
|
const targetPkMeta = getPkMeta(targetMeta);
|
|
156
194
|
if (!targetPkMeta)
|
|
157
|
-
|
|
195
|
+
throw unresolvableIdentityError(targetMeta.name);
|
|
158
196
|
const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
|
|
159
197
|
// TODO(perf): one-side link FK lookups per row could be parallelized; needs collecting across links before await
|
|
160
198
|
// oxlint-disable-next-line eslint/no-await-in-loop -- one FK lookup per link per row; see TODO above
|
|
@@ -178,19 +216,24 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
178
216
|
return results;
|
|
179
217
|
});
|
|
180
218
|
},
|
|
181
|
-
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset }) {
|
|
219
|
+
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
|
|
182
220
|
return loadOneWithPgClient(executor, object({
|
|
183
221
|
doctype: $doctype,
|
|
184
222
|
filters: $filters,
|
|
185
223
|
orderBy: $orderBy,
|
|
186
224
|
limit: $limit,
|
|
187
225
|
offset: $offset,
|
|
226
|
+
includeTotal: $includeTotal,
|
|
188
227
|
}), async (pgClient, specs) => {
|
|
189
228
|
return await Promise.all(specs.map(async (spec) => {
|
|
190
229
|
const doctype = String(spec.doctype);
|
|
191
230
|
const meta = getMeta(doctype);
|
|
192
231
|
if (!meta) {
|
|
193
|
-
|
|
232
|
+
// An unknown doctype answers "no records" rather than erroring, so a caller
|
|
233
|
+
// who asked for a total gets 0. Returning null here would make null mean
|
|
234
|
+
// two things — "you did not ask" and "I could not say" — and a client
|
|
235
|
+
// cannot tell those apart.
|
|
236
|
+
return { data: [], doctype, hasMore: false, count: spec.includeTotal === true ? 0 : null };
|
|
194
237
|
}
|
|
195
238
|
const knownFields = new Set(flattenFields(meta.fields).map(f => f.fieldname));
|
|
196
239
|
const columns = getSqlColumns(meta);
|
|
@@ -228,10 +271,22 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
228
271
|
}
|
|
229
272
|
orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
|
|
230
273
|
}
|
|
231
|
-
// LIMIT / OFFSET
|
|
274
|
+
// LIMIT / OFFSET. A caller that names no limit gets the configured default rather
|
|
275
|
+
// than the whole table: omission is how an unbounded scan used to happen, and the
|
|
276
|
+
// only guard against it lived in the scaffold's fetch helper, which is neither the
|
|
277
|
+
// right layer nor present in a host that wrote its own.
|
|
278
|
+
// Grafast passes arguments through as loosely-typed runtime values, so narrow
|
|
279
|
+
// before doing arithmetic on this — same reason orderBy is validated above.
|
|
280
|
+
if (spec.limit != null && typeof spec.limit !== 'number') {
|
|
281
|
+
throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
|
|
282
|
+
}
|
|
283
|
+
const effectiveLimit = spec.limit ?? (options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit);
|
|
232
284
|
let pagingClause = '';
|
|
233
|
-
if (
|
|
234
|
-
|
|
285
|
+
if (effectiveLimit != null) {
|
|
286
|
+
// One more row than asked for. Its presence is the whole `hasMore` answer, and
|
|
287
|
+
// it is discarded below — this is why knowing a list is truncated costs no
|
|
288
|
+
// second query, where a COUNT(*) would be a full scan on every list read.
|
|
289
|
+
values.push(effectiveLimit + 1);
|
|
235
290
|
pagingClause += ` LIMIT $${values.length}`;
|
|
236
291
|
}
|
|
237
292
|
if (spec.offset != null) {
|
|
@@ -242,9 +297,19 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
242
297
|
text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,
|
|
243
298
|
values,
|
|
244
299
|
});
|
|
245
|
-
//
|
|
246
|
-
|
|
247
|
-
|
|
300
|
+
// The extra row requested above is a probe, not data. Its presence is what makes
|
|
301
|
+
// a capped page distinguishable from a complete table; trim it before anything
|
|
302
|
+
// downstream can mistake it for a record.
|
|
303
|
+
const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
|
|
304
|
+
const data = hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows;
|
|
305
|
+
// Total matching the filters, independent of LIMIT/OFFSET, and opt-in.
|
|
306
|
+
//
|
|
307
|
+
// Explicitly requested rather than inferred from whether `count` was selected:
|
|
308
|
+
// this resolver is a Grafast plan step and receives only its arguments, never the
|
|
309
|
+
// selection set, and making the plan vary by selection is what Grafast optimises
|
|
310
|
+
// against. An argument also puts the cost in the query the client wrote.
|
|
311
|
+
let count = null;
|
|
312
|
+
if (spec.includeTotal === true) {
|
|
248
313
|
const countValues = [];
|
|
249
314
|
const countWhere = [];
|
|
250
315
|
if (spec.filters != null) {
|
|
@@ -263,7 +328,7 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
263
328
|
});
|
|
264
329
|
count = parseInt(countRows[0]?.row_count ?? '0', 10);
|
|
265
330
|
}
|
|
266
|
-
return { data
|
|
331
|
+
return { data, doctype, hasMore, count };
|
|
267
332
|
}));
|
|
268
333
|
});
|
|
269
334
|
},
|
|
@@ -289,40 +354,87 @@ export const createStonecropPlugin = (options = {}) => {
|
|
|
289
354
|
error: `Unknown action: ${spec.action} on ${spec.doctype}`,
|
|
290
355
|
};
|
|
291
356
|
}
|
|
292
|
-
const pkMeta = getPkMeta(meta);
|
|
293
|
-
if (!pkMeta) {
|
|
294
|
-
return {
|
|
295
|
-
success: false,
|
|
296
|
-
data: null,
|
|
297
|
-
error: `No primary key for doctype: ${spec.doctype}`,
|
|
298
|
-
};
|
|
299
|
-
}
|
|
300
|
-
const pkColumn = camelToSnake(pkMeta.fieldname);
|
|
301
357
|
const table = resolveTableName(meta.name, options.tables);
|
|
358
|
+
// Resolved lazily: only a state read or write needs the key column. A
|
|
359
|
+
// record-less command reaches its handler on a doctype that declares no
|
|
360
|
+
// primary key, which an eager check would refuse for no reason.
|
|
361
|
+
const pkColumn = () => {
|
|
362
|
+
const pkMeta = getPkMeta(meta);
|
|
363
|
+
if (!pkMeta)
|
|
364
|
+
throw unresolvableIdentityError(String(spec.doctype));
|
|
365
|
+
return camelToSnake(pkMeta.fieldname);
|
|
366
|
+
};
|
|
302
367
|
// Record envelope: [{ id, data }] — the transition keys off the record id.
|
|
303
368
|
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.actionArgs is a Grafast runtime value; record envelope shape is the dispatch contract
|
|
304
369
|
const argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []);
|
|
305
370
|
const recordId = argList[0]?.id;
|
|
371
|
+
const recordData = argList[0]?.data ?? {};
|
|
372
|
+
// The database author's effect for this action, if one is registered. Keyed
|
|
373
|
+
// by the doctype's canonical name so a slug-resolved lookup above cannot
|
|
374
|
+
// silently miss it.
|
|
375
|
+
const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
|
|
376
|
+
// One transaction spans the guard read, the effect and the state write, so an
|
|
377
|
+
// action either lands whole or not at all. `withTransaction` issues `begin` at
|
|
378
|
+
// the top level and a `savepoint` if something upstream already opened one, so
|
|
379
|
+
// nesting is safe rather than something callers must avoid.
|
|
380
|
+
//
|
|
381
|
+
// Every statement below runs on `tx`, not on the outer client. Work sent to the
|
|
382
|
+
// outer client — or to a connection a handler opens itself — is outside this
|
|
383
|
+
// transaction and would survive a rollback.
|
|
306
384
|
try {
|
|
307
|
-
return await
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
385
|
+
return await pgClient.withTransaction(async (tx) => {
|
|
386
|
+
const outcome = await applyGuardedTransition(actionDef, {
|
|
387
|
+
readState: async () => {
|
|
388
|
+
// No id in the envelope means no record was targeted at all, which is
|
|
389
|
+
// the same answer as a lookup that misses: `null`, not `undefined`.
|
|
390
|
+
if (recordId == null)
|
|
391
|
+
return null;
|
|
392
|
+
// FOR UPDATE holds the row until this transaction ends, so a second
|
|
393
|
+
// action on the same record waits rather than reading the same state
|
|
394
|
+
// and acting on it too. Without it the guard is a check-then-act
|
|
395
|
+
// race: two concurrent approvals both read PENDING and both proceed.
|
|
396
|
+
const { rows } = await debugSql(tx, {
|
|
397
|
+
text: `SELECT "status" FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
|
|
398
|
+
values: [String(recordId)],
|
|
399
|
+
});
|
|
400
|
+
// No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.
|
|
401
|
+
if (rows.length === 0)
|
|
402
|
+
return null;
|
|
403
|
+
return rows[0].status ?? undefined;
|
|
404
|
+
},
|
|
405
|
+
writeState: async (nextState) => {
|
|
406
|
+
await debugSql(tx, {
|
|
407
|
+
text: `UPDATE ${table} SET "status" = $1 WHERE "${pkColumn()}"::text = $2`,
|
|
408
|
+
values: [nextState, String(recordId)],
|
|
409
|
+
});
|
|
410
|
+
},
|
|
411
|
+
runEffect: handler
|
|
412
|
+
? (currentState) => handler({
|
|
413
|
+
pgClient: tx,
|
|
414
|
+
doctype: String(spec.doctype),
|
|
415
|
+
action: String(spec.action),
|
|
416
|
+
meta,
|
|
417
|
+
recordId,
|
|
418
|
+
data: recordData,
|
|
419
|
+
args: argList,
|
|
420
|
+
currentState,
|
|
421
|
+
})
|
|
422
|
+
: undefined,
|
|
423
|
+
});
|
|
424
|
+
// `applyGuardedTransition` REPORTS failure, it does not throw — a refused
|
|
425
|
+
// guard and a handler that blew up both come back as `{ success: false }`.
|
|
426
|
+
// Returning that normally would commit the transaction, so a handler that
|
|
427
|
+
// wrote three rows and then threw would keep all three. Throwing here is
|
|
428
|
+
// what makes the rollback happen; the envelope is carried across so the
|
|
429
|
+
// caller still gets `success: false` rather than a GraphQL error.
|
|
430
|
+
if (!outcome.success)
|
|
431
|
+
throw new ActionRolledBack(outcome);
|
|
432
|
+
return outcome;
|
|
323
433
|
});
|
|
324
434
|
}
|
|
325
435
|
catch (err) {
|
|
436
|
+
if (err instanceof ActionRolledBack)
|
|
437
|
+
return err.outcome;
|
|
326
438
|
return {
|
|
327
439
|
success: false,
|
|
328
440
|
data: null,
|
|
@@ -402,14 +514,111 @@ export function getSqlColumns(meta) {
|
|
|
402
514
|
return collectColumns(meta.fields, links).join(', ');
|
|
403
515
|
}
|
|
404
516
|
/**
|
|
405
|
-
*
|
|
406
|
-
*
|
|
517
|
+
* Resolve the declared field this doctype's records are looked up by.
|
|
518
|
+
*
|
|
519
|
+
* Delegates the *rule* to `@stonecrop/schema` so the server's SQL identity predicate and the
|
|
520
|
+
* client's record keying name the same field — including the `id` fallback, whose absence here
|
|
521
|
+
* used to make the two disagree: a doctype declaring no `primaryKey` was keyed by `id` on the
|
|
522
|
+
* client and refused outright by this adapter, so every fetch answered `null` and looked exactly
|
|
523
|
+
* like a record that does not exist.
|
|
407
524
|
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
525
|
+
* Returns `undefined` only when the resolved name is not a declared top-level field — a doctype
|
|
526
|
+
* with no `primaryKey` and no `id`. That case cannot be served: `getSqlColumns` selects declared
|
|
527
|
+
* fields only, so the row map would key on a column the SELECT never returned and every lookup
|
|
528
|
+
* would miss silently. Callers must say so rather than answer `null`.
|
|
410
529
|
*/
|
|
411
530
|
function getPkMeta(meta) {
|
|
412
|
-
|
|
531
|
+
const fieldname = getRecordIdField(meta.fields);
|
|
532
|
+
return meta.fields.find((f) => f.kind === 'field' && f.fieldname === fieldname);
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Assert that every registered action handler names a doctype and an action that exist.
|
|
536
|
+
*
|
|
537
|
+
* An unregistered action is fine — a transition needs no effect. The reverse is not: a handler
|
|
538
|
+
* registered under a key nothing resolves to can never run, and **nothing says so at dispatch**.
|
|
539
|
+
* `applyGuardedTransition` fails loudly only when the action also has no state outcome; when it
|
|
540
|
+
* has one, the missing effect is skipped and the state write still reports success. So renaming a
|
|
541
|
+
* doctype leaves `approve` moving records to APPROVED while its ledger posting quietly stops.
|
|
542
|
+
*
|
|
543
|
+
* Two ways a key fails to resolve, and the second is the trap. `getMeta` falls back to matching a
|
|
544
|
+
* slug, but dispatch looks handlers up by `meta.name`, so a slug-keyed registration resolves to a
|
|
545
|
+
* real doctype here and still never fires. It is reported as its own case rather than as "unknown
|
|
546
|
+
* doctype", because the repair is different.
|
|
547
|
+
*
|
|
548
|
+
* Throws rather than warns: there is no legitimate reason to register a handler for an action that
|
|
549
|
+
* does not exist, and the alternative is a silent half-executed workflow. Every offender is
|
|
550
|
+
* collected so a consumer with several fixes them in one pass.
|
|
551
|
+
*/
|
|
552
|
+
function assertActionHandlersResolve(actionHandlers) {
|
|
553
|
+
// Nothing registered, nothing to check.
|
|
554
|
+
const registered = Object.entries(actionHandlers);
|
|
555
|
+
if (registered.length === 0)
|
|
556
|
+
return;
|
|
557
|
+
// An empty registry cannot tell "this key is stale" from "doctypes have not loaded yet" — a
|
|
558
|
+
// host is free to build the schema before its loader runs. Warn on that ambiguity rather than
|
|
559
|
+
// failing a boot that is merely early.
|
|
560
|
+
if (getAllMeta().length === 0) {
|
|
561
|
+
// oxlint-disable-next-line no-console
|
|
562
|
+
console.warn('[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the ' +
|
|
563
|
+
'`actionHandlers` map could not be verified. Load doctypes before building the schema to ' +
|
|
564
|
+
'have stale handler keys reported.');
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
const orphans = [];
|
|
568
|
+
for (const [doctypeKey, handlers] of registered) {
|
|
569
|
+
const meta = getMeta(doctypeKey);
|
|
570
|
+
if (!meta) {
|
|
571
|
+
orphans.push(`"${doctypeKey}": no doctype by that name is registered`);
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
if (meta.name !== doctypeKey) {
|
|
575
|
+
orphans.push(`"${doctypeKey}": matches the doctype named "${meta.name}" by slug, but handlers are looked up by name — key it "${meta.name}"`);
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
const actions = meta.workflow?.actions ?? {};
|
|
579
|
+
for (const actionKey of Object.keys(handlers)) {
|
|
580
|
+
if (!(actionKey in actions)) {
|
|
581
|
+
orphans.push(`"${doctypeKey}.${actionKey}": the doctype declares no action by that key`);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
if (orphans.length > 0) {
|
|
586
|
+
throw new Error(`StonecropPlugin: ${orphans.length} registered action handler${orphans.length === 1 ? '' : 's'} ` +
|
|
587
|
+
`cannot be reached and would never run:\n ${orphans.join('\n ')}`);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Refuse a doctype set whose links or `inherits` name a doctype nobody registered.
|
|
592
|
+
*
|
|
593
|
+
* What it prevents is silent: the link read does `const targetMeta = getMeta(link.target)` followed
|
|
594
|
+
* by `if (!targetMeta) continue`, so an unresolvable target drops the relation from the response
|
|
595
|
+
* with no error. On the wire that is indistinguishable from "this record has no such relation", and
|
|
596
|
+
* a typo in a target reads as a legitimately empty link forever.
|
|
597
|
+
*
|
|
598
|
+
* Throws rather than warns, like the handler check above: a link pointing at a doctype that does not
|
|
599
|
+
* exist has no correct reading. Every offender is collected so a consumer fixes them in one pass.
|
|
600
|
+
*
|
|
601
|
+
* Deliberately no empty-registry warning, unlike `assertActionHandlersResolve`. That one warns
|
|
602
|
+
* because a registered handler map is evidence the host meant to be checked; here there is no such
|
|
603
|
+
* evidence, so warning would fire on every host that loads doctypes after building its schema —
|
|
604
|
+
* and an advisory that fires on a correct setup is worse than none. An empty registry simply
|
|
605
|
+
* reports nothing, because the loop has nothing to walk.
|
|
606
|
+
*/
|
|
607
|
+
function assertReferencesResolve() {
|
|
608
|
+
const broken = validateReferences();
|
|
609
|
+
if (broken.length === 0)
|
|
610
|
+
return;
|
|
611
|
+
throw new Error(`StonecropPlugin: ${broken.length} doctype reference${broken.length === 1 ? '' : 's'} ` +
|
|
612
|
+
`cannot be resolved and would silently drop the relation:\n ` +
|
|
613
|
+
broken.map(e => `${e.path.join('.')}: ${e.message}`).join('\n '));
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* The error a caller raises when `getPkMeta` cannot resolve an identity field, naming the doctype
|
|
617
|
+
* and both repairs. Shared so the three lookup sites report one diagnosis.
|
|
618
|
+
*/
|
|
619
|
+
function unresolvableIdentityError(doctype) {
|
|
620
|
+
return new Error(`Doctype "${doctype}" has no identity field: it declares no field with \`primaryKey: true\` ` +
|
|
621
|
+
`and no field named \`id\`. Declare one of the two — records cannot be fetched or acted on until then.`);
|
|
413
622
|
}
|
|
414
623
|
/**
|
|
415
624
|
* Resolve the PostgreSQL FROM clause target for a doctype.
|
|
@@ -61,9 +61,24 @@ export declare function hasMeta(name: string): boolean;
|
|
|
61
61
|
*/
|
|
62
62
|
export declare function clearRegistry(): void;
|
|
63
63
|
/**
|
|
64
|
-
* Validate cross-doctype references (
|
|
65
|
-
*
|
|
66
|
-
*
|
|
64
|
+
* Validate cross-doctype references (link targets, `inherits`) against what is loaded.
|
|
65
|
+
*
|
|
66
|
+
* Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by
|
|
67
|
+
* doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as
|
|
68
|
+
* one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for
|
|
69
|
+
* every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.
|
|
70
|
+
* `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same
|
|
71
|
+
* question the runtime asks.
|
|
72
|
+
*
|
|
73
|
+
* `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers
|
|
74
|
+
* only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the
|
|
75
|
+
* permissive direction.
|
|
76
|
+
*
|
|
77
|
+
* Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that
|
|
78
|
+
* caller. Kept out of the package's public exports: it reads a module-level registry, so it is only
|
|
79
|
+
* meaningful after this module's own loaders have run.
|
|
80
|
+
*
|
|
81
|
+
* @internal
|
|
67
82
|
*/
|
|
68
83
|
export declare function validateReferences(): ValidationError[];
|
|
69
84
|
//# sourceMappingURL=doctypes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"doctypes.d.ts","sourceRoot":"","sources":["../../../src/registry/doctypes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAIrE;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAE/C,4DAA4D;aAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;aACtB,MAAM,EAAE,eAAe,EAAE;;IAHzC,4DAA4D;IAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;IACtB,MAAM,EAAE,eAAe,EAAE;CAM1C;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IACnC,2DAA2D;IAC3D,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,kEAAkE;IAClE,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,KAAK,IAAI,CAAA;CAC3D;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAajF;AAsCD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAgBjH;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAQ7D;AAED;;;GAGG;AACH,wBAAgB,UAAU,IAAI,WAAW,EAAE,CAE1C;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE7C;AAED;;;GAGG;AACH,wBAAgB,aAAa,IAAI,IAAI,CAEpC;AAED
|
|
1
|
+
{"version":3,"file":"doctypes.d.ts","sourceRoot":"","sources":["../../../src/registry/doctypes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAIrE;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAE/C,4DAA4D;aAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;aACtB,MAAM,EAAE,eAAe,EAAE;;IAHzC,4DAA4D;IAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;IACtB,MAAM,EAAE,eAAe,EAAE;CAM1C;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IACnC,2DAA2D;IAC3D,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,kEAAkE;IAClE,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,KAAK,IAAI,CAAA;CAC3D;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAajF;AAsCD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAgBjH;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAQ7D;AAED;;;GAGG;AACH,wBAAgB,UAAU,IAAI,WAAW,EAAE,CAE1C;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE7C;AAED;;;GAGG;AACH,wBAAgB,aAAa,IAAI,IAAI,CAEpC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,kBAAkB,IAAI,eAAe,EAAE,CAsCtD"}
|
|
@@ -131,15 +131,30 @@ export function clearRegistry() {
|
|
|
131
131
|
doctypeRegistry.clear();
|
|
132
132
|
}
|
|
133
133
|
/**
|
|
134
|
-
* Validate cross-doctype references (
|
|
135
|
-
*
|
|
136
|
-
*
|
|
134
|
+
* Validate cross-doctype references (link targets, `inherits`) against what is loaded.
|
|
135
|
+
*
|
|
136
|
+
* Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by
|
|
137
|
+
* doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as
|
|
138
|
+
* one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for
|
|
139
|
+
* every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.
|
|
140
|
+
* `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same
|
|
141
|
+
* question the runtime asks.
|
|
142
|
+
*
|
|
143
|
+
* `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers
|
|
144
|
+
* only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the
|
|
145
|
+
* permissive direction.
|
|
146
|
+
*
|
|
147
|
+
* Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that
|
|
148
|
+
* caller. Kept out of the package's public exports: it reads a module-level registry, so it is only
|
|
149
|
+
* meaningful after this module's own loaders have run.
|
|
150
|
+
*
|
|
151
|
+
* @internal
|
|
137
152
|
*/
|
|
138
153
|
export function validateReferences() {
|
|
139
154
|
const errors = [];
|
|
140
155
|
for (const doctype of doctypeRegistry.values()) {
|
|
141
156
|
// Check inherits reference
|
|
142
|
-
if (doctype.inherits &&
|
|
157
|
+
if (doctype.inherits && getMeta(doctype.inherits) === undefined) {
|
|
143
158
|
errors.push({
|
|
144
159
|
path: [doctype.name, 'inherits'],
|
|
145
160
|
message: `References unknown doctype: ${doctype.inherits}`,
|
|
@@ -150,7 +165,7 @@ export function validateReferences() {
|
|
|
150
165
|
if (field.kind !== 'field')
|
|
151
166
|
continue;
|
|
152
167
|
const target = field.doctype;
|
|
153
|
-
if (target !== undefined &&
|
|
168
|
+
if (target !== undefined && getMeta(target) === undefined) {
|
|
154
169
|
errors.push({
|
|
155
170
|
path: [doctype.name, 'fields', field.fieldname, 'doctype'],
|
|
156
171
|
message: `Link references unknown doctype: ${target}`,
|
|
@@ -160,7 +175,7 @@ export function validateReferences() {
|
|
|
160
175
|
// Check link-declaration targets (component-primary links live in the `links` map)
|
|
161
176
|
if (doctype.links) {
|
|
162
177
|
for (const [key, link] of Object.entries(doctype.links)) {
|
|
163
|
-
if (
|
|
178
|
+
if (getMeta(link.target) === undefined) {
|
|
164
179
|
errors.push({
|
|
165
180
|
path: [doctype.name, 'links', key, 'target'],
|
|
166
181
|
message: `Link references unknown doctype: ${link.target}`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typeDefs.d.ts","sourceRoot":"","sources":["../../src/typeDefs.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,QAAQ,
|
|
1
|
+
{"version":3,"file":"typeDefs.d.ts","sourceRoot":"","sources":["../../src/typeDefs.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,QAAQ,gCA8FpB,CAAA"}
|
package/dist/src/typeDefs.js
CHANGED
|
@@ -62,7 +62,16 @@ export const typeDefs = gql `
|
|
|
62
62
|
type StonecropRecordsResult {
|
|
63
63
|
data: [JSON!]!
|
|
64
64
|
doctype: String!
|
|
65
|
-
|
|
65
|
+
"""
|
|
66
|
+
Whether further records exist beyond this page. Always answered — it is read from the
|
|
67
|
+
page itself (one extra row is requested and discarded), so it costs no second query.
|
|
68
|
+
"""
|
|
69
|
+
hasMore: Boolean!
|
|
70
|
+
"""
|
|
71
|
+
Total matching the filters, ignoring limit/offset. Null unless the query asked for it
|
|
72
|
+
with includeTotal, because counting is a full scan on most backends.
|
|
73
|
+
"""
|
|
74
|
+
count: Int
|
|
66
75
|
}
|
|
67
76
|
|
|
68
77
|
type StonecropActionResult {
|
|
@@ -81,6 +90,7 @@ export const typeDefs = gql `
|
|
|
81
90
|
orderBy: String
|
|
82
91
|
limit: Int
|
|
83
92
|
offset: Int
|
|
93
|
+
includeTotal: Boolean
|
|
84
94
|
options: JSON
|
|
85
95
|
): StonecropRecordsResult
|
|
86
96
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stonecrop/graphql-middleware",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "GraphQL middleware for PostGraphile and Stonecrop schema",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"graphql": "^16.14.0",
|
|
24
24
|
"pluralize": "^8.0.0",
|
|
25
25
|
"postgraphile": "^5.0.3",
|
|
26
|
-
"@stonecrop/schema": "0.
|
|
26
|
+
"@stonecrop/schema": "0.17.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@electric-sql/pglite": "^0.4.5",
|