@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
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
import { snakeToCamel, toPascalCase } from '@stonecrop/schema';
|
|
2
|
+
import { constant, lambda, object, loadOne } from 'postgraphile/grafast';
|
|
3
|
+
import { extendSchema, gql } from 'postgraphile/utils';
|
|
4
|
+
import pluralize from 'pluralize';
|
|
5
|
+
import { getHandler } from '../registry/actions';
|
|
6
|
+
import { getMeta, getAllMeta } from '../registry/doctypes';
|
|
7
|
+
/**
|
|
8
|
+
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality
|
|
9
|
+
* @param options - Plugin configuration options
|
|
10
|
+
* @returns A PostGraphile plugin
|
|
11
|
+
* @public
|
|
12
|
+
*/
|
|
13
|
+
export const createStonecropPlugin = (options) => {
|
|
14
|
+
// Resolve inflection callbacks with Amber defaults
|
|
15
|
+
const recordFieldName = options.inflection?.recordFieldName ?? defaultRecordFieldName;
|
|
16
|
+
const connectionFieldName = options.inflection?.connectionFieldName ?? defaultConnectionFieldName;
|
|
17
|
+
const orderByTypeName = options.inflection?.orderByTypeName ?? defaultOrderByTypeName;
|
|
18
|
+
const recordArgName = options.inflection?.recordArgName ?? defaultRecordArgName;
|
|
19
|
+
const recordArgType = options.inflection?.recordArgType ?? defaultRecordArgType;
|
|
20
|
+
const reverseConnectionName = options.inflection?.reverseConnectionName ?? defaultReverseConnectionName;
|
|
21
|
+
return extendSchema(() => {
|
|
22
|
+
return {
|
|
23
|
+
typeDefs: gql `
|
|
24
|
+
type StonecropFieldMeta {
|
|
25
|
+
fieldname: String!
|
|
26
|
+
fieldtype: String!
|
|
27
|
+
component: String
|
|
28
|
+
label: String
|
|
29
|
+
width: String
|
|
30
|
+
align: String
|
|
31
|
+
required: Boolean
|
|
32
|
+
readOnly: Boolean
|
|
33
|
+
edit: Boolean
|
|
34
|
+
hidden: Boolean
|
|
35
|
+
default: JSON
|
|
36
|
+
options: JSON
|
|
37
|
+
mask: String
|
|
38
|
+
precision: Int
|
|
39
|
+
scale: Int
|
|
40
|
+
mode: String
|
|
41
|
+
validation: JSON
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type StonecropWorkflowAction {
|
|
45
|
+
label: String!
|
|
46
|
+
handler: String!
|
|
47
|
+
requiredFields: [String!]
|
|
48
|
+
allowedStates: [String!]
|
|
49
|
+
confirm: Boolean
|
|
50
|
+
args: JSON
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type StonecropWorkflowMeta {
|
|
54
|
+
states: [String!]
|
|
55
|
+
actions: [StonecropWorkflowAction!]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type StonecropDoctypeMeta {
|
|
59
|
+
name: String!
|
|
60
|
+
slug: String
|
|
61
|
+
tableName: String
|
|
62
|
+
fields: [StonecropFieldMeta!]!
|
|
63
|
+
workflow: StonecropWorkflowMeta
|
|
64
|
+
inherits: String
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
type StonecropRecordResult {
|
|
68
|
+
data: JSON
|
|
69
|
+
doctype: String!
|
|
70
|
+
unknownLinks: [String!]
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type StonecropRecordsResult {
|
|
74
|
+
data: [JSON!]!
|
|
75
|
+
doctype: String!
|
|
76
|
+
count: Int!
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
type StonecropActionResult {
|
|
80
|
+
success: Boolean!
|
|
81
|
+
data: JSON
|
|
82
|
+
error: String
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
extend type Query {
|
|
86
|
+
stonecropMeta(doctype: String!): StonecropDoctypeMeta
|
|
87
|
+
stonecropAllMeta: [StonecropDoctypeMeta!]!
|
|
88
|
+
stonecropRecord(doctype: String!, id: String!, options: JSON): StonecropRecordResult
|
|
89
|
+
stonecropRecords(
|
|
90
|
+
doctype: String!
|
|
91
|
+
filters: JSON
|
|
92
|
+
orderBy: String
|
|
93
|
+
limit: Int
|
|
94
|
+
offset: Int
|
|
95
|
+
): StonecropRecordsResult
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
extend type Mutation {
|
|
99
|
+
stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
|
|
100
|
+
}
|
|
101
|
+
`,
|
|
102
|
+
objects: {
|
|
103
|
+
Query: {
|
|
104
|
+
plans: {
|
|
105
|
+
stonecropMeta(_, { $doctype }) {
|
|
106
|
+
return lambda($doctype, (doctype) => {
|
|
107
|
+
const meta = getMeta(doctype);
|
|
108
|
+
return meta ?? null;
|
|
109
|
+
});
|
|
110
|
+
},
|
|
111
|
+
stonecropAllMeta() {
|
|
112
|
+
return constant(getAllMeta());
|
|
113
|
+
},
|
|
114
|
+
stonecropRecord(_, { $doctype, $id, $options }) {
|
|
115
|
+
return loadOne(object({ doctype: $doctype, id: $id, options: $options }), async (specs) => {
|
|
116
|
+
return await Promise.all(specs.map(async (spec) => {
|
|
117
|
+
const meta = getMeta(spec.doctype);
|
|
118
|
+
if (!meta) {
|
|
119
|
+
throw new Error(`Unknown doctype: ${spec.doctype}`);
|
|
120
|
+
}
|
|
121
|
+
if (!meta.tableName) {
|
|
122
|
+
throw new Error(`Doctype ${spec.doctype} has no table mapping`);
|
|
123
|
+
}
|
|
124
|
+
const recordOptions = spec.options ?? {};
|
|
125
|
+
const query = buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType, getMeta, recordOptions.includeNested
|
|
126
|
+
? {
|
|
127
|
+
includeNested: recordOptions.includeNested,
|
|
128
|
+
maxDepth: recordOptions.maxDepth,
|
|
129
|
+
}
|
|
130
|
+
: undefined, reverseConnectionName);
|
|
131
|
+
const result = await options.executor.query(query, {
|
|
132
|
+
[recordArgName(meta.tableName)]: spec.id,
|
|
133
|
+
});
|
|
134
|
+
let data = extractSingleResult({ result, meta, recordFieldName });
|
|
135
|
+
if (recordOptions.includeNested && data && meta.links) {
|
|
136
|
+
data = mergeNestedResults({
|
|
137
|
+
record: data,
|
|
138
|
+
meta,
|
|
139
|
+
getMeta,
|
|
140
|
+
reverseConnectionNameFn: reverseConnectionName,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
const unknownLinks = Array.isArray(recordOptions.includeNested) && meta.links
|
|
144
|
+
? recordOptions.includeNested.filter((name) => !(name in meta.links))
|
|
145
|
+
: undefined;
|
|
146
|
+
return {
|
|
147
|
+
data,
|
|
148
|
+
doctype: spec.doctype,
|
|
149
|
+
...(unknownLinks ? { unknownLinks } : {}),
|
|
150
|
+
};
|
|
151
|
+
}));
|
|
152
|
+
});
|
|
153
|
+
},
|
|
154
|
+
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset }) {
|
|
155
|
+
return loadOne(object({
|
|
156
|
+
doctype: $doctype,
|
|
157
|
+
filters: $filters,
|
|
158
|
+
orderBy: $orderBy,
|
|
159
|
+
limit: $limit,
|
|
160
|
+
offset: $offset,
|
|
161
|
+
}), async (specs) => {
|
|
162
|
+
return await Promise.all(specs.map(async (spec) => {
|
|
163
|
+
const meta = getMeta(spec.doctype);
|
|
164
|
+
if (!meta) {
|
|
165
|
+
throw new Error(`Unknown doctype: ${spec.doctype}`);
|
|
166
|
+
}
|
|
167
|
+
if (!meta.tableName) {
|
|
168
|
+
throw new Error(`Doctype ${spec.doctype} has no table mapping`);
|
|
169
|
+
}
|
|
170
|
+
const query = buildListQuery(meta, {
|
|
171
|
+
limit: spec.limit,
|
|
172
|
+
offset: spec.offset,
|
|
173
|
+
orderBy: spec.orderBy,
|
|
174
|
+
}, connectionFieldName, orderByTypeName);
|
|
175
|
+
const result = await options.executor.query(query, {
|
|
176
|
+
limit: spec.limit,
|
|
177
|
+
offset: spec.offset,
|
|
178
|
+
orderBy: spec.orderBy,
|
|
179
|
+
});
|
|
180
|
+
const data = extractListResult({ result, meta, connectionFieldName });
|
|
181
|
+
return {
|
|
182
|
+
data,
|
|
183
|
+
doctype: spec.doctype,
|
|
184
|
+
count: data.length,
|
|
185
|
+
};
|
|
186
|
+
}));
|
|
187
|
+
});
|
|
188
|
+
},
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
Mutation: {
|
|
192
|
+
plans: {
|
|
193
|
+
stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
|
|
194
|
+
return loadOne(object({
|
|
195
|
+
doctype: $doctype,
|
|
196
|
+
action: $action,
|
|
197
|
+
actionArgs: $actionArgs,
|
|
198
|
+
}), async (specs) => {
|
|
199
|
+
return await Promise.all(specs.map(async (spec) => {
|
|
200
|
+
const meta = getMeta(spec.doctype);
|
|
201
|
+
if (!meta) {
|
|
202
|
+
return {
|
|
203
|
+
success: false,
|
|
204
|
+
data: null,
|
|
205
|
+
error: `Unknown doctype: ${spec.doctype}`,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
const actionDef = meta.workflow?.actions?.[spec.action];
|
|
209
|
+
if (!actionDef) {
|
|
210
|
+
return {
|
|
211
|
+
success: false,
|
|
212
|
+
data: null,
|
|
213
|
+
error: `Unknown action: ${spec.action} on ${spec.doctype}`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
const handlerName = actionDef.handler;
|
|
217
|
+
const handler = getHandler(handlerName);
|
|
218
|
+
if (!handler) {
|
|
219
|
+
return {
|
|
220
|
+
success: false,
|
|
221
|
+
data: null,
|
|
222
|
+
error: `Handler not registered: ${handlerName}`,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
const actionContext = {
|
|
226
|
+
doctype: meta,
|
|
227
|
+
executor: options.executor,
|
|
228
|
+
};
|
|
229
|
+
try {
|
|
230
|
+
const result = await handler(spec.actionArgs ?? [], actionContext);
|
|
231
|
+
return {
|
|
232
|
+
success: true,
|
|
233
|
+
data: result,
|
|
234
|
+
error: null,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
return {
|
|
239
|
+
success: false,
|
|
240
|
+
data: null,
|
|
241
|
+
error: err instanceof Error ? err.message : String(err),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
}));
|
|
245
|
+
});
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
});
|
|
252
|
+
};
|
|
253
|
+
// =============================================================================
|
|
254
|
+
// Inflection helpers — default to PostGraphile Amber preset conventions
|
|
255
|
+
// Uses `pluralize` for proper English singularization (handles irregular
|
|
256
|
+
// plurals like statuses→status, categories→category, addresses→address).
|
|
257
|
+
// snakeToCamel / toPascalCase are imported from @stonecrop/schema.
|
|
258
|
+
// =============================================================================
|
|
259
|
+
/**
|
|
260
|
+
* Amber default: sales_orders → salesOrderById
|
|
261
|
+
* Uses `pluralize` for proper singularization of irregular plurals.
|
|
262
|
+
* Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.
|
|
263
|
+
* @public
|
|
264
|
+
*/
|
|
265
|
+
function defaultRecordFieldName(tableName) {
|
|
266
|
+
const singular = pluralize.singular(tableName);
|
|
267
|
+
return `${snakeToCamel(singular)}ById`;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Amber default: sales_orders → allSalesOrders
|
|
271
|
+
* @public
|
|
272
|
+
*/
|
|
273
|
+
function defaultConnectionFieldName(tableName) {
|
|
274
|
+
return `all${toPascalCase(tableName)}`;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Amber default: sales_orders → SalesOrdersOrderBy
|
|
278
|
+
* @public
|
|
279
|
+
*/
|
|
280
|
+
function defaultOrderByTypeName(tableName) {
|
|
281
|
+
return `${toPascalCase(tableName)}OrderBy`;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Default PK argument name: 'id' (standard Relay Global ID pattern).
|
|
285
|
+
* Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;
|
|
286
|
+
* PostGraphile Amber generates `rowId: UUID!` for those fields.
|
|
287
|
+
* @public
|
|
288
|
+
*/
|
|
289
|
+
function defaultRecordArgName(_tableName) {
|
|
290
|
+
return 'id';
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).
|
|
294
|
+
* Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs
|
|
295
|
+
* such as integer serials or Relay Global IDs ('ID!').
|
|
296
|
+
* @public
|
|
297
|
+
*/
|
|
298
|
+
function defaultRecordArgType(_tableName) {
|
|
299
|
+
return 'UUID!';
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Default reverse connection name: derives PostGraphile's connection field convention.
|
|
303
|
+
* PostGraphile convention: `{targetPlural}By{FkColumnPascal}Id`
|
|
304
|
+
* - When backlink is defined: FK column is derived from the backlink field name
|
|
305
|
+
* - When backlink is absent: FK column is derived from the parent doctype's table name
|
|
306
|
+
* @public
|
|
307
|
+
*/
|
|
308
|
+
function defaultReverseConnectionName(params) {
|
|
309
|
+
const targetPlural = pluralize.plural(params.target.replace(/-/g, '_'));
|
|
310
|
+
// Use camelCase for target (matches PostGraphile Amber convention: recipeTasksByRecipeId)
|
|
311
|
+
const targetCamel = snakeToCamel(targetPlural);
|
|
312
|
+
// Use backlink if provided, otherwise derive from parent table name
|
|
313
|
+
const fkSource = params.backlink || params.doctype;
|
|
314
|
+
// FK column name: uppercase first char, preserve rest of camelCase
|
|
315
|
+
const fkPascal = fkSource.charAt(0).toUpperCase() + snakeToCamel(fkSource).slice(1);
|
|
316
|
+
return `${targetCamel}By${fkPascal}Id`;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Check if a cardinality represents a "many" relationship
|
|
320
|
+
*/
|
|
321
|
+
function isManyCardinality(cardinality) {
|
|
322
|
+
return cardinality === 'noneOrMany' || cardinality === 'atLeastOne';
|
|
323
|
+
}
|
|
324
|
+
// =============================================================================
|
|
325
|
+
// Query builders — generate GraphQL queries to send to the underlying schema
|
|
326
|
+
// =============================================================================
|
|
327
|
+
const DEFAULT_SYNC_LIMIT = 50;
|
|
328
|
+
/**
|
|
329
|
+
* Fieldtypes that map to GraphQL object/connection types and require sub-selections.
|
|
330
|
+
* These fields are excluded from generated query field selections.
|
|
331
|
+
* @public
|
|
332
|
+
*/
|
|
333
|
+
const RELATION_FIELDTYPES = new Set(['Link']);
|
|
334
|
+
/**
|
|
335
|
+
* Filter fields to only those directly queryable as scalars, excluding Link and Doctype
|
|
336
|
+
* relation fields that require GraphQL sub-selections.
|
|
337
|
+
* @public
|
|
338
|
+
*/
|
|
339
|
+
function queryableFieldNames(meta) {
|
|
340
|
+
return meta.fields
|
|
341
|
+
.filter(f => !RELATION_FIELDTYPES.has(f.fieldtype))
|
|
342
|
+
.map(f => f.fieldname)
|
|
343
|
+
.join('\n ');
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Get the effective fetch strategy for a link, applying cardinality-based defaults.
|
|
347
|
+
*/
|
|
348
|
+
function getEffectiveFetchStrategy(link) {
|
|
349
|
+
if (link.fetch !== undefined) {
|
|
350
|
+
return link.fetch;
|
|
351
|
+
}
|
|
352
|
+
if (isManyCardinality(link.cardinality)) {
|
|
353
|
+
return { method: 'sync', limit: DEFAULT_SYNC_LIMIT };
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
return { method: 'lazy' };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Get the effective blockWorkflows value for a link.
|
|
361
|
+
*/
|
|
362
|
+
function getEffectiveBlockWorkflows(link) {
|
|
363
|
+
if (link.blockWorkflows !== undefined) {
|
|
364
|
+
return link.blockWorkflows;
|
|
365
|
+
}
|
|
366
|
+
const effectiveFetch = getEffectiveFetchStrategy(link);
|
|
367
|
+
return effectiveFetch.method === 'sync';
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Build nested sub-selections for descendant links
|
|
371
|
+
*/
|
|
372
|
+
function buildNestedSelections(params) {
|
|
373
|
+
const { links, meta, includeSet, getMeta, seen, depth, maxDepth, reverseConnectionNameFn } = params;
|
|
374
|
+
if (maxDepth !== undefined && depth >= maxDepth)
|
|
375
|
+
return '';
|
|
376
|
+
const selections = [];
|
|
377
|
+
for (const [fieldname, link] of Object.entries(links)) {
|
|
378
|
+
if (maxDepth !== undefined && depth >= maxDepth)
|
|
379
|
+
break;
|
|
380
|
+
const effectiveBlockWorkflows = getEffectiveBlockWorkflows(link);
|
|
381
|
+
const linkBlockWorkflowsExplicitTrue = link.blockWorkflows === true;
|
|
382
|
+
if (includeSet && !includeSet.has(fieldname) && !linkBlockWorkflowsExplicitTrue) {
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
const effectiveFetch = getEffectiveFetchStrategy(link);
|
|
386
|
+
const shouldSkip = effectiveBlockWorkflows === false || (effectiveFetch.method !== 'sync' && !linkBlockWorkflowsExplicitTrue);
|
|
387
|
+
if (shouldSkip) {
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
const targetMeta = getMeta(link.target);
|
|
391
|
+
if (!targetMeta)
|
|
392
|
+
continue;
|
|
393
|
+
const alreadySeen = seen.has(link.target);
|
|
394
|
+
if (alreadySeen) {
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
seen.add(link.target);
|
|
398
|
+
}
|
|
399
|
+
const scalarFields = queryableFieldNames(targetMeta);
|
|
400
|
+
let nestedLinks = '';
|
|
401
|
+
if (!alreadySeen && targetMeta.links && targetMeta.tableName && (maxDepth === undefined || depth + 1 < maxDepth)) {
|
|
402
|
+
const innerSelections = buildNestedSelections({
|
|
403
|
+
links: targetMeta.links,
|
|
404
|
+
meta: targetMeta,
|
|
405
|
+
includeSet: null,
|
|
406
|
+
getMeta,
|
|
407
|
+
seen,
|
|
408
|
+
depth: depth + 1,
|
|
409
|
+
maxDepth,
|
|
410
|
+
reverseConnectionNameFn,
|
|
411
|
+
});
|
|
412
|
+
if (innerSelections) {
|
|
413
|
+
nestedLinks = '\n ' + innerSelections;
|
|
414
|
+
}
|
|
415
|
+
seen.delete(link.target);
|
|
416
|
+
}
|
|
417
|
+
const fullSelection = scalarFields + nestedLinks;
|
|
418
|
+
if (isManyCardinality(link.cardinality)) {
|
|
419
|
+
const reverseParams = {
|
|
420
|
+
doctype: meta.slug || meta.name,
|
|
421
|
+
linkName: fieldname,
|
|
422
|
+
backlink: link.backlink,
|
|
423
|
+
target: link.target,
|
|
424
|
+
};
|
|
425
|
+
const connectionField = reverseConnectionNameFn
|
|
426
|
+
? reverseConnectionNameFn(reverseParams)
|
|
427
|
+
: defaultReverseConnectionName(reverseParams);
|
|
428
|
+
const limitArg = effectiveFetch.method === 'sync' && effectiveFetch.limit !== undefined
|
|
429
|
+
? `first: ${effectiveFetch.limit}`
|
|
430
|
+
: effectiveFetch.method === 'sync'
|
|
431
|
+
? `first: ${DEFAULT_SYNC_LIMIT}`
|
|
432
|
+
: '';
|
|
433
|
+
selections.push(`
|
|
434
|
+
${connectionField}${limitArg ? `(${limitArg})` : ''} {
|
|
435
|
+
nodes {
|
|
436
|
+
${fullSelection}
|
|
437
|
+
}
|
|
438
|
+
}`);
|
|
439
|
+
}
|
|
440
|
+
else {
|
|
441
|
+
selections.push(`
|
|
442
|
+
${fieldname} {
|
|
443
|
+
${fullSelection}
|
|
444
|
+
}`);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return selections.join('');
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Build a GraphQL query to fetch a single record by ID.
|
|
451
|
+
* When includeNested is set, recursively includes descendant link sub-selections.
|
|
452
|
+
* @public
|
|
453
|
+
*/
|
|
454
|
+
function buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType, getMeta, options, reverseConnectionNameFn) {
|
|
455
|
+
const queryName = recordFieldName(meta.tableName);
|
|
456
|
+
const argName = recordArgName(meta.tableName);
|
|
457
|
+
const argType = recordArgType(meta.tableName);
|
|
458
|
+
const seen = new Set([meta.slug || meta.name]);
|
|
459
|
+
let selection = queryableFieldNames(meta);
|
|
460
|
+
if (options?.includeNested && meta.links) {
|
|
461
|
+
const includeSet = Array.isArray(options.includeNested) ? new Set(options.includeNested) : null;
|
|
462
|
+
const nestedSelections = buildNestedSelections({
|
|
463
|
+
links: meta.links,
|
|
464
|
+
meta,
|
|
465
|
+
includeSet,
|
|
466
|
+
getMeta,
|
|
467
|
+
seen,
|
|
468
|
+
depth: 0,
|
|
469
|
+
maxDepth: options.maxDepth,
|
|
470
|
+
reverseConnectionNameFn,
|
|
471
|
+
});
|
|
472
|
+
if (nestedSelections) {
|
|
473
|
+
selection += '\n ' + nestedSelections;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return `
|
|
477
|
+
query GetRecord($${argName}: ${argType}) {
|
|
478
|
+
${queryName}(${argName}: $${argName}) {
|
|
479
|
+
${selection}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
`;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Build a GraphQL connection query to fetch a list of records.
|
|
486
|
+
* Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,
|
|
487
|
+
* avoiding GraphQL spec §5.8.3 violations from unused variable declarations.
|
|
488
|
+
* Excludes Link and Doctype relation fields from the selection set.
|
|
489
|
+
* @public
|
|
490
|
+
*/
|
|
491
|
+
function buildListQuery(meta, args, connectionFieldName, orderByTypeName) {
|
|
492
|
+
const fieldNames = queryableFieldNames(meta);
|
|
493
|
+
const connectionName = connectionFieldName(meta.tableName);
|
|
494
|
+
const orderByType = orderByTypeName(meta.tableName);
|
|
495
|
+
const varDecls = [];
|
|
496
|
+
const queryArgs = [];
|
|
497
|
+
if (args.limit) {
|
|
498
|
+
varDecls.push('$limit: Int');
|
|
499
|
+
queryArgs.push(`first: $limit`);
|
|
500
|
+
}
|
|
501
|
+
if (args.offset) {
|
|
502
|
+
varDecls.push('$offset: Int');
|
|
503
|
+
queryArgs.push(`offset: $offset`);
|
|
504
|
+
}
|
|
505
|
+
if (args.orderBy) {
|
|
506
|
+
varDecls.push(`$orderBy: [${orderByType}!]`);
|
|
507
|
+
queryArgs.push(`orderBy: $orderBy`);
|
|
508
|
+
}
|
|
509
|
+
const varStr = varDecls.length > 0 ? `(${varDecls.join(', ')})` : '';
|
|
510
|
+
const argsStr = queryArgs.length > 0 ? `(${queryArgs.join(', ')})` : '';
|
|
511
|
+
return `
|
|
512
|
+
query GetRecords${varStr} {
|
|
513
|
+
${connectionName}${argsStr} {
|
|
514
|
+
nodes {
|
|
515
|
+
${fieldNames}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
`;
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Merge nested connection results into flat arrays.
|
|
523
|
+
* For `noneOrMany`/`atLeastOne` links, the query returns `{ nodes: [...] }`.
|
|
524
|
+
* This flattens them to just `[]` for easier consumption.
|
|
525
|
+
* @public
|
|
526
|
+
*/
|
|
527
|
+
function mergeNestedResults(params) {
|
|
528
|
+
const { record, meta, getMeta, reverseConnectionNameFn } = params;
|
|
529
|
+
if (!meta.links)
|
|
530
|
+
return record;
|
|
531
|
+
const merged = { ...record };
|
|
532
|
+
for (const [fieldname, link] of Object.entries(meta.links)) {
|
|
533
|
+
const isMany = isManyCardinality(link.cardinality);
|
|
534
|
+
if (isMany) {
|
|
535
|
+
const targetMeta = getMeta(link.target);
|
|
536
|
+
if (!targetMeta)
|
|
537
|
+
continue;
|
|
538
|
+
const reverseParams = {
|
|
539
|
+
doctype: meta.slug || meta.name,
|
|
540
|
+
linkName: fieldname,
|
|
541
|
+
backlink: link.backlink || fieldname,
|
|
542
|
+
target: link.target,
|
|
543
|
+
};
|
|
544
|
+
const connectionField = reverseConnectionNameFn
|
|
545
|
+
? reverseConnectionNameFn(reverseParams)
|
|
546
|
+
: defaultReverseConnectionName(reverseParams);
|
|
547
|
+
const connectionResult = merged[connectionField];
|
|
548
|
+
if (connectionResult?.nodes) {
|
|
549
|
+
merged[fieldname] = connectionResult.nodes;
|
|
550
|
+
delete merged[connectionField];
|
|
551
|
+
}
|
|
552
|
+
else {
|
|
553
|
+
merged[fieldname] = [];
|
|
554
|
+
delete merged[connectionField];
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return merged;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Extract a single record from a PostGraphile query result using the record field name.
|
|
562
|
+
* @public
|
|
563
|
+
*/
|
|
564
|
+
function extractSingleResult(params) {
|
|
565
|
+
const { result, meta, recordFieldName } = params;
|
|
566
|
+
const queryName = recordFieldName(meta.tableName);
|
|
567
|
+
return result[queryName];
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Extract the list of nodes from a PostGraphile connection query result.
|
|
571
|
+
* Returns an empty array if the connection field is absent.
|
|
572
|
+
* @public
|
|
573
|
+
*/
|
|
574
|
+
function extractListResult(params) {
|
|
575
|
+
const { result, meta, connectionFieldName } = params;
|
|
576
|
+
const connectionName = connectionFieldName(meta.tableName);
|
|
577
|
+
const connection = result[connectionName];
|
|
578
|
+
return connection?.nodes ?? [];
|
|
579
|
+
}
|
|
580
|
+
// =============================================================================
|
|
581
|
+
// Exported for testing and advanced usage
|
|
582
|
+
// =============================================================================
|
|
583
|
+
export { defaultRecordFieldName, defaultConnectionFieldName, defaultOrderByTypeName, defaultRecordArgName, defaultRecordArgType, defaultReverseConnectionName, buildRecordQuery, buildListQuery, queryableFieldNames, RELATION_FIELDTYPES, extractSingleResult, extractListResult, mergeNestedResults, };
|
package/dist/preset.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { PostGraphileAmberPreset } from 'postgraphile/presets/amber';
|
|
2
|
+
const StonecropFieldCasingPlugin = {
|
|
3
|
+
name: 'StonecropFieldCasingPlugin',
|
|
4
|
+
version: '0.0.0',
|
|
5
|
+
inflection: {
|
|
6
|
+
replace: {
|
|
7
|
+
attribute(previous, _options, details) {
|
|
8
|
+
return this.upperCamelCase(details.attributeName);
|
|
9
|
+
},
|
|
10
|
+
},
|
|
11
|
+
},
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Create a PostGraphile preset configured for Stonecrop.
|
|
15
|
+
*
|
|
16
|
+
* The returned preset extends PostGraphile Amber, which provides PostgreSQL integration,
|
|
17
|
+
* Relay-style connections, and the standard PostGraphile schema structure. Stonecrop's
|
|
18
|
+
* `createStonecropPlugin` should be added to the `plugins` array to enable Stonecrop's
|
|
19
|
+
* `stonecropRecord`, `stonecropRecords`, `stonecropMeta`, and `stonecropAction` resolvers.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```typescript
|
|
23
|
+
* import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'
|
|
24
|
+
*
|
|
25
|
+
* const preset = createStonecropPreset({ fieldCasing: 'camel' })
|
|
26
|
+
* preset.pgServices = [makePgService({ connectionString: process.env.DATABASE_URL, schemas: ['public'] })]
|
|
27
|
+
* preset.plugins = [createStonecropPlugin()]
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @param options - Optional configuration for field casing
|
|
31
|
+
* @public
|
|
32
|
+
*/
|
|
33
|
+
export const createStonecropPreset = (options) => ({
|
|
34
|
+
extends: [PostGraphileAmberPreset],
|
|
35
|
+
plugins: options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : [],
|
|
36
|
+
});
|
|
37
|
+
/**
|
|
38
|
+
* Default Stonecrop preset with camelCase field names.
|
|
39
|
+
*
|
|
40
|
+
* Convenience alias for `createStonecropPreset()` — equivalent to `createStonecropPreset({ fieldCasing: 'camel' })`.
|
|
41
|
+
* Use this for a minimal setup when no custom options are needed.
|
|
42
|
+
*
|
|
43
|
+
* @public
|
|
44
|
+
*/
|
|
45
|
+
export const StonecropPreset = createStonecropPreset();
|