@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 CHANGED
@@ -1,84 +1,108 @@
1
1
  # @stonecrop/graphql-middleware
2
2
 
3
- GraphQL backend for the Stonecrop framework. Reads doctype schemas and exposes them as GraphQL resolvers that handle query construction, response parsing, and action dispatch.
4
-
5
- Currently integrated with PostGraphile (to be extracted into a swappable adapter in the future).
3
+ GraphQL backend for the Stonecrop framework. Reads doctype schemas and exposes them as PostGraphile plan-step resolvers that handle record fetching, fetch-strategy dispatch, and action execution.
6
4
 
7
5
  ## What it does
8
6
 
9
- - **Query construction** — Builds GraphQL queries from doctype metadata, respecting fetch strategies and nesting depth
10
- - **Response merging** — Flattens connection format (`{ nodes: [...] }`) into plain arrays
11
- - **Action dispatch** — Routes doctype actions to registered handlers
12
-
13
- ## How it works
14
-
15
- Doctype schemas declare fields, relationships, and workflow. The middleware uses that schema to:
16
-
17
- 1. Accept a `doctype` and optional `options` from the client
18
- 2. Build a query with field selections and (if `includeNested` is set) nested sub-selections for related records
19
- 3. Execute against the GraphQL engine and merge the response
20
- 4. Return flat data to the client
21
-
22
- The client never constructs queries — it passes `includeNested` through and receives pre-merged results.
7
+ - **Record fetching** — Resolves `stonecropRecord` and `stonecropRecords` via direct parameterised SQL, batched via `loadOneWithPgClient` from `@dataplan/pg`
8
+ - **Fetch-strategy dispatch** — For `stonecropRecord`, iterates `meta.links` and applies `sync` / `lazy` / `custom` strategies; sync links issue additional SQL and merge results into the record; lazy links are absent from the response
9
+ - **Action dispatch** — Routes doctype actions to registered handlers via `sideEffectWithPgClient`
10
+ - **Preset** — `createStonecropPreset()` wraps `PostGraphileAmberPreset` so user apps never import from PostGraphile directly
23
11
 
24
12
  ## Setup
25
13
 
26
- The middleware is a PostGraphile plugin. It needs an executor to bridge between the middleware's query strings and your GraphQL engine:
27
-
28
14
  ```typescript
29
- import { createServer } from 'postgraphile/grafserv/h3/v1'
30
- import { PostGraphileAmberPreset } from 'postgraphile/presets/amber'
31
- import { makePgService } from 'postgraphile/adaptors/pg'
32
- import { graphql } from 'graphql'
33
15
  import {
16
+ createStonecropPreset,
34
17
  createStonecropPlugin,
18
+ makePgService,
35
19
  loadDoctypes,
36
20
  registerBuiltinHandlers,
37
21
  } from '@stonecrop/graphql-middleware'
38
22
 
39
- // Scan doctype JSON files and register them with the middleware
40
23
  loadDoctypes('./doctypes')
41
-
42
- // Register built-in action handlers (submit, approve, etc.)
43
24
  registerBuiltinHandlers()
44
25
 
45
- // Executor bridges the middleware's query strings and your GraphQL engine
46
- const executor = {
47
- async query(query: string, variables?: Record<string, unknown>) {
48
- return graphql({ schema, source: query, variableValues: variables })
49
- },
50
- async mutate(mutation: string, variables?: Record<string, unknown>) {
51
- return graphql({ schema, source: mutation, variableValues: variables })
52
- },
26
+ const preset: GraphileConfig.Preset = {
27
+ extends: [createStonecropPreset()],
28
+ plugins: [createStonecropPlugin()],
29
+ pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],
53
30
  }
31
+ ```
54
32
 
