@stonecrop/graphql-middleware 0.17.0 → 0.19.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,28 @@
1
+ import { flattenFields } from '@stonecrop/schema';
2
+ // Re-exported so this module stays the one place the adapter asks about a doctype's fields, while
3
+ // the definition itself lives in `@stonecrop/schema`. It moved there because `DoctypeMeta`'s own
4
+ // validation needs the same descent, and the copy it had written instead scanned top level only —
5
+ // so the load gate and the read path disagreed about what a doctype declares, which is exactly
6
+ // what keeping one definition is for.
7
+ export { flattenFields };
8
+ /**
9
+ * The fields that have a database column of their own — the one definition of that question.
10
+ *
11
+ * Two properties disqualify a field, and both are the field saying so itself: a `computed` field is
12
+ * declared precisely to state it has no column, and a container (a table field) is a relation
13
+ * rather than a value. Everything else names a column.
14
+ *
15
+ * This is deliberately **not** the same question as "does this column belong in a record payload".
16
+ * An *expanding* link's foreign key has a real column that this returns, while `collectColumns`
17
+ * omits it from the SELECT on purpose because the relation is fetched separately. Conflating the
18
+ * two is how the read path came to drop the very column its expansion needed. Callers wanting the
19
+ * payload projection filter this further by render mode; callers asking whether a column exists —
20
+ * link validation, and the write path deciding what it may set — want it unfiltered.
21
+ *
22
+ * Extracted because the rule had grown three statements across two modules, one of them a comment
23
+ * reading "mirrors `collectColumns`". A rule that has to be mirrored by hand is one edit away from
24
+ * the read path and the validator disagreeing about what a doctype declares.
25
+ */
26
+ export function columnBackedFields(fields) {
27
+ return flattenFields(fields).filter((f) => f.kind === 'field' && !f.computed);
28
+ }
@@ -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
+ * Add `fieldname__display` alongside each inline foreign-key field when the target doctype
11
+ * declares a `displayField`. Scalar FK values only — expanded relations 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;AA6C1D;;;;;;;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,CAqCf"}
@@ -0,0 +1,80 @@
1
+ import { camelToSnake, flattenFields, getDisplayField, getRecordIdField, linkDisplayFieldname } from '@stonecrop/schema';
2
+ import { getMeta } from './registry/doctypes';
3
+ import { resolveTableName } from './tables';
4
+ /** Normalize a scalar FK cell value to a non-empty string id, or skip objects/null. */
5
+ function fkIdKey(value) {
6
+ if (value == null || typeof value === 'object')
7
+ return undefined;
8
+ if (typeof value === 'string')
9
+ return value === '' ? undefined : value;
10
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
11
+ return String(value);
12
+ }
13
+ return undefined;
14
+ }
15
+ function collectLinkDisplaySpecs(meta, tables) {
16
+ const specs = [];
17
+ for (const field of flattenFields(meta.fields)) {
18
+ if (field.kind !== 'field' || !field.doctype)
19
+ continue;
20
+ const targetMeta = getMeta(field.doctype);
21
+ if (!targetMeta)
22
+ continue;
23
+ // `getDisplayField` rather than a lookup written here: it is the same call `DoctypeMeta`
24
+ // makes at the load gate, so a nomination that parsed is one this can build a SELECT from.
25
+ // A hand-rolled scan here admitted `computed` fields, whose column does not exist.
26
+ const displayField = getDisplayField(targetMeta.fields, targetMeta.displayField);
27
+ if (!displayField)
28
+ continue;
29
+ specs.push({
30
+ fieldname: field.fieldname,
31
+ displayField: displayField.fieldname,
32
+ targetPkFieldname: getRecordIdField(targetMeta.fields),
33
+ targetTable: resolveTableName(targetMeta.name, tables),
34
+ });
35
+ }
36
+ return specs;
37
+ }
38
+ /**
39
+ * Add `fieldname__display` alongside each inline foreign-key field when the target doctype
40
+ * declares a `displayField`. Scalar FK values only — expanded relations are skipped.
41
+ *
42
+ * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch
43
+ * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the
44
+ * loader exists to prevent, and does so invisibly, since the result is identical either way.
45
+ */
46
+ export async function enrichLinkDisplayFields(pgClient, meta, rows, tables, debugSql) {
47
+ const specs = collectLinkDisplaySpecs(meta, tables);
48
+ if (specs.length === 0 || rows.length === 0)
49
+ return;
50
+ await Promise.all(specs.map(async (spec) => {
51
+ const ids = new Set();
52
+ for (const row of rows) {
53
+ const id = fkIdKey(row[spec.fieldname]);
54
+ if (id !== undefined)
55
+ ids.add(id);
56
+ }
57
+ if (ids.size === 0)
58
+ return;
59
+ const pkColumn = camelToSnake(spec.targetPkFieldname);
60
+ const displayColumn = camelToSnake(spec.displayField);
61
+ const displayAlias = displayColumn !== spec.displayField ? `"${displayColumn}" AS "${spec.displayField}"` : `"${spec.displayField}"`;
62
+ const { rows: displayRows } = await debugSql(pgClient, {
63
+ text: `SELECT "${pkColumn}" AS "${spec.targetPkFieldname}", ${displayAlias} FROM ${spec.targetTable} WHERE "${pkColumn}"::text = ANY($1::text[])`,
64
+ values: [Array.from(ids)],
65
+ });
66
+ const displayById = new Map();
67
+ for (const displayRow of displayRows) {
68
+ displayById.set(String(displayRow[spec.targetPkFieldname]), displayRow[spec.displayField]);
69
+ }
70
+ for (const row of rows) {
71
+ const id = fkIdKey(row[spec.fieldname]);
72
+ if (id === undefined)
73
+ continue;
74
+ const displayValue = displayById.get(id);
75
+ if (displayValue == null || displayValue === '')
76
+ continue;
77
+ row[linkDisplayFieldname(spec.fieldname)] = displayValue;
78
+ }
79
+ }));
80
+ }
@@ -118,18 +118,26 @@ export interface StonecropPluginOptions {
118
118
  */
119
119
  actionHandlers?: Record<string, Record<string, ActionHandler>>;
120
120
  /**
121
- * Row cap applied to `stonecropRecords` when the caller requests no `limit`. Defaults to 200.
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.
122
124
  *
123
125
  * A row cap is a statement about what this database can afford to serve, so it belongs to
124
126
  * whoever owns the database — not to a doctype (which describes the API surface, not the
125
127
  * table) and not to a page (which cannot know the size of an arbitrary table). Callers stay
126
128
  * free to ask for less; they cannot ask for an unbounded scan by omission.
127
129
  *
128
- * `hasMore` reports whether the cap truncated the result, so a capped page is always
129
- * distinguishable from a complete one without asking for a count.
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.
130
133
  *
131
- * Set to `null` for no default cap. That is the pre-0.17 behaviour and it means an unqualified
132
- * list query returns the whole table.
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.
133
141
  */
134
142
  defaultRecordLimit?: number | null;
135
143
  }
@@ -155,4 +163,10 @@ export declare const createStonecropPlugin: (options?: StonecropPluginOptions) =
155
163
  * Exported for unit testing (not re-exported from the package index).
156
164
  */
157
165
  export declare function getSqlColumns(meta: DoctypeMeta): string;
166
+ /**
167
+ * Resolve the PostgreSQL FROM clause target for a doctype.
168
+ * Uses the `tables` override map first; falls back to camelToSnake(name).
169
+ * Schema-qualified names (e.g. "orpin.plan") are emitted as "schema"."table".
170
+ * Values must be bare identifiers or schema.table pairs — not SQL fragments.
171
+ */
158
172
  //# sourceMappingURL=postgraphile.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgraphile.d.ts","sourceRoot":"","sources":["../../../src/plugin/postgraphile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEX,WAAW,EAKX,MAAM,mBAAmB,CAAA;AAG1B,OAAO,KAAK,EAAE,QAAQ,EAAc,MAAM,cAAc,CAAA;AAExD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAQ5D;;;;;;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,MAA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