@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.
@@ -1,17 +1,20 @@
1
1
  import { DoctypeMeta } from '@stonecrop/schema';
2
2
  import { DocumentNode } from 'graphql';
3
3
  import { GraphileConfig as GraphileConfig_2 } from 'postgraphile/graphile-build';
4
+ import type { LinkDeclaration } from '@stonecrop/schema';
5
+ import { makePgService } from 'postgraphile/adaptors/pg';
6
+ import type { PgClient } from '@dataplan/pg';
4
7
  import { ValidationError } from '@stonecrop/schema';
5
8
 
6
9
  /**
7
- * Context passed to action handlers
10
+ * Context passed to action handlers.
8
11
  * @public
9
12
  */
10
13
  export declare interface ActionContext {
11
14
  /** Doctype metadata for the action being executed */
12
15
  doctype: DoctypeMeta;
13
- /** GraphQL executor for running queries/mutations within the action */
14
- executor: GraphQLExecutor;
16
+ /** Active database client — available when the action is dispatched via stonecropAction */
17
+ pgClient?: PgClient;
15
18
  /** Additional context properties */
16
19
  [key: string]: unknown;
17
20
  }
@@ -23,50 +26,16 @@ export declare interface ActionContext {
23
26
  export declare type ActionHandler = (args: unknown[], context: ActionContext) => Promise<unknown>;
24
27
 
25
28
  /**
26
- * Build a GraphQL connection query to fetch a list of records.
27
- * Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,
28
- * avoiding GraphQL spec §5.8.3 violations from unused variable declarations.
29
- * Excludes Link relation fields and Display fields from the selection set.
30
- * @public
31
- */
32
- export declare function buildListQuery(meta: DoctypeMeta, args: BuildListQueryArgs, connectionFieldName: (t: string) => string, orderByTypeName: (t: string) => string): string;
33
-
34
- /**
35
- * Arguments for buildListQuery
36
- * @public
37
- */
38
- export declare interface BuildListQueryArgs {
39
- /** Maximum number of records to return */
40
- limit?: number;
41
- /** Number of records to skip */
42
- offset?: number;
43
- /** OrderBy specification */
44
- orderBy?: string;
45
- }
46
-
47
- /**
48
- * Build a GraphQL query to fetch a single record by ID.
49
- * When includeNested is set, recursively includes descendant link sub-selections.
50
- * @public
51
- */
52
- export declare function buildRecordQuery(meta: DoctypeMeta, recordFieldName: (t: string) => string, recordArgName: (t: string) => string, recordArgType: (t: string) => string, getMeta: (slug: string) => DoctypeMeta | undefined, options?: BuildRecordQueryOptions, reverseConnectionNameFn?: (params: ReverseConnectionParams) => string): string;
53
-
54
- /**
55
- * Options for buildRecordQuery nested selection building
29
+ * Built-in handlers available for registration
56
30
  * @public
57
31
  */
58
- export declare interface BuildRecordQueryOptions {
59
- /** Include nested/related records */
60
- includeNested?: boolean | string[];
61
- /** Maximum nesting depth */
62
- maxDepth?: number;
63
- }
32
+ export declare const builtinHandlers: Record<string, ActionHandler>;
64
33
 
65
34
  /**
66
- * Built-in handlers available for registration
35
+ * Remove all registered fetch handlers. Primarily for test isolation.
67
36
  * @public
68
37
  */
69
- export declare const builtinHandlers: Record<string, ActionHandler>;
38
+ export declare function clearFetchHandlers(): void;
70
39
 
71
40
  /**
72
41
  * Clear all registered handlers
@@ -81,62 +50,72 @@ export declare function clearHandlers(): void;
81
50
  export declare function clearRegistry(): void;
82
51
 
83
52
  /**
84
- * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality
85
- * @param options - Plugin configuration options
53
+ * Creates a PostGraphile plugin that wraps Stonecrop resolver plans with
54
+ * debug logging. Use it in your preset file:
55
+ *
56
+ * ```typescript
57
+ * import { createStonecropPlugin, createDebugPlugin } from '@stonecrop/graphql-middleware'
58
+ *
59
+ * export default {
60
+ * plugins: [createStonecropPlugin(), createDebugPlugin()],
61
+ * }
62
+ * ```
63
+ *
64
+ * Place `createDebugPlugin()` **after** `createStonecropPlugin()` in the
65
+ * plugins array so the wrapper sees the Stonecrop fields.
66
+ *
67
+ * @param options - Optional logging configuration
86
68
  * @returns A PostGraphile plugin
87
69
  * @public
88
70
  */
89
- export declare const createStonecropPlugin: (options: StonecropPluginOptions) => GraphileConfig_2.Plugin;
90
-
91
- /**
92
- * Amber default: sales_orders → allSalesOrders
93
- * @public
94
- */
95
- export declare function defaultConnectionFieldName(tableName: string): string;
71
+ export declare const createDebugPlugin: (options?: DebugPluginOptions) => GraphileConfig.Plugin;
96
72
 
97
73
  /**
98
- * Amber default: sales_orders → SalesOrdersOrderBy
99
- * @public
100
- */
101
- export declare function defaultOrderByTypeName(tableName: string): string;
102
-
103
- /**
104
- * Default PK argument name: 'id' (standard Relay Global ID pattern).
105
- * Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;
106
- * PostGraphile Amber generates `rowId: UUID!` for those fields.
107
- * @public
108
- */
109
- export declare function defaultRecordArgName(_tableName: string): string;
110
-
111
- /**
112
- * Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).
113
- * Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs
114
- * such as integer serials or Relay Global IDs ('ID!').
74
+ * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
75
+ *
76
+ * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`
77
+ * during schema construction — it does not need to be supplied by the caller.
78
+ *
79
+ * @param options - Optional plugin configuration
80
+ * @returns A PostGraphile plugin
115
81
  * @public
116
82
  */
117
- export declare function defaultRecordArgType(_tableName: string): string;
83
+ export declare const createStonecropPlugin: (options?: StonecropPluginOptions) => GraphileConfig_2.Plugin;
118
84
 
119
85
  /**
120
- * Amber default: sales_orders → salesOrderById
121
- * Uses `pluralize` for proper singularization of irregular plurals.
122
- * Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.
86
+ * Creates a Stonecrop-flavoured PostGraphile preset.
87
+ *
88
+ * The returned preset extends `PostGraphileAmberPreset` and applies Stonecrop's
89
+ * recommended defaults. Pass it to `extends` in your PostGraphile configuration:
90
+ *
91
+ * ```typescript
92
+ * import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'
93
+ *
94
+ * export default {
95
+ * extends: [createStonecropPreset()],
96
+ * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL, schemas: ['public'] })],
97
+ * plugins: [createStonecropPlugin()],
98
+ * }
99
+ * ```
100
+ *
101
+ * @param options - Optional configuration. Pass `{ fieldCasing: 'pascal' }` to enable
102
+ * `MyColumn`-style field names instead of the default `myColumn` (camelCase).
123
103
  * @public
124
104
  */
125
- export declare function defaultRecordFieldName(tableName: string): string;
105
+ export declare const createStonecropPreset: (options?: {
106
+ fieldCasing?: FieldCasing;
107
+ }) => GraphileConfig.Preset;
126
108
 
127
109
  /**
128
- * Default reverse connection name: derives PostGraphile's connection field convention.
129
- * PostGraphile convention: `{targetPlural}By{FkColumnPascal}Id`
130
- * - When backlink is defined: FK column is derived from the backlink field name
131
- * - When backlink is absent: FK column is derived from the parent doctype's table name
110
+ * Options for the Stonecrop debug plugin.
132
111
  * @public
133
112
  */
134
- export declare function defaultReverseConnectionName(params: {
135
- doctype: string;
136
- linkName: string;
137
- backlink?: string;
138
- target: string;
139
- }): string;
113
+ export declare interface DebugPluginOptions {
114
+ /** Log a message when a plan is built for a Stonecrop field. Default: `true` */
115
+ logPlans?: boolean;
116
+ /** Log timing for plan construction. Default: `false` */
117
+ logTiming?: boolean;
118
+ }
140
119
 
141
120
  export { DoctypeMeta }
142
121
 
@@ -157,49 +136,41 @@ export declare class DoctypeValidationError extends Error {
157
136
  }
158
137
 
159
138
  /**
160
- * Extract the list of nodes from a PostGraphile connection query result.
161
- * Returns an empty array if the connection field is absent.
162
- * @public
163
- */
164
- export declare function extractListResult(params: ExtractListResultParams): unknown[];
165
-
166
- /**
167
- * Parameters for extractListResult
139
+ * Handler for a custom fetch strategy on a link declaration.
140
+ * Called during `stonecropRecord` resolution when `link.fetch.method === 'custom'`.
141
+ *
142
+ * @param pgClient - Active database client for the current request
143
+ * @param parentRecord - Resolved parent record (scalar fields already populated)
144
+ * @param link - The link declaration, giving access to cardinality and other metadata
145
+ * @returns A single linked record or an array depending on `link.cardinality`
168
146
  * @public
169
147
  */
170
- export declare interface ExtractListResultParams {
171
- /** The raw query result */
172
- result: unknown;
173
- /** Doctype metadata */
174
- meta: DoctypeMeta;
175
- /** Function to derive the connection field name from a table name */
176
- connectionFieldName: (tableName: string) => string;
177
- }
148
+ export declare type FetchHandler = (pgClient: PgClient, parentRecord: Record<string, unknown>, link: LinkDeclaration) => Promise<Record<string, unknown> | Record<string, unknown>[]>;
178
149
 
179
150
  /**
180
- * Extract a single record from a PostGraphile query result using the record field name.
151
+ * Controls how PostgreSQL column names are mapped to GraphQL field names in the synthesized preset.
152
+ *
153
+ * - `'camel'` (default): `my_column` → `myColumn`. This matches PostGraphile Amber's built-in behaviour.
154
+ * - `'pascal'`: `my_column` → `MyColumn`. Opt in via `createStonecropPreset({ fieldCasing: 'pascal' })` or
155
+ * `grafserv.fieldCasing: 'pascal'` in `nuxt.config.ts`.
156
+ *
157
+ * Smart tag overrides (`@name` on column comments) are respected regardless of this setting.
181
158
  * @public
182
159
  */
183
- export declare function extractSingleResult(params: ExtractSingleResultParams): unknown;
160
+ export declare type FieldCasing = 'camel' | 'pascal';
184
161
 
185
162
  /**
186
- * Parameters for extractSingleResult
163
+ * Get all loaded doctypes
187
164
  * @public
188
165
  */
189
- export declare interface ExtractSingleResultParams {
190
- /** The raw query result */
191
- result: unknown;
192
- /** Doctype metadata */
193
- meta: DoctypeMeta;
194
- /** Function to derive the record field name from a table name */
195
- recordFieldName: (tableName: string) => string;
196
- }
166
+ export declare function getAllMeta(): DoctypeMeta[];
197
167
 
198
168
  /**
199
- * Get all loaded doctypes
169
+ * Retrieve a registered fetch handler by name.
170
+ * Returns `undefined` if no handler has been registered under that name.
200
171
  * @public
201
172
  */
202
- export declare function getAllMeta(): DoctypeMeta[];
173
+ export declare function getFetchHandler(name: string): FetchHandler | undefined;
203
174
 
204
175
  /**
205
176
  * Get a registered handler by name
@@ -215,17 +186,6 @@ export declare function getHandler(name: string): ActionHandler | undefined;
215
186
  */
216
187
  export declare function getMeta(name: string): DoctypeMeta | undefined;
217
188
 
218
- /**
219
- * GraphQL executor interface for running queries/mutations
220
- * @public
221
- */
222
- export declare interface GraphQLExecutor {
223
- /** Execute a GraphQL query */
224
- query<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T>;
225
- /** Execute a GraphQL mutation */
226
- mutate<T = unknown>(mutation: string, variables?: Record<string, unknown>): Promise<T>;
227
- }
228
-
229
189
  /**
230
190
  * Check if a handler is registered
231
191
  * @param name - Name of the action handler to check
@@ -267,43 +227,20 @@ export declare interface LoadDoctypesOptions {
267
227
  onError?: (file: string, errors: ValidationError[]) => void;
268
228
  }
269
229
 
270
- /**
271
- * Merge nested connection results into flat arrays.
272
- * For `noneOrMany`/`atLeastOne` links, the query returns `{ nodes: [...] }`.
273
- * This flattens them to just `[]` for easier consumption.
274
- * @public
275
- */
276
- export declare function mergeNestedResults(params: MergeNestedResultsParams): Record<string, unknown>;
277
-
278
- /**
279
- * Parameters for mergeNestedResults
280
- * @public
281
- */
282
- export declare interface MergeNestedResultsParams {
283
- /** The record object with nested connection data */
284
- record: Record<string, unknown>;
285
- /** Doctype metadata */
286
- meta: DoctypeMeta;
287
- /** Lookup function to get doctype metadata by slug */
288
- getMeta: (slug: string) => DoctypeMeta | undefined;
289
- /** Function to derive the reverse connection field name from link params */
290
- reverseConnectionNameFn?: (params: ReverseConnectionParams) => string;
291
- }
230
+ export { makePgService }
292
231
 
293
232
  /**
294
- * Filter fields to only those directly queryable as scalars.
295
- * Excludes Display fields (no backing DB column) and Link fields that have an
296
- * explicit `links` declaration (those require sub-selection, not scalar reads).
297
- * Link fields without a `links` declaration are scalar FK UUID columns and ARE included.
233
+ * Register all built-in handlers
298
234
  * @public
299
235
  */
300
- export declare function queryableFieldNames(meta: DoctypeMeta): string;
236
+ export declare function registerBuiltinHandlers(): void;
301
237
 
302
238
  /**
303
- * Register all built-in handlers
239
+ * Register a custom fetch handler by name.
240
+ * The name must match the `handler` field on a `CustomFetch` strategy declaration.
304
241
  * @public
305
242
  */
306
- export declare function registerBuiltinHandlers(): void;
243
+ export declare function registerFetchHandler(name: string, handler: FetchHandler): void;
307
244
 
308
245
  /**
309
246
  * Register an action handler
@@ -314,112 +251,42 @@ export declare function registerBuiltinHandlers(): void;
314
251
  export declare function registerHandler(name: string, handler: ActionHandler): void;
315
252
 
316
253
  /**
317
- * Fieldtypes unconditionally excluded from the generated scalar query selection set.
318
- * - `'Display'`: display-only composite component with no backing DB column
319
- *
320
- * Note: `'Link'` fields are NOT blanket-excluded here. Scalar FK UUID columns use
321
- * `fieldtype: 'Link'` and ARE queryable. Only Link fields that also appear in the
322
- * doctype's `links` declaration (i.e. those that resolve to a sub-object or connection)
323
- * are excluded — that logic lives in `queryableFieldNames`.
324
- * @public
325
- */
326
- export declare const RELATION_FIELDTYPES: Set<string>;
327
-
328
- /**
329
- * Parameters for reverse connection name inflection
330
- * @public
331
- */
332
- export declare interface ReverseConnectionParams {
333
- /** Parent doctype slug */
334
- doctype: string;
335
- /** Link key on the parent */
336
- linkName: string;
337
- /** Link field on the target that points back to the parent (optional) */
338
- backlink?: string;
339
- /** Target doctype slug */
340
- target: string;
341
- }
342
-
343
- /**
344
- * Inflection callbacks for mapping table names to GraphQL query field names.
345
- * Override these when using a non-Amber inflection preset (e.g., V4, SimplifyInflection).
346
- *
347
- * Defaults match the PostGraphile Amber preset conventions.
254
+ * Options for creating a Stonecrop PostGraphile plugin.
348
255
  * @public
349
256
  */
350
- export declare interface StonecropInflectionConfig {
351
- /**
352
- * Given a table name, return the GraphQL field name for fetching a single record by ID.
353
- * @example Amber default: "sales_orders" → "salesOrderById"
354
- * @example V4 preset: "sales_orders" → "salesOrderByRowId"
355
- */
356
- recordFieldName?: (tableName: string) => string;
357
- /**
358
- * Given a table name, return the GraphQL field name for fetching a list/connection.
359
- * @example Amber default: "sales_orders" → "allSalesOrders"
360
- * @example SimplifyInflection: "sales_orders" → "salesOrders"
361
- */
362
- connectionFieldName?: (tableName: string) => string;
363
- /**
364
- * Given a table name, return the GraphQL OrderBy enum type name.
365
- * @example Amber default: "sales_orders" → "SalesOrdersOrderBy"
366
- */
367
- orderByTypeName?: (tableName: string) => string;
368
- /**
369
- * Given a table name, return the GraphQL argument name used to look up a record by PK.
370
- * @example Amber default (Relay Global ID): "sales_orders" → "id"
371
- * @example row_id PK: "sales_orders" → "rowId"
372
- */
373
- recordArgName?: (tableName: string) => string;
257
+ export declare interface StonecropPluginOptions {
374
258
  /**
375
- * Given a table name, return the GraphQL variable type for the PK argument.
376
- * @example Default UUID PK: "sales_orders" → "UUID!"
377
- * @example Integer PK: "sales_orders" → "Int!"
259
+ * When `true`, SQL queries executed inside `loadOneWithPgClient` callbacks
260
+ * are logged to `console.log` with `[@stonecrop/graphql-middleware]` prefix. Defaults to `false`.
378
261
  */
379
- recordArgType?: (tableName: string) => string;
262
+ debug?: boolean;
380
263
  /**
381
- * Derive the GraphQL connection field name for a reverse-FK link.
382
- * PostGraphile convention: `{targetPlural}By{FkColumnPascal}Id`
383
- * - When backlink is provided: FK column is derived from the backlink field
384
- * - When backlink is absent: FK column is derived from the parent doctype
385
- * @example Recipe → RecipeTasksByRecipeId
264
+ * Override the PostgreSQL FROM clause target for specific doctypes, keyed by doctype name.
265
+ * Values may be a bare table name (`'plan'`) or a schema-qualified name (`'orpin.plan'`).
266
+ * SQL fragments and subqueries are not supported.
267
+ * When absent for a doctype, the table name is derived as `camelToSnake(doctype.name)`.
386
268
  */
387
- reverseConnectionName?: (params: {
388
- /** Parent doctype slug */
389
- doctype: string;
390
- /** Link key on the parent */
391
- linkName: string;
392
- /** Link field on the target that points back to the parent (optional) */
393
- backlink?: string;
394
- /** Target doctype slug */
395
- target: string;
396
- }) => string;
269
+ tables?: Record<string, string>;
397
270
  }
398
271
 
399
272
  /**
400
- * Options for creating a Stonecrop PostGraphile plugin
401
- * @public
402
- */
403
- export declare interface StonecropPluginOptions {
404
- /** GraphQL executor for running queries/mutations */
405
- executor: GraphQLExecutor;
406
- /**
407
- * Override inflection conventions for mapping table names to GraphQL field names.
408
- * Defaults to PostGraphile Amber preset conventions.
409
- */
410
- inflection?: StonecropInflectionConfig;
411
- }
412
-
413
- /**
414
- * Options for stonecropRecord queries
273
+ * The default Stonecrop PostGraphile preset with camelCase field names.
274
+ *
275
+ * Equivalent to `createStonecropPreset()` with no options. Use this when you
276
+ * do not need to customise field casing:
277
+ *
278
+ * ```typescript
279
+ * import { StonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'
280
+ *
281
+ * export default {
282
+ * extends: [StonecropPreset],
283
+ * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],
284
+ * plugins: [createStonecropPlugin()],
285
+ * }
286
+ * ```
415
287
  * @public
416
288
  */
417
- export declare interface StonecropRecordOptions {
418
- /** Include nested/related records */
419
- includeNested?: boolean | string[];
420
- /** Maximum nesting depth */
421
- maxDepth?: number;
422
- }
289
+ export declare const StonecropPreset: GraphileConfig.Preset;
423
290
 
424
291
  /**
425
292
  * GraphQL type definitions for Stonecrop's middleware API.