55
- // PostGraphile configuration
56
- const preset: GraphileConfig.Preset = {
57
- extends: [PostGraphileAmberPreset], // Base preset with PostgreSQL integration
58
- plugins: [createStonecropPlugin({ executor })], // Stonecrop GraphQL resolvers
59
- pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })], // Database connection
33
+ `createStonecropPlugin()` discovers the `PgExecutor` automatically from `pgServices` — no executor argument is needed. An optional `StonecropPluginOptions` object accepts:
34
+
35
+ | Option | Default | Description |
36
+ |--------|---------|-------------|
37
+ | `pkField` | `'id'` | Primary key column name for record lookups |
38
+
39
+ ## Debugging
40
+
41
+ ### Nuxt module shortcut
42
+
43
+ When using `@stonecrop/nuxt-grafserv`, set `debug: true` in `nuxt.config.ts` to enable all development aids at once:
44
+
45
+ ```typescript
46
+ export default defineNuxtConfig({
47
+ grafserv: {
48
+ type: 'postgraphile',
49
+ debug: true,
50
+ },
51
+ })
52
+ ```
53
+
54
+ `debug: true` automatically:
55
+ - Enables the **Ruru Explain** tab (`grafast.explain`) to inspect Grafast plan steps and generated SQL
56
+ - Injects `createDebugPlugin()` to log Stonecrop resolver plan construction
57
+ - Configures `grafserv.maskError` using PostGraphile's recommended pattern: logs every error server-side, returns `GraphQLError` and safe errors directly, and masks unknown errors with a SHA-1 hash
58
+
59
+ **Never enable `debug` in production** — it exposes query internals and detailed error messages to clients.
60
+
61
+ ### Custom preset
62
+
63
+ If you manage your own preset file, import the debug plugin directly:
64
+
65
+ ```typescript
66
+ import { createStonecropPlugin, createDebugPlugin } from '@stonecrop/graphql-middleware'
67
+
68
+ export default {
69
+ plugins: [createStonecropPlugin(), createDebugPlugin()],
70
+ grafast: { explain: true },
60
71
  }
61
72
  ```
62
73
 
63
- The middleware builds PostGraphile-formatted query strings (e.g., `SalesOrderById`, `SalesOrderItemsBySalesOrderId`). The executor runs them — it doesn't control what queries are constructed.
74
+ ### Environment variables
75
+
76
+ PostGraphile's native `DEBUG` variables still work alongside Stonecrop's debug plugin:
77
+
78
+ | Variable | What it shows |
79
+ |----------|---------------|
80
+ | `DEBUG="@dataplan/pg:PgExecutor"` | SQL queries executed by plan steps |
81
+ | `DEBUG="@dataplan/pg:PgExecutor:explain"` | SQL plus `EXPLAIN` output |
82
+ | `DEBUG="graphile-build:warn"` | Warnings during schema construction |
83
+ | `DEBUG="graphile-build:SchemaBuilder"` | Hook execution order during schema build |
84
+
85
+ ```bash
86
+ DEBUG="@dataplan/pg:PgExecutor:explain,graphile-build:warn" node server.js
87
+ ```
64
88
 
65
89
  ## Doctype Schemas
66
90
 
67
- The middleware loads doctype definitions from JSON files. Each file defines a doctype's structure:
91
+ Each doctype JSON file defines structure, relationships, and workflow:
68
92
 
69
93
  ```json
70
94
  {
71
95
  "name": "SalesOrder",
72
- "tableName": "sales_orders",
73
96
  "fields": [
74
- { "fieldname": "id", "fieldtype": "UUID" },
97
+ { "fieldname": "id", "fieldtype": "Data" },
75
98
  { "fieldname": "status", "fieldtype": "Select" }
76
99
  ],
77
100
  "links": {
78
101
  "items": {
79
102
  "target": "sales-order-item",
80
103
  "cardinality": "noneOrMany",
81
- "backlink": "sales_order"
104
+ "backlink": "sales_order_id",
105
+ "fetch": { "method": "sync", "limit": 100 }
82
106
  }
83
107
  },
84
108
  "workflow": {
@@ -90,49 +114,64 @@ The middleware loads doctype definitions from JSON files. Each file defines a do
90
114
  }
91
115
  ```
92
116
 
93
- The `links` object declares relationships used when `includeNested` is requested. The `workflow` object enables action dispatch.
117
+ ### Fetch strategies
118
+
119
+ Each entry in `links` can declare a `fetch` strategy:
120
+
121
+ | Strategy | Behaviour |
122
+ |----------|-----------|
123
+ | `{ "method": "sync", "limit": N }` | Linked records are fetched in the same resolver call and merged into `data` |
124
+ | `{ "method": "lazy" }` | Link is absent from the response; client retrieves it via `stonecropRecords` with `filters` |
125
+ | `{ "method": "custom", "handler": "myHandler" }` | Calls a registered fetch handler (see below) |
126
+
127
+ When `fetch` is omitted, `noneOrMany`/`atLeastOne` links default to `sync` (limit 50) and `atMostOne`/`one` links default to `lazy`.
94
128
 
