@stonecrop/graphql-middleware 0.23.0 → 0.24.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,MA8qB3F,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';
@@ -314,6 +315,10 @@ export const createStonecropPlugin = (options = {}) => {
314
315
  truncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,
315
316
  };
316
317
  }
318
+ // After the expansion loop, not before it: a link that expanded has replaced its
319
+ // scalar FK with an object, and enrichment skips those. Running first stamped a
320
+ // display value beside a relation that no longer had an id to display.
321
+ await enrichLinkDisplayFields(pgClient, meta, enrichedRows, options.tables, debugSql);
317
322
  }
318
323
  return results;
319
324
  });
@@ -404,6 +409,7 @@ export const createStonecropPlugin = (options = {}) => {
404
409
  // downstream can mistake it for a record.
405
410
  const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
406
411
  const data = [...(hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows)];
412
+ await enrichLinkDisplayFields(pgClient, meta, data, options.tables, debugSql);
407
413
  // Total matching the filters, independent of LIMIT/OFFSET, and opt-in.
408
414
  //
409
415
  // 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.24.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.24.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@electric-sql/pglite": "^0.4.5",