@stonecrop/graphql-middleware 0.12.8 → 0.13.1
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 -64
- package/dist/graphql-middleware.d.ts +113 -246
- package/dist/index.js +383 -423
- 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 +17 -171
- package/dist/src/plugin/postgraphile.d.ts.map +1 -1
- package/dist/src/plugin/postgraphile.js +279 -446
- 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/typeDefs.d.ts.map +1 -1
- package/dist/src/typeDefs.js +0 -1
- 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 {
|
|
1
|
+
import { camelToSnake, pascalToSnake } from '@stonecrop/schema';
|
|
2
|
+
import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
|
|
3
|
+
import { constant, lambda, object } from 'postgraphile/grafast';
|
|
3
4
|
import { extendSchema } from 'postgraphile/utils';
|
|
4
|
-
import pluralize from 'pluralize';
|
|
5
5
|
import { getHandler } from '../registry/actions';
|
|
6
|
+
import { getFetchHandler } from '../registry/fetchHandlers';
|
|
6
7
|
import { getMeta, getAllMeta } from '../registry/doctypes';
|
|
7
8
|
import { typeDefs } from '../typeDefs';
|
|
8
9
|
/**
|
|
9
|
-
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality
|
|
10
|
-
*
|
|
10
|
+
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
|
|
11
|
+
*
|
|
12
|
+
* The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`
|
|
13
|
+
* during schema construction — it does not need to be supplied by the caller.
|
|
14
|
+
*
|
|
15
|
+
* @param options - Optional plugin configuration
|
|
11
16
|
* @returns A PostGraphile plugin
|
|
12
17
|
* @public
|
|
13
18
|
*/
|
|
14
|
-
export const createStonecropPlugin = (options) => {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
export const createStonecropPlugin = (options = {}) => {
|
|
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,204 @@ export const createStonecropPlugin = (options) => {
|
|
|
35
51
|
return constant(getAllMeta());
|
|
36
52
|
},
|
|
37
53
|
stonecropRecord(_, { $doctype, $id, $options }) {
|
|
38
|
-
return
|
|
39
|
-
|
|
40
|
-
|
|
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);
|
|
41
66
|
if (!meta) {
|
|
42
|
-
|
|
67
|
+
for (const i of indices)
|
|
68
|
+
results[i] = { data: null, doctype };
|
|
69
|
+
continue;
|
|
43
70
|
}
|
|
44
|
-
|
|
45
|
-
|
|
71
|
+
const pkMeta = getPkMeta(meta);
|
|
72
|
+
if (!pkMeta) {
|
|
73
|
+
for (const i of indices)
|
|
74
|
+
results[i] = { data: null, doctype };
|
|
75
|
+
continue;
|
|
46
76
|
}
|
|
47
|
-
const
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
: undefined, reverseConnectionName);
|
|
54
|
-
const result = await options.executor.query(query, {
|
|
55
|
-
[recordArgName(meta.tableName)]: spec.id,
|
|
77
|
+
const pkColumn = camelToSnake(pkMeta.fieldname);
|
|
78
|
+
const columns = getSqlColumns(meta);
|
|
79
|
+
const ids = indices.map(i => specs[i].id);
|
|
80
|
+
const { rows } = await debugSql(pgClient, {
|
|
81
|
+
text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
|
|
82
|
+
values: [ids],
|
|
56
83
|
});
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
84
|
+
// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
|
|
85
|
+
const rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]));
|
|
86
|
+
for (const i of indices) {
|
|
87
|
+
const specId = specs[i].id;
|
|
88
|
+
const row = rowByPk.get(specId);
|
|
89
|
+
if (!row) {
|
|
90
|
+
results[i] = { data: null, doctype };
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const rowData = { ...row };
|
|
94
|
+
const recordOptions = (specs[i].options ?? {});
|
|
95
|
+
const includeAll = recordOptions.includeNested === true;
|
|
96
|
+
const includeSet = Array.isArray(recordOptions.includeNested)
|
|
97
|
+
? new Set(recordOptions.includeNested)
|
|
98
|
+
: null;
|
|
99
|
+
// FetchStrategy dispatch over link declarations
|
|
100
|
+
if (meta.links) {
|
|
101
|
+
for (const [linkName, link] of Object.entries(meta.links)) {
|
|
102
|
+
const fetch = link.fetch;
|
|
103
|
+
const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
|
|
104
|
+
const effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy');
|
|
105
|
+
const effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined;
|
|
106
|
+
const shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync');
|
|
107
|
+
if (!shouldInclude)
|
|
108
|
+
continue;
|
|
109
|
+
if (effectiveMethod === 'custom') {
|
|
110
|
+
const handlerName = fetch.handler;
|
|
111
|
+
const handler = getFetchHandler(handlerName);
|
|
112
|
+
if (handler) {
|
|
113
|
+
rowData[linkName] = await handler(pgClient, rowData, link);
|
|
114
|
+
}
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (effectiveMethod !== 'sync' && !includeSet?.has(linkName))
|
|
118
|
+
continue;
|
|
119
|
+
const targetMeta = getMeta(link.target);
|
|
120
|
+
if (!targetMeta)
|
|
121
|
+
continue;
|
|
122
|
+
const targetColumns = getSqlColumns(targetMeta);
|
|
123
|
+
if (isMany) {
|
|
124
|
+
if (!link.backlink)
|
|
125
|
+
continue;
|
|
126
|
+
const backlinkCol = camelToSnake(link.backlink);
|
|
127
|
+
let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
|
|
128
|
+
const linkValues = [specId];
|
|
129
|
+
if (effectiveLimit != null) {
|
|
130
|
+
sql += ` LIMIT $2`;
|
|
131
|
+
linkValues.push(effectiveLimit);
|
|
132
|
+
}
|
|
133
|
+
const { rows: linked } = await debugSql(pgClient, {
|
|
134
|
+
text: sql,
|
|
135
|
+
values: linkValues,
|
|
136
|
+
});
|
|
137
|
+
rowData[linkName] = linked;
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
if (!link.fieldname)
|
|
141
|
+
continue;
|
|
142
|
+
const fkValue = rowData[link.fieldname];
|
|
143
|
+
if (fkValue == null) {
|
|
144
|
+
rowData[linkName] = null;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
const targetPkMeta = getPkMeta(targetMeta);
|
|
148
|
+
if (!targetPkMeta)
|
|
149
|
+
continue;
|
|
150
|
+
const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
|
|
151
|
+
const { rows: linked } = await debugSql(pgClient, {
|
|
152
|
+
text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
|
|
153
|
+
values: [fkValue],
|
|
154
|
+
});
|
|
155
|
+
rowData[linkName] = linked[0] ?? null;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
// Names in includeNested that don't correspond to any link
|
|
160
|
+
const unknownLinks = includeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links)) : undefined;
|
|
161
|
+
results[i] = {
|
|
162
|
+
data: rowData,
|
|
163
|
+
doctype,
|
|
164
|
+
unknownLinks: unknownLinks?.length ? unknownLinks : undefined,
|
|
165
|
+
};
|
|
65
166
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
: undefined;
|
|
69
|
-
return {
|
|
70
|
-
data,
|
|
71
|
-
doctype: spec.doctype,
|
|
72
|
-
...(unknownLinks ? { unknownLinks } : {}),
|
|
73
|
-
};
|
|
74
|
-
}));
|
|
167
|
+
}
|
|
168
|
+
return results;
|
|
75
169
|
});
|
|
76
170
|
},
|
|
77
|
-
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset
|
|
78
|
-
return
|
|
171
|
+
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset }) {
|
|
172
|
+
return loadOneWithPgClient(executor, object({
|
|
79
173
|
doctype: $doctype,
|
|
80
174
|
filters: $filters,
|
|
81
175
|
orderBy: $orderBy,
|
|
82
176
|
limit: $limit,
|
|
83
177
|
offset: $offset,
|
|
84
|
-
|
|
85
|
-
}), async (specs) => {
|
|
178
|
+
}), async (pgClient, specs) => {
|
|
86
179
|
return await Promise.all(specs.map(async (spec) => {
|
|
87
180
|
const meta = getMeta(spec.doctype);
|
|
88
181
|
if (!meta) {
|
|
89
|
-
|
|
182
|
+
return { data: [], doctype: spec.doctype, count: 0 };
|
|
90
183
|
}
|
|
91
|
-
|
|
92
|
-
|
|
184
|
+
const knownFields = new Set(meta.fields.map(f => f.fieldname));
|
|
185
|
+
const columns = getSqlColumns(meta);
|
|
186
|
+
const values = [];
|
|
187
|
+
// WHERE from filters (parameterised — safe against SQL injection)
|
|
188
|
+
const whereClauses = [];
|
|
189
|
+
if (spec.filters != null) {
|
|
190
|
+
for (const [field, value] of Object.entries(spec.filters)) {
|
|
191
|
+
if (!knownFields.has(field)) {
|
|
192
|
+
throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
|
|
193
|
+
}
|
|
194
|
+
values.push(value);
|
|
195
|
+
whereClauses.push(`"${camelToSnake(field)}" = $${values.length}`);
|
|
196
|
+
}
|
|
93
197
|
}
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
198
|
+
const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
|
|
199
|
+
// ORDER BY (field name whitelisted — column names cannot be parameterised)
|
|
200
|
+
let orderByClause = '';
|
|
201
|
+
if (spec.orderBy != null) {
|
|
202
|
+
const orderByStr = spec.orderBy;
|
|
203
|
+
const lastUnder = orderByStr.lastIndexOf('_');
|
|
204
|
+
if (lastUnder <= 0) {
|
|
205
|
+
throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
|
|
206
|
+
}
|
|
207
|
+
const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
|
|
208
|
+
if (dir !== 'ASC' && dir !== 'DESC') {
|
|
209
|
+
throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
|
|
210
|
+
}
|
|
211
|
+
const fieldName = orderByStr.slice(0, lastUnder);
|
|
212
|
+
if (!knownFields.has(fieldName)) {
|
|
213
|
+
throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
|
|
214
|
+
}
|
|
215
|
+
orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
|
|
216
|
+
}
|
|
217
|
+
// LIMIT / OFFSET
|
|
218
|
+
let pagingClause = '';
|
|
219
|
+
if (spec.limit != null) {
|
|
220
|
+
values.push(spec.limit);
|
|
221
|
+
pagingClause += ` LIMIT $${values.length}`;
|
|
222
|
+
}
|
|
223
|
+
if (spec.offset != null) {
|
|
224
|
+
values.push(spec.offset);
|
|
225
|
+
pagingClause += ` OFFSET $${values.length}`;
|
|
226
|
+
}
|
|
227
|
+
const { rows } = await debugSql(pgClient, {
|
|
228
|
+
text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,
|
|
229
|
+
values,
|
|
103
230
|
});
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
231
|
+
// Total count matching filters (independent of LIMIT/OFFSET)
|
|
232
|
+
let count = rows.length;
|
|
233
|
+
if (spec.limit != null || spec.offset != null) {
|
|
234
|
+
const countValues = [];
|
|
235
|
+
const countWhere = [];
|
|
236
|
+
if (spec.filters != null) {
|
|
237
|
+
for (const [field, value] of Object.entries(spec.filters)) {
|
|
238
|
+
if (!knownFields.has(field))
|
|
239
|
+
continue;
|
|
240
|
+
countValues.push(value);
|
|
241
|
+
countWhere.push(`"${camelToSnake(field)}" = $${countValues.length}`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : '';
|
|
245
|
+
const { rows: countRows } = await debugSql(pgClient, {
|
|
246
|
+
text: `SELECT COUNT(*) AS __count FROM ${resolveTableName(meta.name, options.tables)}${countWhereClause}`,
|
|
247
|
+
values: countValues,
|
|
248
|
+
});
|
|
249
|
+
count = parseInt(countRows[0]?.__count ?? '0', 10);
|
|
250
|
+
}
|
|
251
|
+
return { data: rows, doctype: spec.doctype, count };
|
|
110
252
|
}));
|
|
111
253
|
});
|
|
112
254
|
},
|
|
@@ -115,57 +257,43 @@ export const createStonecropPlugin = (options) => {
|
|
|
115
257
|
Mutation: {
|
|
116
258
|
plans: {
|
|
117
259
|
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,
|
|
260
|
+
return sideEffectWithPgClient(executor, object({ doctype: $doctype, action: $action, actionArgs: $actionArgs }), async (pgClient, spec) => {
|
|
261
|
+
const meta = getMeta(spec.doctype);
|
|
262
|
+
if (!meta) {
|
|
263
|
+
return {
|
|
264
|
+
success: false,
|
|
265
|
+
data: null,
|
|
266
|
+
error: `Unknown doctype: ${spec.doctype}`,
|
|
152
267
|
};
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
268
|
+
}
|
|
269
|
+
const actionDef = meta.workflow?.actions?.[spec.action];
|
|
270
|
+
if (!actionDef) {
|
|
271
|
+
return {
|
|
272
|
+
success: false,
|
|
273
|
+
data: null,
|
|
274
|
+
error: `Unknown action: ${spec.action} on ${spec.doctype}`,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
const handler = getHandler(actionDef.handler);
|
|
278
|
+
if (!handler) {
|
|
279
|
+
return {
|
|
280
|
+
success: false,
|
|
281
|
+
data: null,
|
|
282
|
+
error: `Handler not registered: ${actionDef.handler}`,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
const actionContext = { doctype: meta, pgClient };
|
|
286
|
+
try {
|
|
287
|
+
const result = await handler(spec.actionArgs ?? [], actionContext);
|
|
288
|
+
return { success: true, data: result, error: null };
|
|
289
|
+
}
|
|
290
|
+
catch (err) {
|
|
291
|
+
return {
|
|
292
|
+
success: false,
|
|
293
|
+
data: null,
|
|
294
|
+
error: err instanceof Error ? err.message : String(err),
|
|
295
|
+
};
|
|
296
|
+
}
|
|
169
297
|
});
|
|
170
298
|
},
|
|
171
299
|
},
|
|
@@ -174,351 +302,56 @@ export const createStonecropPlugin = (options) => {
|
|
|
174
302
|
};
|
|
175
303
|
});
|
|
176
304
|
};
|
|
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
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).
|
|
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;
|
|
305
|
+
// ===========================================================================
|
|
306
|
+
// SQL column helpers
|
|
307
|
+
// ===========================================================================
|
|
252
308
|
/**
|
|
253
|
-
*
|
|
254
|
-
*
|
|
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.
|
|
309
|
+
* Derive a quoted SQL column list from doctype field definitions.
|
|
310
|
+
* Applies camelToSnake to each fieldname to get the DB column name, then
|
|
311
|
+
* aliases it back to the fieldname so result rows carry API-layer keys.
|
|
265
312
|
* Excludes Display fields (no backing DB column) and Link fields that have an
|
|
266
|
-
* explicit `links` declaration (those
|
|
267
|
-
*
|
|
268
|
-
*
|
|
313
|
+
* explicit `links` declaration (those are FK references, not scalar columns).
|
|
314
|
+
*
|
|
315
|
+
* TODO(schema-types Phase 4): add f.kind === 'field' narrowing when DoctypeField union lands
|
|
269
316
|
*/
|
|
270
|
-
function
|
|
317
|
+
function getSqlColumns(meta) {
|
|
271
318
|
const linkedFieldnames = new Set();
|
|
272
319
|
if (meta.links) {
|
|
273
320
|
for (const [key, link] of Object.entries(meta.links)) {
|
|
274
321
|
linkedFieldnames.add(link.fieldname ?? key);
|
|
275
322
|
}
|
|
276
323
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
if (
|
|
280
|
-
return false;
|
|
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;
|
|
308
|
-
}
|
|
309
|
-
const effectiveFetch = getEffectiveFetchStrategy(link);
|
|
310
|
-
return effectiveFetch.method === 'sync';
|
|
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) {
|
|
324
|
+
const columns = [];
|
|
325
|
+
for (const f of meta.fields) {
|
|
326
|
+
if (f.fieldtype === 'Display')
|
|
331
327
|
continue;
|
|
332
|
-
|
|
333
|
-
const targetMeta = getMeta(link.target);
|
|
334
|
-
if (!targetMeta)
|
|
328
|
+
if (f.fieldtype === 'Link' && linkedFieldnames.has(f.fieldname))
|
|
335
329
|
continue;
|
|
336
|
-
const
|
|
337
|
-
|
|
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
|
-
}
|
|
330
|
+
const col = camelToSnake(f.fieldname);
|
|
331
|
+
columns.push(col !== f.fieldname ? `"${col}" AS "${f.fieldname}"` : `"${f.fieldname}"`);
|
|
416
332
|
}
|
|
417
|
-
return
|
|
418
|
-
query GetRecord($${argName}: ${argType}) {
|
|
419
|
-
${queryName}(${argName}: $${argName}) {
|
|
420
|
-
${selection}
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
`;
|
|
333
|
+
return columns.join(', ');
|
|
424
334
|
}
|
|
425
335
|
/**
|
|
426
|
-
*
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
* @public
|
|
336
|
+
* Find the field declared with fieldtype 'PrimaryKey' in the doctype.
|
|
337
|
+
* Returns undefined when no PrimaryKey field is declared (PK-less doctypes).
|
|
338
|
+
*
|
|
339
|
+
* TODO(schema-types Phase 4): add f.kind === 'field' narrowing when DoctypeField union lands
|
|
431
340
|
*/
|
|
432
|
-
function
|
|
433
|
-
|
|
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`);
|
|
441
|
-
}
|
|
442
|
-
if (args.offset) {
|
|
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
|
-
`;
|
|
341
|
+
function getPkMeta(meta) {
|
|
342
|
+
return meta.fields.find(f => f.fieldtype === 'PrimaryKey');
|
|
461
343
|
}
|
|
462
344
|
/**
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
*
|
|
466
|
-
*
|
|
345
|
+
* Resolve the PostgreSQL FROM clause target for a doctype.
|
|
346
|
+
* Uses the `tables` override map first; falls back to camelToSnake(name).
|
|
347
|
+
* Schema-qualified names (e.g. "orpin.plan") are emitted as "schema"."table".
|
|
348
|
+
* Values must be bare identifiers or schema.table pairs — not SQL fragments.
|
|
467
349
|
*/
|
|
468
|
-
function
|
|
469
|
-
const
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
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
|
-
}
|
|
350
|
+
function resolveTableName(name, tables) {
|
|
351
|
+
const target = tables?.[name] ?? pascalToSnake(name);
|
|
352
|
+
const dotIndex = target.indexOf('.');
|
|
353
|
+
if (dotIndex > 0) {
|
|
354
|
+
return `"${target.slice(0, dotIndex)}"."${target.slice(dotIndex + 1)}"`;
|
|
498
355
|
}
|
|
499
|
-
return
|
|
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 ?? [];
|
|
356
|
+
return `"${target}"`;
|
|
520
357
|
}
|
|
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, };
|