@stonecrop/graphql-middleware 0.23.0 → 0.25.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.
@@ -0,0 +1,19 @@
1
+ import type { DoctypeMeta } from '@stonecrop/schema';
2
+ import type { PgClient } from '@dataplan/pg';
3
+ type SqlQueryFn = (pgClient: PgClient, query: {
4
+ text: string;
5
+ values?: unknown[];
6
+ }) => Promise<{
7
+ rows: readonly Record<string, unknown>[];
8
+ }>;
9
+ /**
10
+ * Replace inline link FK scalars with `{ id, displayText }` when the target doctype declares a
11
+ * `displayField`. Expanded relations (object values) are skipped.
12
+ *
13
+ * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch
14
+ * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the
15
+ * loader exists to prevent, and does so invisibly, since the result is identical either way.
16
+ */
17
+ export declare function enrichLinkDisplayFields(pgClient: PgClient, meta: DoctypeMeta, rows: Record<string, unknown>[], tables: Record<string, string> | undefined, debugSql: SqlQueryFn): Promise<void>;
18
+ export {};
19
+ //# sourceMappingURL=link-display.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"link-display.d.ts","sourceRoot":"","sources":["../../src/link-display.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAEpD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAK5C,KAAK,UAAU,GAAG,CACjB,QAAQ,EAAE,QAAQ,EAClB,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAA;CAAE,KACvC,OAAO,CAAC;IAAE,IAAI,EAAE,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;CAAE,CAAC,CAAA;AAqD1D;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAC5C,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,WAAW,EACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAC1C,QAAQ,EAAE,UAAU,GAClB,OAAO,CAAC,IAAI,CAAC,CAyCf"}
@@ -0,0 +1,93 @@
1
+ import { camelToSnake, flattenFields, getDisplayField, getRecordIdField } from '@stonecrop/schema';
2
+ import { getMeta } from './registry/doctypes';
3
+ import { resolveTableName } from './tables';
4
+ /**
5
+ * Normalize a scalar SQL cell value to a non-empty string, or nothing.
6
+ *
7
+ * One rule for the three reads that all need it — the FK a lookup keys on, the target's own key
8
+ * in the result, and the display text stamped into the payload. Rejecting objects is what each
9
+ * of those wants: an object FK is a link that was already expanded, and an object display column
10
+ * is the `[object Object]` a bare `String()` would otherwise write into the payload as though it
11
+ * were the record's name. Falling back to the raw id is visibly unhelpful; that is not.
12
+ */
13
+ function scalarText(value) {
14
+ if (value == null || typeof value === 'object')
15
+ return undefined;
16
+ if (typeof value === 'string')
17
+ return value === '' ? undefined : value;
18
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
19
+ return String(value);
20
+ }
21
+ return undefined;
22
+ }
23
+ function collectLinkDisplaySpecs(meta, tables) {
24
+ const specs = [];
25
+ for (const field of flattenFields(meta.fields)) {
26
+ if (field.kind !== 'field' || !field.doctype)
27
+ continue;
28
+ const targetMeta = getMeta(field.doctype);
29
+ if (!targetMeta)
30
+ continue;
31
+ // `getDisplayField` rather than a lookup written here: it is the same call `DoctypeMeta`
32
+ // makes at the load gate, so a nomination that parsed is one this can build a SELECT from.
33
+ // A hand-rolled scan here admitted `computed` fields, whose column does not exist.
34
+ const displayField = getDisplayField(targetMeta.fields, targetMeta.displayField);
35
+ if (!displayField)
36
+ continue;
37
+ specs.push({
38
+ fieldname: field.fieldname,
39
+ displayField: displayField.fieldname,
40
+ targetPkFieldname: getRecordIdField(targetMeta.fields),
41
+ targetTable: resolveTableName(targetMeta.name, tables),
42
+ });
43
+ }
44
+ return specs;
45
+ }
46
+ /**
47
+ * Replace inline link FK scalars with `{ id, displayText }` when the target doctype declares a
48
+ * `displayField`. Expanded relations (object values) are skipped.
49
+ *
50
+ * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch
51
+ * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the
52
+ * loader exists to prevent, and does so invisibly, since the result is identical either way.
53
+ */
54
+ export async function enrichLinkDisplayFields(pgClient, meta, rows, tables, debugSql) {
55
+ const specs = collectLinkDisplaySpecs(meta, tables);
56
+ if (specs.length === 0 || rows.length === 0)
57
+ return;
58
+ await Promise.all(specs.map(async (spec) => {
59
+ const ids = new Set();
60
+ for (const row of rows) {
61
+ const id = scalarText(row[spec.fieldname]);
62
+ if (id !== undefined)
63
+ ids.add(id);
64
+ }
65
+ if (ids.size === 0)
66
+ return;
67
+ const pkColumn = camelToSnake(spec.targetPkFieldname);
68
+ const displayColumn = camelToSnake(spec.displayField);
69
+ const displayAlias = displayColumn !== spec.displayField ? `"${displayColumn}" AS "${spec.displayField}"` : `"${spec.displayField}"`;
70
+ const { rows: displayRows } = await debugSql(pgClient, {
71
+ text: `SELECT "${pkColumn}" AS "${spec.targetPkFieldname}", ${displayAlias} FROM ${spec.targetTable} WHERE "${pkColumn}"::text = ANY($1::text[])`,
72
+ values: [Array.from(ids)],
73
+ });
74
+ const displayById = new Map();
75
+ for (const displayRow of displayRows) {
76
+ const key = scalarText(displayRow[spec.targetPkFieldname]);
77
+ const text = scalarText(displayRow[spec.displayField]);
78
+ if (key === undefined || text === undefined)
79
+ continue;
80
+ displayById.set(key, text);
81
+ }
82
+ for (const row of rows) {
83
+ const rawId = row[spec.fieldname];
84
+ const idKey = scalarText(rawId);
85
+ if (idKey === undefined)
86
+ continue;
87
+ const displayText = displayById.get(idKey);
88
+ if (displayText === undefined)
89
+ continue;
90
+ row[spec.fieldname] = { id: rawId, displayText };
91
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KG;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,MAwsB3F,CAAA;AA0BD;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,CAQvD;AA6HD;;;;;GAKG"}
@@ -3,6 +3,7 @@ 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 { columnBackedFields, flattenFields } from '../fields';
6
+ import { enrichLinkDisplayFields } from '../link-display';
6
7
  import { resolveTableName } from '../tables';
7
8
  import { getFetchHandler } from '../registry/fetchHandlers';
8
9
  import { getMeta, getAllMeta, validateReferences } from '../registry/doctypes';
@@ -249,6 +250,15 @@ export const createStonecropPlugin = (options = {}) => {
249
250
  const backlinkCol = camelToSnake(link.backlink);
250
251
  let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
251
252
  const linkValues = [specId];
253
+ // Same reason the list path orders: a capped relation without a fixed order
254
+ // returns an arbitrary subset of the children, and a different one each time
255
+ // a child row is updated. `truncatedLinks` says the tail was cut; it cannot
256
+ // say the head kept changing. Skipped when the target declares no identity —
257
+ // there is no stable key to order by, and inventing one would be a guess.
258
+ const linkPkMeta = getPkMeta(targetMeta);
259
+ if (linkPkMeta) {
260
+ sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
261
+ }
252
262
  if (effectiveLimit != null) {
253
263
  // One row more than the cap, same probe the list path uses: its presence
254
264
  // is the whole truncation answer and costs no second query.
@@ -314,6 +324,10 @@ export const createStonecropPlugin = (options = {}) => {
314
324
  truncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,
315
325
  };
316
326
  }
327
+ // After the expansion loop, not before it: a link that expanded has replaced its
328
+ // scalar FK with an object, and enrichment skips those. Running first stamped a
329
+ // display value beside a relation that no longer had an id to display.
330
+ await enrichLinkDisplayFields(pgClient, meta, enrichedRows, options.tables, debugSql);
317
331
  }
318
332
  return results;
319
333
  });
@@ -373,6 +387,22 @@ export const createStonecropPlugin = (options = {}) => {
373
387
  }
374
388
  orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
375
389
  }
390
+ // A page is only meaningful against a fixed order, and LIMIT/OFFSET without one
391
+ // is two independent scans of heap order — an UPDATE between them moves that row
392
+ // to the tail, so the row it displaced is never returned and nothing in the
393
+ // payload says a record was skipped. The declared identity is the right default
394
+ // because it is unique: it gives a total order, which is what makes page 2 start
395
+ // exactly where page 1 stopped.
396
+ //
397
+ // Only when the doctype declares an identity. Without one there is no stable key
398
+ // to order by, and inventing one here would be a guess; such a doctype cannot be
399
+ // paged stably by any means.
400
+ if (orderByClause === '') {
401
+ const listPkMeta = getPkMeta(meta);
402
+ if (listPkMeta) {
403
+ orderByClause = ` ORDER BY "${camelToSnake(listPkMeta.fieldname)}" ASC`;
404
+ }
405
+ }
376
406
  // LIMIT / OFFSET. A caller that names no limit gets the configured default rather
377
407
  // than the whole table: omission is how an unbounded scan used to happen, and the
378
408
  // only guard against it lived in the scaffold's fetch helper, which is neither the
@@ -404,6 +434,7 @@ export const createStonecropPlugin = (options = {}) => {
404
434
  // downstream can mistake it for a record.
405
435
  const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
406
436
  const data = [...(hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows)];
437
+ await enrichLinkDisplayFields(pgClient, meta, data, options.tables, debugSql);
407
438
  // Total matching the filters, independent of LIMIT/OFFSET, and opt-in.
408
439
  //
409
440
  // Explicitly requested rather than inferred from whether `count` was selected:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stonecrop/graphql-middleware",
3
- "version": "0.23.0",
3
+ "version": "0.25.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.23.0"
26
+ "@stonecrop/schema": "0.25.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@electric-sql/pglite": "^0.4.5",