@openreachtech/hora-skills-ort-renchan 0.0.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/LICENSE +201 -0
- package/README.ja.md +135 -0
- package/README.md +135 -0
- package/dist/skills/hor-agent-loop/SKILL.md +123 -0
- package/dist/skills/hor-agent-loop/references/core.md +485 -0
- package/dist/skills/hor-agent-loop/references/graphql-integration.md +178 -0
- package/dist/skills/hor-agent-loop/references/renchan-job-integration.md +368 -0
- package/dist/skills/hor-agent-loop/references/testing.md +492 -0
- package/dist/skills/hor-ai-agent-structure/SKILL.md +403 -0
- package/dist/skills/hor-ai-agent-structure/references/loop-and-actions.md +100 -0
- package/dist/skills/hor-ai-prompt-document-store/SKILL.md +220 -0
- package/dist/skills/hor-ai-prompt-document-store/references/models-and-composition.md +156 -0
- package/dist/skills/hor-backend-testing/SKILL.md +118 -0
- package/dist/skills/hor-backend-testing/references/placement-and-ordering.md +89 -0
- package/dist/skills/hor-backend-testing/references/purity-and-mocks.md +82 -0
- package/dist/skills/hor-backend-testing/references/running-tests.md +186 -0
- package/dist/skills/hor-bank-id/SKILL.md +91 -0
- package/dist/skills/hor-build-e2e-test-environment/SKILL.md +609 -0
- package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +368 -0
- package/dist/skills/hor-build-e2e-test-environment/references/edge-and-proxy.md +287 -0
- package/dist/skills/hor-build-e2e-test-environment/references/environment-and-ports.md +201 -0
- package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +330 -0
- package/dist/skills/hor-build-e2e-test-environment/references/seed-data.md +145 -0
- package/dist/skills/hor-build-e2e-test-environment/references/windows-runner.md +146 -0
- package/dist/skills/hor-constant-definition/SKILL.md +139 -0
- package/dist/skills/hor-cookie-authentication/SKILL.md +33 -0
- package/dist/skills/hor-cookie-authentication/references/auth-filter.md +55 -0
- package/dist/skills/hor-cookie-authentication/references/cookie-context.md +53 -0
- package/dist/skills/hor-cookie-authentication/references/dev-login-seeder.md +22 -0
- package/dist/skills/hor-cookie-authentication/references/environment.md +64 -0
- package/dist/skills/hor-cookie-authentication/references/error-codes.md +24 -0
- package/dist/skills/hor-cookie-authentication/references/migrations.md +18 -0
- package/dist/skills/hor-cookie-authentication/references/resolvers.md +97 -0
- package/dist/skills/hor-cookie-authentication/references/session-clerk.md +41 -0
- package/dist/skills/hor-cookie-authentication/references/token-models.md +125 -0
- package/dist/skills/hor-database-design/SKILL.md +54 -0
- package/dist/skills/hor-database-design/references/column-types.md +92 -0
- package/dist/skills/hor-database-design/references/datetimes.md +88 -0
- package/dist/skills/hor-database-design/references/master-tables.md +117 -0
- package/dist/skills/hor-database-design/references/normalization.md +40 -0
- package/dist/skills/hor-database-design/references/update-history.md +35 -0
- package/dist/skills/hor-execution-placement-pattern/SKILL.md +216 -0
- package/dist/skills/hor-external-api-client/SKILL.md +99 -0
- package/dist/skills/hor-external-api-client/references/architecture.md +127 -0
- package/dist/skills/hor-external-api-client/references/authorization.md +105 -0
- package/dist/skills/hor-external-api-client/references/capsule.md +130 -0
- package/dist/skills/hor-external-api-client/references/conventions.md +68 -0
- package/dist/skills/hor-external-api-client/references/launcher.md +138 -0
- package/dist/skills/hor-external-api-client/references/payload.md +176 -0
- package/dist/skills/hor-external-api-client/references/sdk-wrapper.md +291 -0
- package/dist/skills/hor-external-api-client/references/testing.md +130 -0
- package/dist/skills/hor-external-api-client/references/usage.md +152 -0
- package/dist/skills/hor-graphql-schema/SKILL.md +360 -0
- package/dist/skills/hor-graphql-server-engine/SKILL.md +356 -0
- package/dist/skills/hor-light-rag/SKILL.md +242 -0
- package/dist/skills/hor-light-rag/references/retrieval-internals.md +143 -0
- package/dist/skills/hor-multi-llm-provider/SKILL.md +288 -0
- package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +153 -0
- package/dist/skills/hor-mutation-resolver/SKILL.md +360 -0
- package/dist/skills/hor-mutation-resolver/references/dependency-injection.md +148 -0
- package/dist/skills/hor-mutation-resolver/references/errors.md +120 -0
- package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +275 -0
- package/dist/skills/hor-mutation-resolver/references/testing.md +125 -0
- package/dist/skills/hor-mutation-resolver/references/transaction.md +197 -0
- package/dist/skills/hor-post-worker/SKILL.md +320 -0
- package/dist/skills/hor-query-resolver/SKILL.md +246 -0
- package/dist/skills/hor-query-resolver/references/anatomy.md +384 -0
- package/dist/skills/hor-query-resolver/references/data-access.md +248 -0
- package/dist/skills/hor-query-resolver/references/errors-and-context.md +172 -0
- package/dist/skills/hor-query-resolver/references/testing.md +241 -0
- package/dist/skills/hor-renchan-job-bullmq/SKILL.md +178 -0
- package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +182 -0
- package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +106 -0
- package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +189 -0
- package/dist/skills/hor-renchan-job-bullmq/references/queues.md +74 -0
- package/dist/skills/hor-renchan-job-bullmq/references/subscriptions.md +113 -0
- package/dist/skills/hor-resolver-share/SKILL.md +262 -0
- package/dist/skills/hor-resolver-validator/SKILL.md +194 -0
- package/dist/skills/hor-resolver-validator/references/inspector-api.md +115 -0
- package/dist/skills/hor-resolver-validator/references/validator-pattern.md +281 -0
- package/dist/skills/hor-restfulapi-architecture/SKILL.md +275 -0
- package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +192 -0
- package/dist/skills/hor-restfulapi-architecture/references/renderers.md +204 -0
- package/dist/skills/hor-restfulapi-architecture/references/response-and-flusher.md +118 -0
- package/dist/skills/hor-restfulapi-architecture/references/validation.md +229 -0
- package/dist/skills/hor-security-audit/SKILL.md +110 -0
- package/dist/skills/hor-security-audit/references/application-surface.md +90 -0
- package/dist/skills/hor-security-audit/references/auth-and-transport.md +147 -0
- package/dist/skills/hor-security-audit/references/code-safety.md +74 -0
- package/dist/skills/hor-security-audit/references/dependencies.md +72 -0
- package/dist/skills/hor-security-audit/references/network-and-logging.md +56 -0
- package/dist/skills/hor-security-audit/references/secrets.md +95 -0
- package/dist/skills/hor-sequelize-migration/SKILL.md +336 -0
- package/dist/skills/hor-sequelize-migration/references/alter-table.md +147 -0
- package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +107 -0
- package/dist/skills/hor-sequelize-migration/references/indexes.md +149 -0
- package/dist/skills/hor-sequelize-migration/references/notation.md +215 -0
- package/dist/skills/hor-sequelize-model/SKILL.md +69 -0
- package/dist/skills/hor-sequelize-model/references/associations.md +218 -0
- package/dist/skills/hor-sequelize-model/references/default-methods.md +244 -0
- package/dist/skills/hor-sequelize-model/references/mixins.md +247 -0
- package/dist/skills/hor-sequelize-model/references/notation.md +225 -0
- package/dist/skills/hor-sequelize-model/references/timestamps.md +74 -0
- package/dist/skills/hor-sequelize-seeder/SKILL.md +275 -0
- package/dist/skills/hor-sequelize-seeder/references/development-coverage.md +74 -0
- package/dist/skills/hor-sequelize-seeder/references/directory-structure.md +113 -0
- package/dist/skills/hor-sequelize-seeder/references/id-numbering.md +133 -0
- package/dist/skills/hor-sequelize-seeder/references/naming.md +59 -0
- package/dist/skills/hor-sequelize-seeder/references/notation.md +170 -0
- package/dist/skills/hor-sequelize-subquery/SKILL.md +369 -0
- package/dist/skills/hor-strategy-pattern/SKILL.md +371 -0
- package/dist/skills/hor-stub-api/SKILL.md +330 -0
- package/dist/skills/hor-subscription-resolver/SKILL.md +105 -0
- package/dist/skills/hor-subscription-resolver/references/authentication.md +99 -0
- package/dist/skills/hor-subscription-resolver/references/basic-notation.md +116 -0
- package/dist/skills/hor-subscription-resolver/references/design-philosophy.md +68 -0
- package/dist/skills/hor-type-interface/SKILL.md +200 -0
- package/docs/skills.ja.md +40 -0
- package/docs/skills.md +40 -0
- package/lib/equip/CommandLineArguments.js +178 -0
- package/lib/equip/HoraSkillsCli.js +590 -0
- package/lib/equip/SkillsInstaller.js +443 -0
- package/lib/equip/SkillsManifestFile.js +260 -0
- package/lib/equip/constants/CLI_COMMAND.js +8 -0
- package/lib/equip/hora-skills-ort-renchan.js +8 -0
- package/package.json +51 -0
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-post-worker
|
|
3
|
+
description: >
|
|
4
|
+
Implement a GraphQL post-worker: a hook that fires after a query/mutation resolver has resolved
|
|
5
|
+
and the response has been sent, to run a side effect that is not part of the API's main
|
|
6
|
+
processing (send a welcome email after signup, emit an audit log, invalidate a cache). Use this
|
|
7
|
+
skill whenever the user asks to add or edit a post-worker, wants "run something after this
|
|
8
|
+
resolver / after the response", or needs to fire-and-forget a side effect right after an API
|
|
9
|
+
call.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# Post-Worker (a post-response side-effect hook)
|
|
13
|
+
|
|
14
|
+
A skill for implementing `BaseGraphqlPostWorker`, a hook that runs a side effect — one that is *not*
|
|
15
|
+
part of the API's main processing — **after** the resolver has resolved (after the response has been
|
|
16
|
+
sent). It handles requirements of the form "after this operation, also run …" as a follow-up, without
|
|
17
|
+
polluting the resolver itself.
|
|
18
|
+
|
|
19
|
+
Deciding the placement itself (whether a post-worker is even the right choice, versus enqueuing inside
|
|
20
|
+
the resolver) is settled in section 2.2 of `hor-execution-placement-pattern`. This skill covers "once
|
|
21
|
+
you've decided on a post-worker, how to implement it". The implementation of the worker body you
|
|
22
|
+
dispatch to belongs to `hor-renchan-job-bullmq`.
|
|
23
|
+
|
|
24
|
+
## Grand principle: a post-worker is a thin layer that only dispatches — the real work always lives in the worker
|
|
25
|
+
|
|
26
|
+
The only things you may write in a post-worker's `onResolved()` are **the dispatch to a background
|
|
27
|
+
worker and the branching that precedes it**. **Write no real work at all** — no email-body assembly,
|
|
28
|
+
no external API calls, no DB updates, no heavy loops.
|
|
29
|
+
|
|
30
|
+
- **Why only dispatch**: a post-worker fires **after** the HTTP response has been fully sent (Express's
|
|
31
|
+
`res.on('finish')`). Throwing an exception here **never reaches the caller, and neither retry,
|
|
32
|
+
progress notification, nor monitoring apply**. Put real work here and logic accumulates in a place
|
|
33
|
+
where failures get swallowed. Keep it to dispatch and the real work runs on the worker's machinery
|
|
34
|
+
(retries, observability, scaling), while the post-worker stays predictably thin — "just enqueuing".
|
|
35
|
+
- **Why add a post-worker layer at all**: for something like "I don't want to make the signup response
|
|
36
|
+
wait, but I do want to send a welcome email" — writing a **side effect unrelated to the main
|
|
37
|
+
processing** into the resolver itself bloats the resolver's responsibility and lets a side-effect
|
|
38
|
+
failure drag down the main processing's response. Push it out to a post-worker and the resolver can
|
|
39
|
+
focus on returning its proper result.
|
|
40
|
+
- **If the decision touches "heavy / want to retry", go to the worker.** A post-worker is itself a thin
|
|
41
|
+
hook that is never re-run, so any processing that must not fail, or that takes time, always belongs
|
|
42
|
+
in the worker you dispatch to.
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
// Good: the post-worker only dispatches (the real work of the side effect is on the worker side)
|
|
46
|
+
/** @override */
|
|
47
|
+
async onResolved ({
|
|
48
|
+
variables,
|
|
49
|
+
context,
|
|
50
|
+
information,
|
|
51
|
+
response: {
|
|
52
|
+
output,
|
|
53
|
+
error,
|
|
54
|
+
},
|
|
55
|
+
}) {
|
|
56
|
+
if (error) {
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
await context.share.jobDispatcherProvider.dispatchJob({
|
|
61
|
+
DispatcherCtor: SendWelcomeEmailJobDispatcher,
|
|
62
|
+
body: {
|
|
63
|
+
customerId: output.customer.id,
|
|
64
|
+
},
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
```js
|
|
70
|
+
// Avoid: writing email-body assembly or sending logic directly in the post-worker
|
|
71
|
+
// → real work accumulates in a post-response place where failures get swallowed, and neither retry nor monitoring apply. Put the real work in the worker.
|
|
72
|
+
async onResolved ({ output }) {
|
|
73
|
+
const html = await this.buildWelcomeMailHtml({ output }) // real work
|
|
74
|
+
await this.mailer.send({ to: output.customer.email, html }) // external I/O — if it fails, no one notices
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Comment language in the sample code
|
|
79
|
+
|
|
80
|
+
Comments in the `js` examples in this SKILL.md follow the prose language (here, **English**), because
|
|
81
|
+
the examples are *explanation* of the skill. Comments inside the **artifact this skill produces** (the
|
|
82
|
+
real `*PostWorker.js` code) follow the **codebase** language — English — to match the surrounding source.
|
|
83
|
+
|
|
84
|
+
## 1. How it works (when it fires and what it receives)
|
|
85
|
+
|
|
86
|
+
A post-worker is a hook **per operation (query / mutation)**. The framework (renchan) fires it in the
|
|
87
|
+
following flow.
|
|
88
|
+
|
|
89
|
+
1. When the resolver resolves (or throws), the framework stores
|
|
90
|
+
`{ variables, context, information, response }` bound to the request (`response` is
|
|
91
|
+
`{ output, error: null }` on success, `{ output: null, error }` on failure).
|
|
92
|
+
2. **After the HTTP response has been fully sent** (`res.on('finish')`), using the stored content, it
|
|
93
|
+
fires in this order:
|
|
94
|
+
- first the engine-wide `defineOnResolved()` (a noop by default, **common to all operations**),
|
|
95
|
+
- then the `onResolved()` of **the post-worker whose name matches that operation**.
|
|
96
|
+
|
|
97
|
+
- **The correspondence to an operation is by name match.** A post-worker is called only when the string
|
|
98
|
+
returned by its `static get schema()` matches the fired operation's name (the GraphQL field name,
|
|
99
|
+
e.g. `signUp`). **One post-worker per operation** (don't define the same `schema` more than once).
|
|
100
|
+
- `onResolved()` receives the **same `context`** as the resolver. This is the key point: because
|
|
101
|
+
`context` reaches the shared instances (the job dispatcher, etc.), a post-worker can dispatch a worker
|
|
102
|
+
([2](#2-dispatch-a-worker-from-contextshare)).
|
|
103
|
+
- `variables` is the operation's input arguments, `output` is the resolver's return value, and
|
|
104
|
+
`information` is the resolve info (`fieldName`, etc.).
|
|
105
|
+
|
|
106
|
+
Arguments `onResolved()` receives:
|
|
107
|
+
|
|
108
|
+
| Argument | Contents |
|
|
109
|
+
| --- | --- |
|
|
110
|
+
| `variables` | The operation's input arguments (the same ones the resolver received) |
|
|
111
|
+
| `context` | The same context as the resolver. `context.share` holds the shared instances ([2](#2-dispatch-a-worker-from-contextshare)) |
|
|
112
|
+
| `information` | GraphQL resolve info (`fieldName` = the operation name, etc.) |
|
|
113
|
+
| `response.output` | The resolver's return value (on success). `null` on failure |
|
|
114
|
+
| `response.error` | The error the resolver threw (on failure). `null` on success |
|
|
115
|
+
|
|
116
|
+
## 2. Dispatch a worker from `context.share`
|
|
117
|
+
|
|
118
|
+
A post-worker receives the same `context` as the resolver, and `context` has **`share`**. `share` holds
|
|
119
|
+
the instances the app uses in common, and in many renchan apps it keeps the **renchan-job-bullmq
|
|
120
|
+
dispatch entry point** (`jobDispatcherProvider`). A post-worker uses this to enqueue a worker.
|
|
121
|
+
|
|
122
|
+
```js
|
|
123
|
+
// Dispatch via share (a JobDispatcherProvider that reuses the connection)
|
|
124
|
+
await context.share.jobDispatcherProvider.dispatchJob({
|
|
125
|
+
DispatcherCtor: SendWelcomeEmailJobDispatcher, // the Dispatcher of the job to enqueue
|
|
126
|
+
body: {
|
|
127
|
+
customerId: output.customer.id, // keep the body minimal (just ids or tokens)
|
|
128
|
+
},
|
|
129
|
+
})
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- **Why use `context.share`**: taking the dispatch entry point from the request-scoped shared instance
|
|
133
|
+
lets you reuse the connection to Redis, etc. Don't `new` a Dispatcher every time inside the post-worker.
|
|
134
|
+
- The implementation of **the job you dispatch (Manifest / Worker / Dispatcher)** follows
|
|
135
|
+
`hor-renchan-job-bullmq`. The post-worker side only decides "which Dispatcher, with what
|
|
136
|
+
body" to enqueue.
|
|
137
|
+
- What's in `share` is app-dependent. Confirm the name of the dispatch entry point
|
|
138
|
+
(`jobDispatcherProvider`, etc.) in that app's Share implementation. **If it's missing, the right move
|
|
139
|
+
is to add it to share** — don't create a connection on the fly inside the post-worker.
|
|
140
|
+
|
|
141
|
+
## 3. Implementation steps
|
|
142
|
+
|
|
143
|
+
Steps to add one new post-worker.
|
|
144
|
+
|
|
145
|
+
### Step 1: Create the post-worker class
|
|
146
|
+
|
|
147
|
+
Extend `BaseGraphqlPostWorker` and override the following two. The file name is `<Operation>PostWorker.js`
|
|
148
|
+
(a name that makes the corresponding operation clear; align it with the resolver's naming).
|
|
149
|
+
|
|
150
|
+
- `static get schema()`: returns the **operation name** to hook (the GraphQL field name).
|
|
151
|
+
- `async onResolved({ variables, context, information, response })`: write dispatch only (the grand
|
|
152
|
+
principle at the top of this file).
|
|
153
|
+
|
|
154
|
+
```js
|
|
155
|
+
import {
|
|
156
|
+
BaseGraphqlPostWorker,
|
|
157
|
+
} from '@openreachtech/renchan'
|
|
158
|
+
|
|
159
|
+
import SendWelcomeEmailJobDispatcher from '../../../../app/jobs/send-welcome-email/SendWelcomeEmailJobDispatcher.js'
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Post-worker: dispatch a welcome email after signUp resolves.
|
|
163
|
+
*
|
|
164
|
+
* @extends {BaseGraphqlPostWorker<*, *, *>}
|
|
165
|
+
*/
|
|
166
|
+
export default class SignUpPostWorker extends BaseGraphqlPostWorker {
|
|
167
|
+
/**
|
|
168
|
+
* get: Operation name to hook.
|
|
169
|
+
*
|
|
170
|
+
* @override
|
|
171
|
+
* @returns {string}
|
|
172
|
+
*/
|
|
173
|
+
static get schema () {
|
|
174
|
+
return 'signUp'
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* On resolved hook. Dispatch only; the real work lives in the worker.
|
|
179
|
+
*
|
|
180
|
+
* @override
|
|
181
|
+
*/
|
|
182
|
+
async onResolved ({
|
|
183
|
+
variables,
|
|
184
|
+
context,
|
|
185
|
+
information,
|
|
186
|
+
response: {
|
|
187
|
+
output,
|
|
188
|
+
error,
|
|
189
|
+
},
|
|
190
|
+
}) {
|
|
191
|
+
if (error) {
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
await context.share.jobDispatcherProvider.dispatchJob({
|
|
196
|
+
DispatcherCtor: SendWelcomeEmailJobDispatcher,
|
|
197
|
+
body: {
|
|
198
|
+
customerId: output.customer.id,
|
|
199
|
+
},
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
### Step 2: Guard against failures and missing values
|
|
206
|
+
|
|
207
|
+
- **If there's an `error`, return early.** Enqueuing a side effect (like sending an email) when the
|
|
208
|
+
operation failed creates inconsistency. The standard guard is `if (!output || error) { return }` —
|
|
209
|
+
treat a missing `output` the same as a failure.
|
|
210
|
+
- **Check that the values you read from `output` exist.** A post-worker runs after the resolver
|
|
211
|
+
succeeds, but if `output`'s shape differs from what you expect, traverse it defensively like
|
|
212
|
+
`output?.customer?.id` and don't dispatch when it's absent.
|
|
213
|
+
- **Don't throw from `onResolved()`.** It's after the response has been sent, so no one can catch it.
|
|
214
|
+
Handle it with branching and return early.
|
|
215
|
+
- **Don't declare an `errorCodeHash` getter on a post-worker.** Unlike a resolver, a post-worker has
|
|
216
|
+
no error contract with the caller (the response is already sent), so failures are handled by
|
|
217
|
+
branching and early returns, not by raising error codes.
|
|
218
|
+
|
|
219
|
+
### Step 3: Wire it into the engine (`postWorkersPath`)
|
|
220
|
+
|
|
221
|
+
Post-workers are **auto-loaded recursively** from the directory the engine's `config.postWorkersPath`
|
|
222
|
+
points at (only classes extending `BaseGraphqlPostWorker` are picked up). While `postWorkersPath` is
|
|
223
|
+
`null`, post-workers **never fire at all**.
|
|
224
|
+
|
|
225
|
+
- Following the resolver layout, prepare a per-role directory like
|
|
226
|
+
`server/graphql/post-workers/<role>/` and point `postWorkersPath` at it.
|
|
227
|
+
|
|
228
|
+
```js
|
|
229
|
+
// server/graphql/CustomerGraphqlServerEngine.js
|
|
230
|
+
/** @override */
|
|
231
|
+
static get config () {
|
|
232
|
+
return {
|
|
233
|
+
// ...existing config...
|
|
234
|
+
actualResolversPath: rootPath.to('server/graphql/resolvers/customer/actual/'),
|
|
235
|
+
// Before: postWorkersPath: null,
|
|
236
|
+
postWorkersPath: rootPath.to('server/graphql/post-workers/customer/'),
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
- If you need **engine-wide post-processing (common to all operations)**, override the engine's
|
|
242
|
+
`defineOnResolved()` rather than a post-worker under `postWorkersPath`. The "dispatch only" principle
|
|
243
|
+
still applies here too. Use them separately: **a post-worker for a specific operation's
|
|
244
|
+
post-processing, `defineOnResolved()` for post-processing across all operations.**
|
|
245
|
+
|
|
246
|
+
## 4. Use cases (what to put in a post-worker)
|
|
247
|
+
|
|
248
|
+
All of these are **side effects unrelated to the main processing that you don't want to make the
|
|
249
|
+
response wait for**, and in the post-worker you **only dispatch**.
|
|
250
|
+
|
|
251
|
+
| Use case | Example operation to hook | What the dispatched worker does |
|
|
252
|
+
| --- | --- | --- |
|
|
253
|
+
| Notification email right after signup | `signUp` | Generate and send the welcome email body |
|
|
254
|
+
| Recording an audit log / operation history | Each mutation | Write the changes to the audit store |
|
|
255
|
+
| Syncing to an external system / webhook notification | `createXxx` / `updateXxx` | Push to the external API (external API client) |
|
|
256
|
+
| Cache invalidation / rebuild | Data-updating mutations | Delete and warm up the cache |
|
|
257
|
+
| Sending analytics events | Any operation | Send measurement events to analytics |
|
|
258
|
+
|
|
259
|
+
- **What a post-worker is not suited for**: processing whose result **the caller waits for / is included
|
|
260
|
+
in the response** is too late in a post-worker (since it runs after the response). Handle that in the
|
|
261
|
+
resolver itself, or with enqueuing inside the resolver (`hor-execution-placement-pattern` 2.1).
|
|
262
|
+
|
|
263
|
+
## 5. Testing
|
|
264
|
+
|
|
265
|
+
A post-worker has thin logic (dispatch only), so keep its tests thin too. Following the `hoc-jest` skill,
|
|
266
|
+
split files per class.
|
|
267
|
+
|
|
268
|
+
- That it extends `BaseGraphqlPostWorker` (inheritance).
|
|
269
|
+
- That `static get schema()` returns the **correct operation name**.
|
|
270
|
+
- The branching in `onResolved()`:
|
|
271
|
+
- **On success** (`error: null`, `output` present) → **dispatch is called** with the expected
|
|
272
|
+
`DispatcherCtor` and `body`.
|
|
273
|
+
- **On failure** (`error` present) → **dispatch is not called** (early return).
|
|
274
|
+
- Stub the dispatch entry point. Replace `context.share.jobDispatcherProvider.dispatchJob` with a
|
|
275
|
+
`jest.fn()` and verify the arguments (`DispatcherCtor` / `body`). **Don't actually enqueue a job.**
|
|
276
|
+
|
|
277
|
+
```js
|
|
278
|
+
// Success case: verify only that dispatch is called with the correct Dispatcher and body
|
|
279
|
+
const dispatchJobSpy = jest.fn()
|
|
280
|
+
const context = {
|
|
281
|
+
share: {
|
|
282
|
+
jobDispatcherProvider: {
|
|
283
|
+
dispatchJob: dispatchJobSpy,
|
|
284
|
+
},
|
|
285
|
+
},
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
await SignUpPostWorker.create({ engine })
|
|
289
|
+
.onResolved({
|
|
290
|
+
variables: {},
|
|
291
|
+
context,
|
|
292
|
+
information: {},
|
|
293
|
+
response: {
|
|
294
|
+
output: {
|
|
295
|
+
customer: {
|
|
296
|
+
id: 'fake-customer-id-001',
|
|
297
|
+
},
|
|
298
|
+
},
|
|
299
|
+
error: null,
|
|
300
|
+
},
|
|
301
|
+
})
|
|
302
|
+
|
|
303
|
+
expect(dispatchJobSpy)
|
|
304
|
+
.toHaveBeenCalledWith({
|
|
305
|
+
DispatcherCtor: SendWelcomeEmailJobDispatcher,
|
|
306
|
+
body: {
|
|
307
|
+
customerId: 'fake-customer-id-001',
|
|
308
|
+
},
|
|
309
|
+
})
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
## Finishing checklist
|
|
313
|
+
|
|
314
|
+
- [ ] Is what you wrote in `onResolved()` **only dispatch and branching** (did you put the real work in the worker)?
|
|
315
|
+
- [ ] Does `static get schema()` match the **operation name** it hooks (one post-worker per operation)?
|
|
316
|
+
- [ ] Do you return early when there's an `error`, and guard against a missing `output`? Are you not throwing from `onResolved()`?
|
|
317
|
+
- [ ] Is the dispatch via `context.share`'s shared dispatch entry point (not `new`-ing a connection inside the post-worker)?
|
|
318
|
+
- [ ] Did you wire the engine's `postWorkersPath` (it won't fire while it stays `null`)?
|
|
319
|
+
- [ ] Did you use `defineOnResolved()` for post-processing across all operations and a post-worker for a specific operation, appropriately?
|
|
320
|
+
- [ ] In tests, did you verify "dispatched on success / not on failure" with a stub of the dispatch entry point?
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-query-resolver
|
|
3
|
+
description: >
|
|
4
|
+
Write GraphQL Query resolvers under
|
|
5
|
+
server/graphql/resolvers/<endpoint>/{actual,stub}/queries/<Operation>QueryResolver.js, extending
|
|
6
|
+
BaseQueryResolver from @openreachtech/renchan. Use this skill whenever the user asks to add or
|
|
7
|
+
edit a read query resolver, including its pagination, association includes, domain-error
|
|
8
|
+
throwing, and the actual-vs-stub pair. Input validation belongs to the resolver input-validator
|
|
9
|
+
convention; state-changing operations belong to the mutation resolver convention.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# Query Resolver
|
|
13
|
+
|
|
14
|
+
A skill for writing the **`*QueryResolver` classes** that answer a GraphQL `Query` field. A query
|
|
15
|
+
resolver **extends `BaseQueryResolver`** (from `@openreachtech/renchan`), is **read-only** (it never
|
|
16
|
+
opens a transaction — that is the mutation side's job), and always follows the same shape: a `schema`
|
|
17
|
+
getter that names the GraphQL field, an `errorCodeHash`, and a `resolve()` that **validates the
|
|
18
|
+
input, reads data, throws domain errors, and formats the response**.
|
|
19
|
+
|
|
20
|
+
> Examples use a made-up `users` domain (a `User` model with a `UserProfile` / `Department` / `Role`
|
|
21
|
+
> around it) on the `admin` endpoint. They are placeholders — swap in the resource, fields, and
|
|
22
|
+
> endpoint of the query you are writing.
|
|
23
|
+
|
|
24
|
+
This skill covers the **resolver class itself**. Two related skills own the pieces it delegates to:
|
|
25
|
+
|
|
26
|
+
- The `*InputValidator` it calls belongs to `hor-resolver-validator` —
|
|
27
|
+
this skill only shows the wiring, not the validator internals.
|
|
28
|
+
- The unit tests belong to `hoc-jest` — see [testing.md](./references/testing.md) for
|
|
29
|
+
the resolver-specific shape.
|
|
30
|
+
|
|
31
|
+
> This is the **Query** side. A **Mutation** resolver is a different template (it wraps a
|
|
32
|
+
> transaction callback and returns save results); do not copy this skeleton for a write.
|
|
33
|
+
|
|
34
|
+
## Core principle: a query resolver is a filled-in template
|
|
35
|
+
|
|
36
|
+
Every query resolver has the **same skeleton** — `schema` getter → `errorCodeHash` → `resolve()` →
|
|
37
|
+
validation wiring → finders → `formatResponse()` → error creators → a trailing block of `@typedef`s.
|
|
38
|
+
Keep the skeleton identical so review attention goes straight to the **query-specific differences
|
|
39
|
+
(what it reads and how it shapes the result)**. Do not write it cleverly; lean toward the layout of
|
|
40
|
+
the existing resolvers.
|
|
41
|
+
|
|
42
|
+
`resolve()` reads as a fixed pipeline:
|
|
43
|
+
|
|
44
|
+
1. **Validate** the input (`validateInput()` returns an error **or `null`**; `throw` it when present).
|
|
45
|
+
2. **Read** the data (finders: `findX()` / `countX()`), passing already-trusted input.
|
|
46
|
+
3. **Throw domain errors** for not-found / empty results, via `this.errorHash.Xxx.create()`.
|
|
47
|
+
4. **Format** the result to the GraphQL schema shape (`formatResponse()`), and `return` it.
|
|
48
|
+
|
|
49
|
+
```js
|
|
50
|
+
/** @override */
|
|
51
|
+
async resolve ({
|
|
52
|
+
variables: {
|
|
53
|
+
input,
|
|
54
|
+
},
|
|
55
|
+
}) {
|
|
56
|
+
const validationError = this.validateInput({
|
|
57
|
+
input,
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
if (validationError) {
|
|
61
|
+
throw validationError
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const user = await this.findUser({
|
|
65
|
+
userId: input.userId,
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
if (!user) {
|
|
69
|
+
throw this.errorHash.UserNotFound.create()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return this.formatResponse({
|
|
73
|
+
user,
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
- **No transaction.** Queries only read. Reach for `.findOne` / `.findByPk` / `.findAll` / `.count`;
|
|
79
|
+
never `db.transaction(...)` here.
|
|
80
|
+
- **`resolve()` orchestrates; the small methods do the work.** Each `findX` / `buildWhereClause` /
|
|
81
|
+
`formatResponse` has one job and is unit-testable in isolation. Do not inline a 60-line find or a
|
|
82
|
+
giant response object into `resolve()`.
|
|
83
|
+
- The full member-by-member template with JSDoc and the typedef block is in
|
|
84
|
+
[anatomy.md](./references/anatomy.md).
|
|
85
|
+
|
|
86
|
+
## 1. Directory, class name, and schema linkage
|
|
87
|
+
|
|
88
|
+
One resolver = one file. Placement encodes the endpoint and whether it is real or a stub:
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
server/graphql/resolvers/<endpoint>/<actual|stub>/queries/<Operation>QueryResolver.js
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
- `<endpoint>` is the GraphQL endpoint the resolver serves: `user`, `customer`, `admin`, `portal`,
|
|
95
|
+
`jobs`. It maps to a `*GraphqlServerEngine` (e.g. `server/graphql/AdminGraphqlServerEngine.js`).
|
|
96
|
+
- `<actual|stub>` — **`actual`** holds the real business logic; **`stub`** returns fixed fake data
|
|
97
|
+
for the frontend to develop against ([errors-and-context.md](./references/errors-and-context.md)).
|
|
98
|
+
- Class name = `<Operation>QueryResolver` (PascalCase), default-exported, one class per file.
|
|
99
|
+
- **Auto-loaded — no manual registration.** The engine loads every file under `.../queries/` by
|
|
100
|
+
directory (`actualResolversPath` in the engine config). Adding the file is enough; there is no
|
|
101
|
+
index to edit.
|
|
102
|
+
- **`schema` getter = the GraphQL `Query` field name** (camelCase). It must match a field declared in
|
|
103
|
+
`server/graphql/schemas/<endpoint>/*.graphql`, whose `Input!` / `Result!` types become the
|
|
104
|
+
resolver's `input` and return shape:
|
|
105
|
+
|
|
106
|
+
```graphql
|
|
107
|
+
# server/graphql/schemas/admin/003-user.graphql
|
|
108
|
+
type Query {
|
|
109
|
+
users(input: UsersInput!): UsersResult!
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```js
|
|
114
|
+
/** @override */
|
|
115
|
+
static get schema () {
|
|
116
|
+
return 'users'
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## 2. Member order
|
|
121
|
+
|
|
122
|
+
Declare members in this fixed order (matches the existing resolvers and the backend guideline):
|
|
123
|
+
|
|
124
|
+
1. `static get schema ()` — the GraphQL field name. `@override`.
|
|
125
|
+
2. `static get errorCodeHash ()` — spread `...super.errorCodeHash`, then this resolver's codes (§4).
|
|
126
|
+
3. `async resolve ({ variables, context })` — the entrypoint. `@override`.
|
|
127
|
+
4. `validateInput ({ input })` — runs the validator, returns the error or `null`.
|
|
128
|
+
5. `createInputValidator ({ input, errorHash })` — factory for the `*InputValidator`.
|
|
129
|
+
6. **Finders and helpers**, in call order (`findX` / `countX` / `buildWhereClause` / `create*`).
|
|
130
|
+
Place each helper right after its caller; unrelated helpers go in dictionary order.
|
|
131
|
+
7. `formatResponse ({ ... })` — shape the GraphQL result.
|
|
132
|
+
8. Error creators (`createXxxNotFoundError`), when domain errors are built through helpers.
|
|
133
|
+
|
|
134
|
+
After the class, a block of `@typedef`s (`ErrorCodeHash`, the `Input` / `Result` aliases, `ErrorHash`,
|
|
135
|
+
`RenchanGraphqlErrorCtor`, and any associated-entity types). See [anatomy.md](./references/anatomy.md).
|
|
136
|
+
|
|
137
|
+
## 3. Reading data
|
|
138
|
+
|
|
139
|
+
Finders are thin wrappers over the Sequelize models; keep query-shape logic (where clauses,
|
|
140
|
+
includes, pagination) in their own small methods so `resolve()` stays a pipeline.
|
|
141
|
+
|
|
142
|
+
- **Single record:** `Model.findByPk(id, { include })` / `Model.findOne({ where, include })`, then a
|
|
143
|
+
not-found guard that throws a domain error.
|
|
144
|
+
- **List with pagination:** the canonical trio is `buildWhereClause()` → `countX({ whereClause })`
|
|
145
|
+
(for `totalRecords`) → `findX({ whereClause, pagination })` (with `offset` / `limit` / `order`).
|
|
146
|
+
- **Associations:** pass an `include` tree of models; deep values are pulled out in `formatResponse`
|
|
147
|
+
with `FieldPathValueExtractor`.
|
|
148
|
+
|
|
149
|
+
The where-clause / pagination / include / extractor patterns are in
|
|
150
|
+
[data-access.md](./references/data-access.md).
|
|
151
|
+
|
|
152
|
+
## 4. errorCodeHash and domain errors
|
|
153
|
+
|
|
154
|
+
`errorCodeHash` maps each error name to a **string code**; `.create()` turns those into the
|
|
155
|
+
`this.errorHash.<Name>` constructors the resolver throws. Spread the parent first:
|
|
156
|
+
|
|
157
|
+
```js
|
|
158
|
+
/** @override */
|
|
159
|
+
static get errorCodeHash () {
|
|
160
|
+
return {
|
|
161
|
+
...super.errorCodeHash,
|
|
162
|
+
|
|
163
|
+
// Invalid Input Errors (203 prefix)
|
|
164
|
+
InvalidUserId: '203.Q002.001',
|
|
165
|
+
|
|
166
|
+
// Database Errors (204 prefix)
|
|
167
|
+
UserNotFound: '204.Q002.001',
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
- **Leading number = error family.** `203` invalid input, `204` database / not-found, `205` business
|
|
173
|
+
logic / external API. (Framework standards live above these: `102` unauthorized, `104` database —
|
|
174
|
+
do not redefine them.)
|
|
175
|
+
- **Middle segment (`Q002`) is a stable per-query identifier**; the trailing `001…` numbers the
|
|
176
|
+
errors within this resolver. Keep a given resolver on one identifier and add sequentially.
|
|
177
|
+
- **Input-shape errors** (`InvalidXxx`) are raised by the validator via the shared `errorHash`, so
|
|
178
|
+
their names must exist here. **Domain errors** (`XxxNotFound`, `NoXxxFound`) are thrown from
|
|
179
|
+
`resolve()` with `this.errorHash.Xxx.create()` (optionally through a `createXxxError()` helper).
|
|
180
|
+
|
|
181
|
+
The families, the validator↔errorHash contract, and error-creator helpers are in
|
|
182
|
+
[errors-and-context.md](./references/errors-and-context.md).
|
|
183
|
+
|
|
184
|
+
## 5. Input validation wiring
|
|
185
|
+
|
|
186
|
+
The resolver does not validate inline — it delegates to a `*InputValidator`
|
|
187
|
+
(`hor-resolver-validator`) through two small methods:
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
validateInput ({
|
|
191
|
+
input,
|
|
192
|
+
}) {
|
|
193
|
+
const validator = this.createInputValidator({
|
|
194
|
+
input,
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
return validator.validateInput()
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
createInputValidator ({
|
|
201
|
+
input,
|
|
202
|
+
errorHash = this.errorHash,
|
|
203
|
+
}) {
|
|
204
|
+
return UsersInputValidator.create({
|
|
205
|
+
input,
|
|
206
|
+
errorHash,
|
|
207
|
+
})
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
- `validateInput()` returns the error **or `null`**; `resolve()` throws it when present (do not throw
|
|
212
|
+
from inside `validateInput`). The validator is fed the resolver's own `errorHash`, so its
|
|
213
|
+
`InvalidXxx` names resolve to the codes declared in §4.
|
|
214
|
+
- A resolver that takes no input (or only auth from `context`) has **no** validator — see the
|
|
215
|
+
minimal `departments` / `userSummary` resolvers in [anatomy.md](./references/anatomy.md).
|
|
216
|
+
|
|
217
|
+
## 6. Formatting the response
|
|
218
|
+
|
|
219
|
+
`formatResponse()` is the **only** place that builds the GraphQL output object. It maps model
|
|
220
|
+
entities to the schema's field names — never returns raw model instances.
|
|
221
|
+
|
|
222
|
+
- Rename model columns to schema fields (`user.id` → `userId`), map arrays to their output shape, and
|
|
223
|
+
**echo pagination** (`limit` / `offset` / `sort` / `totalRecords`) for lists.
|
|
224
|
+
- Read deep association values with `FieldPathValueExtractor`; guard optional relations and default
|
|
225
|
+
missing scalars (`?? ''` / `?? null`) rather than leaking `undefined`
|
|
226
|
+
([data-access.md](./references/data-access.md)).
|
|
227
|
+
|
|
228
|
+
## 7. Testing
|
|
229
|
+
|
|
230
|
+
Each public member is unit-tested with the `hoc-jest` skill: a top-level `describe` per
|
|
231
|
+
member, `test.each` cases, and `Resolver.create()` with no args. `#resolve()` gets both the
|
|
232
|
+
happy path and a throws-case per error code; `.get:schema` asserts the field name. The
|
|
233
|
+
resolver-specific structure (mocking the validator, DB-backed finder cases, `formatResponse` with
|
|
234
|
+
built model instances) is in [testing.md](./references/testing.md).
|
|
235
|
+
|
|
236
|
+
## Detail files
|
|
237
|
+
|
|
238
|
+
- [anatomy.md](./references/anatomy.md) — the full canonical resolver (every member with JSDoc, the
|
|
239
|
+
minimal no-input variant, and the trailing `@typedef` block) (§2)
|
|
240
|
+
- [data-access.md](./references/data-access.md) — finders, `buildWhereClause`, the count+findAll
|
|
241
|
+
pagination trio, association `include` trees, model `subquery()`, and `FieldPathValueExtractor` (§3, §6)
|
|
242
|
+
- [errors-and-context.md](./references/errors-and-context.md) — the errorCodeHash prefix families, the
|
|
243
|
+
validator↔errorHash contract, domain-error creators, reading auth/providers off `context`, and
|
|
244
|
+
actual-vs-stub resolvers (§1, §4)
|
|
245
|
+
- [testing.md](./references/testing.md) — the member-by-member test layout for a query resolver,
|
|
246
|
+
building on the jest skill (§7)
|