95
129
  ### Display-only fields
96
130
 
97
- Fields with `fieldtype: "Display"` are excluded from the auto-generated scalar query. Use this for composite UI components (e.g. a canvas visualisation) that have no backing database column:
131
+ Fields with `fieldtype: "Display"` have no backing database column and are excluded from all SQL queries:
98
132
 
99
133
  ```json
100
134
  { "fieldname": "planner", "fieldtype": "Display", "component": "Planner", "label": "Resource Planner" }
101
135
  ```
102
136
 
103
- All other non-`Link` fieldtypes are assumed to map to a scalar DB column and are included in the query.
104
-
105
- ## Architecture
106
-
107
- ### Why the middleware builds queries
108
-
109
- The client (`@stonecrop/graphql-client`) is intentionally transport-only — it sends requests and receives flat data. It never constructs GraphQL queries. All query generation lives in the middleware, which is the only layer aware of PostGraphile naming conventions (inflection).
110
-
111
- This boundary exists because PostGraphile's schema naming is configurable. A single application might use `ById` for UUID primary keys, `ByRowId` for `row_id` columns, or entirely custom conventions. If the client hardcoded any of these conventions, it would silently generate wrong queries for any non-default setup. By keeping query construction server-side, the middleware's `StonecropInflectionConfig` becomes the single source of truth.
112
-
113
137
  ## Actions
114
138
 
115
- Actions are custom logic triggered by the client. Register handlers with `registerHandler`:
139
+ Register action handlers with `registerHandler`. Handlers receive the action arguments and an `ActionContext` that includes the active `PgClient`:
116
140
 
117
141
  ```typescript
142
+ import { registerHandler } from '@stonecrop/graphql-middleware'
143
+
118
144
  registerHandler('submitOrder', async (args, ctx) => {
119
145
  const [orderId] = args as [string]
146
+ // ctx.pgClient is available for additional database work
120
147
  return { submitted: true }
121
148
  })
122
149
  ```
123
150
 
124
- The `args` are passed from the client, and `ctx` provides the doctype metadata and GraphQL executor.
151
+ ## Custom fetch handlers
125
152
 
126
- ## API
153
+ Register custom fetch handlers for links that use `{ "method": "custom" }`:
154
+
155
+ ```typescript
156
+ import { registerFetchHandler } from '@stonecrop/graphql-middleware'
157
+
158
+ registerFetchHandler('loadLineItems', async (pgClient, parentRecord, link) => {
159
+ // Returns a single record or an array depending on link.cardinality
160
+ const { rows } = await pgClient.query(...)
161
+ return rows
162
+ })
163
+ ```
127
164
 
128
- The middleware exposes these GraphQL operations:
165
+ ## API
129
166
 
130
167
  | Operation | Description |
131
168
  |-----------|-------------|
132
- | `stonecropRecord(doctype, id, options?)` | Fetch a single record, optionally with nested links |
133
- | `stonecropRecords(doctype, filters?, orderBy?, limit?, offset?, options?)` | Fetch multiple records |
169
+ | `stonecropRecord(doctype, id, options?)` | Fetch a single record; `options.includeNested` controls which links are resolved |
170
+ | `stonecropRecords(doctype, filters?, orderBy?, limit?, offset?)` | Fetch a list with optional filtering and ordering |
134
171
  | `stonecropMeta(doctype)` | Fetch doctype metadata |
135
- | `stonecropAllMeta` | Fetch all doctype metadata |
172
+ | `stonecropAllMeta` | Fetch all registered doctype metadata |
136
173
  | `stonecropAction(doctype, action, args?)` | Execute a doctype action |
137
174
 
138
- For type signatures and detailed parameters, see [API Reference](./api.md).
175
+ `stonecropRecords` accepts `orderBy` as `FIELD_ASC` or `FIELD_DESC` (e.g. `"status_ASC"`). The field name is validated against the doctype's known fields before interpolation.
176
+
177
+ For full type signatures see [API Reference](./api.md).