@stonecrop/graphql-middleware 0.12.7 → 0.13.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 +103 -63
- package/dist/graphql-middleware.d.ts +111 -246
- package/dist/index.js +352 -408
- package/dist/index.js.map +1 -1
- package/dist/plugin/postgraphile.js +583 -0
- package/dist/preset.js +45 -0
- package/dist/registry/actions.js +163 -0
- package/dist/registry/doctypes.js +161 -0
- package/dist/src/debug.d.ts +31 -0
- package/dist/src/debug.d.ts.map +1 -0
- package/dist/src/debug.js +49 -0
- package/dist/src/index.d.ts +9 -4
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +7 -2
- package/dist/src/plugin/postgraphile.d.ts +15 -171
- package/dist/src/plugin/postgraphile.d.ts.map +1 -1
- package/dist/src/plugin/postgraphile.js +253 -455
- package/dist/src/preset.d.ts +53 -0
- package/dist/src/preset.d.ts.map +1 -0
- package/dist/src/preset.js +54 -0
- package/dist/src/registry/fetchHandlers.d.ts +31 -0
- package/dist/src/registry/fetchHandlers.d.ts.map +1 -0
- package/dist/src/registry/fetchHandlers.js +24 -0
- package/dist/src/types/context.d.ts +20 -0
- package/dist/src/types/context.d.ts.map +1 -0
- package/dist/src/types/index.d.ts +4 -14
- package/dist/src/types/index.d.ts.map +1 -1
- package/dist/src/types/preset.d.ts +18 -0
- package/dist/src/types/preset.d.ts.map +1 -0
- package/dist/typeDefs.js +79 -0
- package/dist/types/context.js +0 -0
- package/dist/types/index.js +3 -0
- package/dist/types/preset.js +0 -0
- package/dist/types/query.js +3 -0
- package/package.json +7 -2
|
@@ -1,25 +1,41 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { constant, lambda, object
|
|
1
|
+
import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
|
|
2
|
+
import { constant, lambda, object } from 'postgraphile/grafast';
|
|
3
3
|
import { extendSchema } from 'postgraphile/utils';
|
|
4
|
-
import pluralize from 'pluralize';
|
|
5
4
|
import { getHandler } from '../registry/actions';
|
|
5
|
+
import { getFetchHandler } from '../registry/fetchHandlers';
|
|
6
6
|
import { getMeta, getAllMeta } from '../registry/doctypes';
|
|
7
7
|
import { typeDefs } from '../typeDefs';
|
|
8
8
|
/**
|
|
9
|
-
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality
|
|
10
|
-
*
|
|
9
|
+
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
|
|
10
|
+
*
|
|
11
|
+
* The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`
|
|
12
|
+
* during schema construction — it does not need to be supplied by the caller.
|
|
13
|
+
*
|
|
14
|
+
* @param options - Optional plugin configuration
|
|
11
15
|
* @returns A PostGraphile plugin
|
|
12
16
|
* @public
|
|
13
17
|
*/
|
|
14
|
-
export const createStonecropPlugin = (options) => {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
|
|
18
|
+
export const createStonecropPlugin = (options = {}) => {
|
|
19
|
+
const pkField = options.pkField ?? 'id';
|
|
20
|
+
/**
|
|
21
|
+
* SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging
|
|
22
|
+
* for queries that run inside custom loadOneWithPgClient callbacks, which
|
|
23
|
+
* bypass the executor's native instrumentation.
|
|
24
|
+
*/
|
|
25
|
+
const debugSql = options.debug
|
|
26
|
+
? (pgClient, query) => {
|
|
27
|
+
// eslint-disable-next-line no-console
|
|
28
|
+
console.log(`[@stonecrop/graphql-middleware] ${query.text}`, query.values ?? []);
|
|
29
|
+
return pgClient.query(query);
|
|
30
|
+
}
|
|
31
|
+
: (pgClient, query) => pgClient.query(query);
|
|
32
|
+
return extendSchema(build => {
|
|
33
|
+
// Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.
|
|
34
|
+
const pgExecutors = build.input?.pgRegistry?.pgExecutors;
|
|
35
|
+
const executor = pgExecutors ? Object.values(pgExecutors)[0] : undefined;
|
|
36
|
+
if (!executor) {
|
|
37
|
+
throw new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured');
|
|
38
|
+
}
|
|
23
39
|
return {
|
|
24
40
|
typeDefs,
|
|
25
41
|
objects: {
|
|
@@ -35,78 +51,192 @@ export const createStonecropPlugin = (options) => {
|
|
|
35
51
|
return constant(getAllMeta());
|
|
36
52
|
},
|
|
37
53
|
stonecropRecord(_, { $doctype, $id, $options }) {
|
|
38
|
-
return
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
54
|
+
return loadOneWithPgClient(executor, object({ doctype: $doctype, id: $id, options: $options }), async (pgClient, specs) => {
|
|
55
|
+
// Group specs by doctype to batch the main SELECT per table
|
|
56
|
+
const byDoctype = new Map();
|
|
57
|
+
for (let i = 0; i < specs.length; i++) {
|
|
58
|
+
const d = specs[i].doctype;
|
|
59
|
+
if (!byDoctype.has(d))
|
|
60
|
+
byDoctype.set(d, []);
|
|
61
|
+
byDoctype.get(d).push(i);
|
|
62
|
+
}
|
|
63
|
+
const results = new Array(specs.length);
|
|
64
|
+
for (const [doctype, indices] of byDoctype) {
|
|
65
|
+
const meta = getMeta(doctype);
|
|
66
|
+
if (!meta?.tableName) {
|
|
67
|
+
for (const i of indices)
|
|
68
|
+
results[i] = { data: null, doctype };
|
|
69
|
+
continue;
|
|
43
70
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
? {
|
|
50
|
-
includeNested: recordOptions.includeNested,
|
|
51
|
-
maxDepth: recordOptions.maxDepth,
|
|
52
|
-
}
|
|
53
|
-
: undefined, reverseConnectionName);
|
|
54
|
-
const result = await options.executor.query(query, {
|
|
55
|
-
[recordArgName(meta.tableName)]: spec.id,
|
|
71
|
+
const columns = getSqlColumns(meta, pkField);
|
|
72
|
+
const ids = indices.map(i => specs[i].id);
|
|
73
|
+
const { rows } = await debugSql(pgClient, {
|
|
74
|
+
text: `SELECT ${columns} FROM "${meta.tableName}" WHERE "${pkField}"::text = ANY($1::text[])`,
|
|
75
|
+
values: [ids],
|
|
56
76
|
});
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
77
|
+
// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
|
|
78
|
+
const rowByPk = new Map(rows.map(r => [String(r[pkField]), r]));
|
|
79
|
+
for (const i of indices) {
|
|
80
|
+
const specId = specs[i].id;
|
|
81
|
+
const row = rowByPk.get(specId);
|
|
82
|
+
if (!row) {
|
|
83
|
+
results[i] = { data: null, doctype };
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const rowData = { ...row };
|
|
87
|
+
const recordOptions = (specs[i].options ?? {});
|
|
88
|
+
const includeAll = recordOptions.includeNested === true;
|
|
89
|
+
const includeSet = Array.isArray(recordOptions.includeNested)
|
|
90
|
+
? new Set(recordOptions.includeNested)
|
|
91
|
+
: null;
|
|
92
|
+
// FetchStrategy dispatch over link declarations
|
|
93
|
+
if (meta.links) {
|
|
94
|
+
for (const [linkName, link] of Object.entries(meta.links)) {
|
|
95
|
+
const fetch = link.fetch;
|
|
96
|
+
const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
|
|
97
|
+
const effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy');
|
|
98
|
+
const effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined;
|
|
99
|
+
const shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync');
|
|
100
|
+
if (!shouldInclude)
|
|
101
|
+
continue;
|
|
102
|
+
if (effectiveMethod === 'custom') {
|
|
103
|
+
const handlerName = fetch.handler;
|
|
104
|
+
const handler = getFetchHandler(handlerName);
|
|
105
|
+
if (handler) {
|
|
106
|
+
rowData[linkName] = await handler(pgClient, rowData, link);
|
|
107
|
+
}
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (effectiveMethod !== 'sync' && !includeSet?.has(linkName))
|
|
111
|
+
continue;
|
|
112
|
+
const targetMeta = getMeta(link.target);
|
|
113
|
+
if (!targetMeta?.tableName)
|
|
114
|
+
continue;
|
|
115
|
+
const targetColumns = getSqlColumns(targetMeta, pkField);
|
|
116
|
+
if (isMany) {
|
|
117
|
+
if (!link.backlink)
|
|
118
|
+
continue;
|
|
119
|
+
let sql = `SELECT ${targetColumns} FROM "${targetMeta.tableName}" WHERE "${link.backlink}"::text = $1`;
|
|
120
|
+
const linkValues = [specId];
|
|
121
|
+
if (effectiveLimit != null) {
|
|
122
|
+
sql += ` LIMIT $2`;
|
|
123
|
+
linkValues.push(effectiveLimit);
|
|
124
|
+
}
|
|
125
|
+
const { rows: linked } = await debugSql(pgClient, {
|
|
126
|
+
text: sql,
|
|
127
|
+
values: linkValues,
|
|
128
|
+
});
|
|
129
|
+
rowData[linkName] = linked;
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
if (!link.fieldname)
|
|
133
|
+
continue;
|
|
134
|
+
const fkValue = rowData[link.fieldname];
|
|
135
|
+
if (fkValue == null) {
|
|
136
|
+
rowData[linkName] = null;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const { rows: linked } = await debugSql(pgClient, {
|
|
140
|
+
text: `SELECT ${targetColumns} FROM "${targetMeta.tableName}" WHERE "${pkField}" = $1`,
|
|
141
|
+
values: [fkValue],
|
|
142
|
+
});
|
|
143
|
+
rowData[linkName] = linked[0] ?? null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
// Names in includeNested that don't correspond to any link
|
|
148
|
+
const unknownLinks = includeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links)) : undefined;
|
|
149
|
+
results[i] = {
|
|
150
|
+
data: rowData,
|
|
151
|
+
doctype,
|
|
152
|
+
unknownLinks: unknownLinks?.length ? unknownLinks : undefined,
|
|
153
|
+
};
|
|
65
154
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
: undefined;
|
|
69
|
-
return {
|
|
70
|
-
data,
|
|
71
|
-
doctype: spec.doctype,
|
|
72
|
-
...(unknownLinks ? { unknownLinks } : {}),
|
|
73
|
-
};
|
|
74
|
-
}));
|
|
155
|
+
}
|
|
156
|
+
return results;
|
|
75
157
|
});
|
|
76
158
|
},
|
|
77
|
-
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset
|
|
78
|
-
return
|
|
159
|
+
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset }) {
|
|
160
|
+
return loadOneWithPgClient(executor, object({
|
|
79
161
|
doctype: $doctype,
|
|
80
162
|
filters: $filters,
|
|
81
163
|
orderBy: $orderBy,
|
|
82
164
|
limit: $limit,
|
|
83
165
|
offset: $offset,
|
|
84
|
-
|
|
85
|
-
}), async (specs) => {
|
|
166
|
+
}), async (pgClient, specs) => {
|
|
86
167
|
return await Promise.all(specs.map(async (spec) => {
|
|
87
168
|
const meta = getMeta(spec.doctype);
|
|
88
|
-
if (!meta) {
|
|
89
|
-
|
|
169
|
+
if (!meta?.tableName) {
|
|
170
|
+
return { data: [], doctype: spec.doctype, count: 0 };
|
|
171
|
+
}
|
|
172
|
+
const knownFields = new Set(meta.fields.map(f => f.fieldname));
|
|
173
|
+
const columns = getSqlColumns(meta, pkField);
|
|
174
|
+
const values = [];
|
|
175
|
+
// WHERE from filters (parameterised — safe against SQL injection)
|
|
176
|
+
const whereClauses = [];
|
|
177
|
+
if (spec.filters != null) {
|
|
178
|
+
for (const [field, value] of Object.entries(spec.filters)) {
|
|
179
|
+
if (!knownFields.has(field)) {
|
|
180
|
+
throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
|
|
181
|
+
}
|
|
182
|
+
values.push(value);
|
|
183
|
+
whereClauses.push(`"${field}" = $${values.length}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
|
|
187
|
+
// ORDER BY (field name whitelisted — column names cannot be parameterised)
|
|
188
|
+
let orderByClause = '';
|
|
189
|
+
if (spec.orderBy != null) {
|
|
190
|
+
const orderByStr = spec.orderBy;
|
|
191
|
+
const lastUnder = orderByStr.lastIndexOf('_');
|
|
192
|
+
if (lastUnder <= 0) {
|
|
193
|
+
throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
|
|
194
|
+
}
|
|
195
|
+
const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
|
|
196
|
+
if (dir !== 'ASC' && dir !== 'DESC') {
|
|
197
|
+
throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
|
|
198
|
+
}
|
|
199
|
+
const fieldName = orderByStr.slice(0, lastUnder);
|
|
200
|
+
if (!knownFields.has(fieldName)) {
|
|
201
|
+
throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
|
|
202
|
+
}
|
|
203
|
+
orderByClause = ` ORDER BY "${fieldName}" ${dir}`;
|
|
204
|
+
}
|
|
205
|
+
// LIMIT / OFFSET
|
|
206
|
+
let pagingClause = '';
|
|
207
|
+
if (spec.limit != null) {
|
|
208
|
+
values.push(spec.limit);
|
|
209
|
+
pagingClause += ` LIMIT $${values.length}`;
|
|
90
210
|
}
|
|
91
|
-
if (
|
|
92
|
-
|
|
211
|
+
if (spec.offset != null) {
|
|
212
|
+
values.push(spec.offset);
|
|
213
|
+
pagingClause += ` OFFSET $${values.length}`;
|
|
93
214
|
}
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
orderBy: spec.orderBy,
|
|
98
|
-
}, connectionFieldName, orderByTypeName);
|
|
99
|
-
const result = await options.executor.query(query, {
|
|
100
|
-
limit: spec.limit,
|
|
101
|
-
offset: spec.offset,
|
|
102
|
-
orderBy: spec.orderBy,
|
|
215
|
+
const { rows } = await debugSql(pgClient, {
|
|
216
|
+
text: `SELECT ${columns} FROM "${meta.tableName}"${whereClause}${orderByClause}${pagingClause}`,
|
|
217
|
+
values,
|
|
103
218
|
});
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
219
|
+
// Total count matching filters (independent of LIMIT/OFFSET)
|
|
220
|
+
let count = rows.length;
|
|
221
|
+
if (spec.limit != null || spec.offset != null) {
|
|
222
|
+
const countValues = [];
|
|
223
|
+
const countWhere = [];
|
|
224
|
+
if (spec.filters != null) {
|
|
225
|
+
for (const [field, value] of Object.entries(spec.filters)) {
|
|
226
|
+
if (!knownFields.has(field))
|
|
227
|
+
continue;
|
|
228
|
+
countValues.push(value);
|
|
229
|
+
countWhere.push(`"${field}" = $${countValues.length}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : '';
|
|
233
|
+
const { rows: countRows } = await debugSql(pgClient, {
|
|
234
|
+
text: `SELECT COUNT(*) AS __count FROM "${meta.tableName}"${countWhereClause}`,
|
|
235
|
+
values: countValues,
|
|
236
|
+
});
|
|
237
|
+
count = parseInt(countRows[0]?.__count ?? '0', 10);
|
|
238
|
+
}
|
|
239
|
+
return { data: rows, doctype: spec.doctype, count };
|
|
110
240
|
}));
|
|
111
241
|
});
|
|
112
242
|
},
|
|
@@ -115,57 +245,43 @@ export const createStonecropPlugin = (options) => {
|
|
|
115
245
|
Mutation: {
|
|
116
246
|
plans: {
|
|
117
247
|
stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
|
|
118
|
-
return
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
if (!meta) {
|
|
126
|
-
return {
|
|
127
|
-
success: false,
|
|
128
|
-
data: null,
|
|
129
|
-
error: `Unknown doctype: ${spec.doctype}`,
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
const actionDef = meta.workflow?.actions?.[spec.action];
|
|
133
|
-
if (!actionDef) {
|
|
134
|
-
return {
|
|
135
|
-
success: false,
|
|
136
|
-
data: null,
|
|
137
|
-
error: `Unknown action: ${spec.action} on ${spec.doctype}`,
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
const handlerName = actionDef.handler;
|
|
141
|
-
const handler = getHandler(handlerName);
|
|
142
|
-
if (!handler) {
|
|
143
|
-
return {
|
|
144
|
-
success: false,
|
|
145
|
-
data: null,
|
|
146
|
-
error: `Handler not registered: ${handlerName}`,
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
const actionContext = {
|
|
150
|
-
doctype: meta,
|
|
151
|
-
executor: options.executor,
|
|
248
|
+
return sideEffectWithPgClient(executor, object({ doctype: $doctype, action: $action, actionArgs: $actionArgs }), async (pgClient, spec) => {
|
|
249
|
+
const meta = getMeta(spec.doctype);
|
|
250
|
+
if (!meta) {
|
|
251
|
+
return {
|
|
252
|
+
success: false,
|
|
253
|
+
data: null,
|
|
254
|
+
error: `Unknown doctype: ${spec.doctype}`,
|
|
152
255
|
};
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
256
|
+
}
|
|
257
|
+
const actionDef = meta.workflow?.actions?.[spec.action];
|
|
258
|
+
if (!actionDef) {
|
|
259
|
+
return {
|
|
260
|
+
success: false,
|
|
261
|
+
data: null,
|
|
262
|
+
error: `Unknown action: ${spec.action} on ${spec.doctype}`,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
const handler = getHandler(actionDef.handler);
|
|
266
|
+
if (!handler) {
|
|
267
|
+
return {
|
|
268
|
+
success: false,
|
|
269
|
+
data: null,
|
|
270
|
+
error: `Handler not registered: ${actionDef.handler}`,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
const actionContext = { doctype: meta, pgClient };
|
|
274
|
+
try {
|
|
275
|
+
const result = await handler(spec.actionArgs ?? [], actionContext);
|
|
276
|
+
return { success: true, data: result, error: null };
|
|
277
|
+
}
|
|
278
|
+
catch (err) {
|
|
279
|
+
return {
|
|
280
|
+
success: false,
|
|
281
|
+
data: null,
|
|
282
|
+
error: err instanceof Error ? err.message : String(err),
|
|
283
|
+
};
|
|
284
|
+
}
|
|
169
285
|
});
|
|
170
286
|
},
|
|
171
287
|
},
|
|
@@ -174,351 +290,33 @@ export const createStonecropPlugin = (options) => {
|
|
|
174
290
|
};
|
|
175
291
|
});
|
|
176
292
|
};
|
|
177
|
-
//
|
|
178
|
-
//
|
|
179
|
-
//
|
|
180
|
-
// plurals like statuses→status, categories→category, addresses→address).
|
|
181
|
-
// snakeToCamel / toPascalCase are imported from @stonecrop/schema.
|
|
182
|
-
// =============================================================================
|
|
183
|
-
/**
|
|
184
|
-
* Amber default: sales_orders → salesOrderById
|
|
185
|
-
* Uses `pluralize` for proper singularization of irregular plurals.
|
|
186
|
-
* Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.
|
|
187
|
-
* @public
|
|
188
|
-
*/
|
|
189
|
-
function defaultRecordFieldName(tableName) {
|
|
190
|
-
const singular = pluralize.singular(tableName);
|
|
191
|
-
return `${snakeToCamel(singular)}ById`;
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Amber default: sales_orders → allSalesOrders
|
|
195
|
-
* @public
|
|
196
|
-
*/
|
|
197
|
-
function defaultConnectionFieldName(tableName) {
|
|
198
|
-
return `all${toPascalCase(tableName)}`;
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Amber default: sales_orders → SalesOrdersOrderBy
|
|
202
|
-
* @public
|
|
203
|
-
*/
|
|
204
|
-
function defaultOrderByTypeName(tableName) {
|
|
205
|
-
return `${toPascalCase(tableName)}OrderBy`;
|
|
206
|
-
}
|
|
207
|
-
/**
|
|
208
|
-
* Default PK argument name: 'id' (standard Relay Global ID pattern).
|
|
209
|
-
* Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;
|
|
210
|
-
* PostGraphile Amber generates `rowId: UUID!` for those fields.
|
|
211
|
-
* @public
|
|
212
|
-
*/
|
|
213
|
-
function defaultRecordArgName(_tableName) {
|
|
214
|
-
return 'id';
|
|
215
|
-
}
|
|
293
|
+
// ===========================================================================
|
|
294
|
+
// SQL column helper — produces a quoted comma-separated column list for SELECT
|
|
295
|
+
// ===========================================================================
|
|
216
296
|
/**
|
|
217
|
-
*
|
|
218
|
-
* Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs
|
|
219
|
-
* such as integer serials or Relay Global IDs ('ID!').
|
|
220
|
-
* @public
|
|
221
|
-
*/
|
|
222
|
-
function defaultRecordArgType(_tableName) {
|
|
223
|
-
return 'UUID!';
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Default reverse connection name: derives PostGraphile's connection field convention.
|
|
227
|
-
* PostGraphile convention: `{targetPlural}By{FkColumnPascal}Id`
|
|
228
|
-
* - When backlink is defined: FK column is derived from the backlink field name
|
|
229
|
-
* - When backlink is absent: FK column is derived from the parent doctype's table name
|
|
230
|
-
* @public
|
|
231
|
-
*/
|
|
232
|
-
function defaultReverseConnectionName(params) {
|
|
233
|
-
const targetPlural = pluralize.plural(params.target.replace(/-/g, '_'));
|
|
234
|
-
// Use camelCase for target (matches PostGraphile Amber convention: recipeTasksByRecipeId)
|
|
235
|
-
const targetCamel = snakeToCamel(targetPlural);
|
|
236
|
-
// Use backlink if provided, otherwise derive from parent table name
|
|
237
|
-
const fkSource = params.backlink || params.doctype;
|
|
238
|
-
// FK column name: uppercase first char, preserve rest of camelCase
|
|
239
|
-
const fkPascal = fkSource.charAt(0).toUpperCase() + snakeToCamel(fkSource).slice(1);
|
|
240
|
-
return `${targetCamel}By${fkPascal}Id`;
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* Check if a cardinality represents a "many" relationship
|
|
244
|
-
*/
|
|
245
|
-
function isManyCardinality(cardinality) {
|
|
246
|
-
return cardinality === 'noneOrMany' || cardinality === 'atLeastOne';
|
|
247
|
-
}
|
|
248
|
-
// =============================================================================
|
|
249
|
-
// Query builders — generate GraphQL queries to send to the underlying schema
|
|
250
|
-
// =============================================================================
|
|
251
|
-
const DEFAULT_SYNC_LIMIT = 50;
|
|
252
|
-
/**
|
|
253
|
-
* Fieldtypes unconditionally excluded from the generated scalar query selection set.
|
|
254
|
-
* - `'Display'`: display-only composite component with no backing DB column
|
|
255
|
-
*
|
|
256
|
-
* Note: `'Link'` fields are NOT blanket-excluded here. Scalar FK UUID columns use
|
|
257
|
-
* `fieldtype: 'Link'` and ARE queryable. Only Link fields that also appear in the
|
|
258
|
-
* doctype's `links` declaration (i.e. those that resolve to a sub-object or connection)
|
|
259
|
-
* are excluded — that logic lives in `queryableFieldNames`.
|
|
260
|
-
* @public
|
|
261
|
-
*/
|
|
262
|
-
const RELATION_FIELDTYPES = new Set(['Display']);
|
|
263
|
-
/**
|
|
264
|
-
* Filter fields to only those directly queryable as scalars.
|
|
297
|
+
* Derive a quoted SQL column list from doctype field definitions.
|
|
265
298
|
* Excludes Display fields (no backing DB column) and Link fields that have an
|
|
266
|
-
* explicit `links` declaration (those
|
|
267
|
-
*
|
|
268
|
-
* @public
|
|
299
|
+
* explicit `links` declaration (those are FK references, not scalar columns).
|
|
300
|
+
* Always prepends the PK column when it is not already listed in `meta.fields`.
|
|
269
301
|
*/
|
|
270
|
-
function
|
|
302
|
+
function getSqlColumns(meta, pkField) {
|
|
271
303
|
const linkedFieldnames = new Set();
|
|
272
304
|
if (meta.links) {
|
|
273
305
|
for (const [key, link] of Object.entries(meta.links)) {
|
|
274
306
|
linkedFieldnames.add(link.fieldname ?? key);
|
|
275
307
|
}
|
|
276
308
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
if (f.fieldtype === 'Link' && linkedFieldnames.has(f.fieldname))
|
|
282
|
-
return false;
|
|
283
|
-
return true;
|
|
284
|
-
})
|
|
285
|
-
.map(f => f.fieldname)
|
|
286
|
-
.join('\n ');
|
|
287
|
-
}
|
|
288
|
-
/**
|
|
289
|
-
* Get the effective fetch strategy for a link, applying cardinality-based defaults.
|
|
290
|
-
*/
|
|
291
|
-
function getEffectiveFetchStrategy(link) {
|
|
292
|
-
if (link.fetch !== undefined) {
|
|
293
|
-
return link.fetch;
|
|
294
|
-
}
|
|
295
|
-
if (isManyCardinality(link.cardinality)) {
|
|
296
|
-
return { method: 'sync', limit: DEFAULT_SYNC_LIMIT };
|
|
297
|
-
}
|
|
298
|
-
else {
|
|
299
|
-
return { method: 'lazy' };
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
/**
|
|
303
|
-
* Get the effective blockWorkflows value for a link.
|
|
304
|
-
*/
|
|
305
|
-
function getEffectiveBlockWorkflows(link) {
|
|
306
|
-
if (link.blockWorkflows !== undefined) {
|
|
307
|
-
return link.blockWorkflows;
|
|
309
|
+
const columns = [];
|
|
310
|
+
const hasPk = meta.fields.some(f => f.fieldname === pkField);
|
|
311
|
+
if (!hasPk) {
|
|
312
|
+
columns.push(`"${pkField}"`);
|
|
308
313
|
}
|
|
309
|
-
const
|
|
310
|
-
|
|
311
|
-
}
|
|
312
|
-
/**
|
|
313
|
-
* Build nested sub-selections for descendant links
|
|
314
|
-
*/
|
|
315
|
-
function buildNestedSelections(params) {
|
|
316
|
-
const { links, meta, includeSet, getMeta, seen, depth, maxDepth, reverseConnectionNameFn } = params;
|
|
317
|
-
if (maxDepth !== undefined && depth >= maxDepth)
|
|
318
|
-
return '';
|
|
319
|
-
const selections = [];
|
|
320
|
-
for (const [fieldname, link] of Object.entries(links)) {
|
|
321
|
-
if (maxDepth !== undefined && depth >= maxDepth)
|
|
322
|
-
break;
|
|
323
|
-
const effectiveBlockWorkflows = getEffectiveBlockWorkflows(link);
|
|
324
|
-
const linkBlockWorkflowsExplicitTrue = link.blockWorkflows === true;
|
|
325
|
-
if (includeSet && !includeSet.has(fieldname) && !linkBlockWorkflowsExplicitTrue) {
|
|
326
|
-
continue;
|
|
327
|
-
}
|
|
328
|
-
const effectiveFetch = getEffectiveFetchStrategy(link);
|
|
329
|
-
const shouldSkip = effectiveBlockWorkflows === false || (effectiveFetch.method !== 'sync' && !linkBlockWorkflowsExplicitTrue);
|
|
330
|
-
if (shouldSkip) {
|
|
314
|
+
for (const f of meta.fields) {
|
|
315
|
+
if (f.fieldtype === 'Display')
|
|
331
316
|
continue;
|
|
332
|
-
|
|
333
|
-
const targetMeta = getMeta(link.target);
|
|
334
|
-
if (!targetMeta)
|
|
317
|
+
if (f.fieldtype === 'Link' && linkedFieldnames.has(f.fieldname))
|
|
335
318
|
continue;
|
|
336
|
-
|
|
337
|
-
if (!alreadySeen) {
|
|
338
|
-
seen.add(link.target);
|
|
339
|
-
}
|
|
340
|
-
const scalarFields = queryableFieldNames(targetMeta);
|
|
341
|
-
let nestedLinks = '';
|
|
342
|
-
if (!alreadySeen && targetMeta.links && targetMeta.tableName && (maxDepth === undefined || depth + 1 < maxDepth)) {
|
|
343
|
-
const innerSelections = buildNestedSelections({
|
|
344
|
-
links: targetMeta.links,
|
|
345
|
-
meta: targetMeta,
|
|
346
|
-
includeSet: null,
|
|
347
|
-
getMeta,
|
|
348
|
-
seen,
|
|
349
|
-
depth: depth + 1,
|
|
350
|
-
maxDepth,
|
|
351
|
-
reverseConnectionNameFn,
|
|
352
|
-
});
|
|
353
|
-
if (innerSelections) {
|
|
354
|
-
nestedLinks = '\n ' + innerSelections;
|
|
355
|
-
}
|
|
356
|
-
seen.delete(link.target);
|
|
357
|
-
}
|
|
358
|
-
const fullSelection = scalarFields + nestedLinks;
|
|
359
|
-
if (isManyCardinality(link.cardinality)) {
|
|
360
|
-
const reverseParams = {
|
|
361
|
-
doctype: meta.slug || meta.name,
|
|
362
|
-
linkName: fieldname,
|
|
363
|
-
backlink: link.backlink,
|
|
364
|
-
target: link.target,
|
|
365
|
-
};
|
|
366
|
-
const connectionField = reverseConnectionNameFn
|
|
367
|
-
? reverseConnectionNameFn(reverseParams)
|
|
368
|
-
: defaultReverseConnectionName(reverseParams);
|
|
369
|
-
const limitArg = effectiveFetch.method === 'sync' && effectiveFetch.limit !== undefined
|
|
370
|
-
? `first: ${effectiveFetch.limit}`
|
|
371
|
-
: effectiveFetch.method === 'sync'
|
|
372
|
-
? `first: ${DEFAULT_SYNC_LIMIT}`
|
|
373
|
-
: '';
|
|
374
|
-
selections.push(`
|
|
375
|
-
${connectionField}${limitArg ? `(${limitArg})` : ''} {
|
|
376
|
-
nodes {
|
|
377
|
-
${fullSelection}
|
|
378
|
-
}
|
|
379
|
-
}`);
|
|
380
|
-
}
|
|
381
|
-
else {
|
|
382
|
-
selections.push(`
|
|
383
|
-
${fieldname} {
|
|
384
|
-
${fullSelection}
|
|
385
|
-
}`);
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
return selections.join('');
|
|
389
|
-
}
|
|
390
|
-
/**
|
|
391
|
-
* Build a GraphQL query to fetch a single record by ID.
|
|
392
|
-
* When includeNested is set, recursively includes descendant link sub-selections.
|
|
393
|
-
* @public
|
|
394
|
-
*/
|
|
395
|
-
function buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType, getMeta, options, reverseConnectionNameFn) {
|
|
396
|
-
const queryName = recordFieldName(meta.tableName);
|
|
397
|
-
const argName = recordArgName(meta.tableName);
|
|
398
|
-
const argType = recordArgType(meta.tableName);
|
|
399
|
-
const seen = new Set([meta.slug || meta.name]);
|
|
400
|
-
let selection = queryableFieldNames(meta);
|
|
401
|
-
if (options?.includeNested && meta.links) {
|
|
402
|
-
const includeSet = Array.isArray(options.includeNested) ? new Set(options.includeNested) : null;
|
|
403
|
-
const nestedSelections = buildNestedSelections({
|
|
404
|
-
links: meta.links,
|
|
405
|
-
meta,
|
|
406
|
-
includeSet,
|
|
407
|
-
getMeta,
|
|
408
|
-
seen,
|
|
409
|
-
depth: 0,
|
|
410
|
-
maxDepth: options.maxDepth,
|
|
411
|
-
reverseConnectionNameFn,
|
|
412
|
-
});
|
|
413
|
-
if (nestedSelections) {
|
|
414
|
-
selection += '\n ' + nestedSelections;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
return `
|
|
418
|
-
query GetRecord($${argName}: ${argType}) {
|
|
419
|
-
${queryName}(${argName}: $${argName}) {
|
|
420
|
-
${selection}
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
`;
|
|
424
|
-
}
|
|
425
|
-
/**
|
|
426
|
-
* Build a GraphQL connection query to fetch a list of records.
|
|
427
|
-
* Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,
|
|
428
|
-
* avoiding GraphQL spec §5.8.3 violations from unused variable declarations.
|
|
429
|
-
* Excludes Link relation fields and Display fields from the selection set.
|
|
430
|
-
* @public
|
|
431
|
-
*/
|
|
432
|
-
function buildListQuery(meta, args, connectionFieldName, orderByTypeName) {
|
|
433
|
-
const fieldNames = queryableFieldNames(meta);
|
|
434
|
-
const connectionName = connectionFieldName(meta.tableName);
|
|
435
|
-
const orderByType = orderByTypeName(meta.tableName);
|
|
436
|
-
const varDecls = [];
|
|
437
|
-
const queryArgs = [];
|
|
438
|
-
if (args.limit) {
|
|
439
|
-
varDecls.push('$limit: Int');
|
|
440
|
-
queryArgs.push(`first: $limit`);
|
|
319
|
+
columns.push(`"${f.fieldname}"`);
|
|
441
320
|
}
|
|
442
|
-
|
|
443
|
-
varDecls.push('$offset: Int');
|
|
444
|
-
queryArgs.push(`offset: $offset`);
|
|
445
|
-
}
|
|
446
|
-
if (args.orderBy) {
|
|
447
|
-
varDecls.push(`$orderBy: [${orderByType}!]`);
|
|
448
|
-
queryArgs.push(`orderBy: $orderBy`);
|
|
449
|
-
}
|
|
450
|
-
const varStr = varDecls.length > 0 ? `(${varDecls.join(', ')})` : '';
|
|
451
|
-
const argsStr = queryArgs.length > 0 ? `(${queryArgs.join(', ')})` : '';
|
|
452
|
-
return `
|
|
453
|
-
query GetRecords${varStr} {
|
|
454
|
-
${connectionName}${argsStr} {
|
|
455
|
-
nodes {
|
|
456
|
-
${fieldNames}
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
`;
|
|
461
|
-
}
|
|
462
|
-
/**
|
|
463
|
-
* Merge nested connection results into flat arrays.
|
|
464
|
-
* For `noneOrMany`/`atLeastOne` links, the query returns `{ nodes: [...] }`.
|
|
465
|
-
* This flattens them to just `[]` for easier consumption.
|
|
466
|
-
* @public
|
|
467
|
-
*/
|
|
468
|
-
function mergeNestedResults(params) {
|
|
469
|
-
const { record, meta, getMeta, reverseConnectionNameFn } = params;
|
|
470
|
-
if (!meta.links)
|
|
471
|
-
return record;
|
|
472
|
-
const merged = { ...record };
|
|
473
|
-
for (const [fieldname, link] of Object.entries(meta.links)) {
|
|
474
|
-
const isMany = isManyCardinality(link.cardinality);
|
|
475
|
-
if (isMany) {
|
|
476
|
-
const targetMeta = getMeta(link.target);
|
|
477
|
-
if (!targetMeta)
|
|
478
|
-
continue;
|
|
479
|
-
const reverseParams = {
|
|
480
|
-
doctype: meta.slug || meta.name,
|
|
481
|
-
linkName: fieldname,
|
|
482
|
-
backlink: link.backlink || fieldname,
|
|
483
|
-
target: link.target,
|
|
484
|
-
};
|
|
485
|
-
const connectionField = reverseConnectionNameFn
|
|
486
|
-
? reverseConnectionNameFn(reverseParams)
|
|
487
|
-
: defaultReverseConnectionName(reverseParams);
|
|
488
|
-
const connectionResult = merged[connectionField];
|
|
489
|
-
if (connectionResult?.nodes) {
|
|
490
|
-
merged[fieldname] = connectionResult.nodes;
|
|
491
|
-
delete merged[connectionField];
|
|
492
|
-
}
|
|
493
|
-
else {
|
|
494
|
-
merged[fieldname] = [];
|
|
495
|
-
delete merged[connectionField];
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
return merged;
|
|
500
|
-
}
|
|
501
|
-
/**
|
|
502
|
-
* Extract a single record from a PostGraphile query result using the record field name.
|
|
503
|
-
* @public
|
|
504
|
-
*/
|
|
505
|
-
function extractSingleResult(params) {
|
|
506
|
-
const { result, meta, recordFieldName } = params;
|
|
507
|
-
const queryName = recordFieldName(meta.tableName);
|
|
508
|
-
return result[queryName];
|
|
509
|
-
}
|
|
510
|
-
/**
|
|
511
|
-
* Extract the list of nodes from a PostGraphile connection query result.
|
|
512
|
-
* Returns an empty array if the connection field is absent.
|
|
513
|
-
* @public
|
|
514
|
-
*/
|
|
515
|
-
function extractListResult(params) {
|
|
516
|
-
const { result, meta, connectionFieldName } = params;
|
|
517
|
-
const connectionName = connectionFieldName(meta.tableName);
|
|
518
|
-
const connection = result[connectionName];
|
|
519
|
-
return connection?.nodes ?? [];
|
|
321
|
+
return columns.join(', ');
|
|
520
322
|
}
|
|
521
|
-
// =============================================================================
|
|
522
|
-
// Exported for testing and advanced usage
|
|
523
|
-
// =============================================================================
|
|
524
|
-
export { defaultRecordFieldName, defaultConnectionFieldName, defaultOrderByTypeName, defaultRecordArgName, defaultRecordArgType, defaultReverseConnectionName, buildRecordQuery, buildListQuery, queryableFieldNames, RELATION_FIELDTYPES, extractSingleResult, extractListResult, mergeNestedResults, };
|