@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,360 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-mutation-resolver
|
|
3
|
+
description: >
|
|
4
|
+
Implement GraphQL Mutation resolvers under
|
|
5
|
+
server/graphql/resolvers/<endpoint>/actual/mutations/<Operation>MutationResolver.js, extending
|
|
6
|
+
BaseMutationResolver (@openreachtech/renchan). Use this skill whenever the user asks to write or
|
|
7
|
+
edit a mutation resolver — a create / update / delete / sign-in / upload operation that changes
|
|
8
|
+
state, and the single transaction it runs in. Input validation, heavy background work and read
|
|
9
|
+
operations each belong to their own convention.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# Mutation Resolver
|
|
13
|
+
|
|
14
|
+
A skill for writing the **`*MutationResolver` classes** that resolve a GraphQL `Mutation` — the
|
|
15
|
+
synchronous write path of the API. A resolver **extends `BaseMutationResolver`** (from
|
|
16
|
+
`@openreachtech/renchan`), declares which schema it resolves and which error codes it can raise, and
|
|
17
|
+
runs a **fixed four-step flow** in `resolve()`. The value-shape checks live in a separate
|
|
18
|
+
`*InputValidator`; the heavy/slow work lives in a Worker. The resolver
|
|
19
|
+
itself only **orchestrates**.
|
|
20
|
+
|
|
21
|
+
> Directory layout follows the target convention (same idealized layer as the
|
|
22
|
+
> `*InputValidator`). `BaseMutationResolver` /
|
|
23
|
+
> `BaseResolver` come from the renchan framework; the `*InputValidator` comes from the shared
|
|
24
|
+
> validator layer; the models come from `sequelize/models/`.
|
|
25
|
+
|
|
26
|
+
## Core principle: a mutation resolver is a filled-in template
|
|
27
|
+
|
|
28
|
+
Every mutation resolver has the **same skeleton** — the same method set in the same order, and the
|
|
29
|
+
same `resolve()` flow:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
resolve() ─┬─▶ validateInput() → throw the InvalidXxx error, or continue
|
|
33
|
+
├─▶ generateTransactionCallback() → a `async transaction => {...}` closure
|
|
34
|
+
├─▶ Model.beginTransaction(callback)→ run every find + save in ONE transaction
|
|
35
|
+
└─▶ formatResponse() → shape the result (usually just an id)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Keep the skeleton identical so review attention goes straight to the **operation-specific
|
|
39
|
+
difference (which models, which guards, which columns)**. Do not write it cleverly; lean toward the
|
|
40
|
+
shape of the existing resolvers. Three rules carry most of the weight:
|
|
41
|
+
|
|
42
|
+
1. **All finds and saves for one request go inside one transaction callback** — never split a
|
|
43
|
+
`find` and its `save` across the transaction boundary (§4, [transaction.md](./references/transaction.md)).
|
|
44
|
+
2. **The resolver validates then delegates.** Input shape → the `*InputValidator` (§6). Value
|
|
45
|
+
changes → the transaction callback. Heavy/slow work → a Worker (§8). The resolver holds no
|
|
46
|
+
business rule that either of those should own.
|
|
47
|
+
3. **Return the save result, not a rendered view** (§5). A mutation returns ids; the frontend
|
|
48
|
+
re-fetches with a Query. This keeps Mutation and Query responsibilities separate.
|
|
49
|
+
|
|
50
|
+
> The examples use generic entities (`Article`, `User`) and standard tools; substitute your own
|
|
51
|
+
> domain models. What transfers is the shape — one transaction, validate-then-delegate, return the
|
|
52
|
+
> save result — not the entity names.
|
|
53
|
+
|
|
54
|
+
- **Comments: English for code, the surrounding language for domain notes.** Comments written into
|
|
55
|
+
the resolver `.js` are English. Domain/ticket notes may be Japanese where the surrounding files
|
|
56
|
+
are — match the neighbors.
|
|
57
|
+
|
|
58
|
+
## 1. Directory, file name, and the `schema` getter
|
|
59
|
+
|
|
60
|
+
One resolver = one file (one class per file). Place it under the endpoint it belongs to:
|
|
61
|
+
|
|
62
|
+
- **Path:** `server/graphql/resolvers/<endpoint>/actual/mutations/<Operation>MutationResolver.js`
|
|
63
|
+
- `<endpoint>` is the GraphQL endpoint (`user`, `customer`, `admin`, `portal`, …).
|
|
64
|
+
- `actual` = real business logic; the sibling `stub/` holds fixed-data stubs for the same schema.
|
|
65
|
+
- e.g. `server/graphql/resolvers/user/actual/mutations/CreateArticleMutationResolver.js`.
|
|
66
|
+
- **Class name** = `<Operation>MutationResolver` (PascalCase), where `<Operation>` is the schema in
|
|
67
|
+
PascalCase (`createArticle` → `CreateArticleMutationResolver`).
|
|
68
|
+
- **`static get schema()`** returns the GraphQL schema name in camelCase and is marked `@override`.
|
|
69
|
+
The base can derive it from the class name, but **always declare it explicitly** — it is the
|
|
70
|
+
single, greppable link between the schema and the class.
|
|
71
|
+
|
|
72
|
+
```js
|
|
73
|
+
import {
|
|
74
|
+
BaseMutationResolver,
|
|
75
|
+
} from '@openreachtech/renchan'
|
|
76
|
+
|
|
77
|
+
export default class UpdateArticleMutationResolver extends BaseMutationResolver {
|
|
78
|
+
/** @override */
|
|
79
|
+
static get schema () {
|
|
80
|
+
return 'updateArticle'
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ... errorCodeHash, resolve(), helpers ...
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## 2. The `resolve()` flow and method order
|
|
88
|
+
|
|
89
|
+
`resolve()` is the entry point and reads the same everywhere: **validate → build callback → run in
|
|
90
|
+
one transaction → format**. It receives `{ variables: { input }, context }`; `context` supplies
|
|
91
|
+
`now`, `userId` / `user`, and the endpoint identity.
|
|
92
|
+
|
|
93
|
+
```js
|
|
94
|
+
/**
|
|
95
|
+
* @param {{
|
|
96
|
+
* variables: { input: server.graphql.user.UpdateArticleInput }
|
|
97
|
+
* context: UserGraphqlContext
|
|
98
|
+
* }} params
|
|
99
|
+
* @returns {Promise<server.graphql.user.UpdateArticleResult>}
|
|
100
|
+
*/
|
|
101
|
+
async resolve ({
|
|
102
|
+
variables: {
|
|
103
|
+
input,
|
|
104
|
+
},
|
|
105
|
+
context,
|
|
106
|
+
}) {
|
|
107
|
+
const validationError = this.validateInput({
|
|
108
|
+
input,
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
if (validationError) {
|
|
112
|
+
throw validationError
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const callback = this.generateTransactionCallback({
|
|
116
|
+
input,
|
|
117
|
+
context,
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
const article = await Article.beginTransaction(callback)
|
|
121
|
+
|
|
122
|
+
return this.formatResponse({
|
|
123
|
+
article,
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
**Method order (matches the framework guideline):**
|
|
129
|
+
|
|
130
|
+
1. `static get schema ()` — `@override`
|
|
131
|
+
2. `static get errorCodeHash ()` — `@override` (§3)
|
|
132
|
+
3. *(optional)* `constructor` → `static create ()` → `static createXxx ()` factory helpers — only when
|
|
133
|
+
a dependency must be injected (§7)
|
|
134
|
+
4. `async resolve ()` — the flow above
|
|
135
|
+
5. `createInputValidator ({ input })` (§6)
|
|
136
|
+
6. `validateInput ({ input })` (§6)
|
|
137
|
+
7. `generateTransactionCallback ({ input, context })` (§4)
|
|
138
|
+
8. other instance methods — `findXxx` / `buildXxxAttributes` / `updateXxx`, placed **next to their
|
|
139
|
+
caller** (call-related methods adjacent; unrelated ones alphabetical)
|
|
140
|
+
9. `formatResponse ({ ... })` (§5)
|
|
141
|
+
10. `@typedef` blocks at the bottom (context type, entity types)
|
|
142
|
+
|
|
143
|
+
The full template with every helper filled in is in
|
|
144
|
+
[resolve-flow.md](./references/resolve-flow.md).
|
|
145
|
+
|
|
146
|
+
## 3. `errorCodeHash` and throwing errors
|
|
147
|
+
|
|
148
|
+
Declare every error the resolver can raise in `static get errorCodeHash ()`, spreading
|
|
149
|
+
`...super.errorCodeHash` first. Each entry maps an `ErrorName` to a **code string** whose leading
|
|
150
|
+
segment encodes the category:
|
|
151
|
+
|
|
152
|
+
- `203.*` — **invalid input** (`InvalidXxx`). These pair with the validator's predicates (§6).
|
|
153
|
+
- `204.*` — **DB / state** errors (`XxxNotFound`, `NotAllowedToXxx`, `CurrentXxxIsSameAsTheNewOne`).
|
|
154
|
+
- `205.*` — **auth** errors (`InvalidCredentials`).
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
/** @override */
|
|
158
|
+
static get errorCodeHash () {
|
|
159
|
+
return {
|
|
160
|
+
...super.errorCodeHash,
|
|
161
|
+
|
|
162
|
+
// Invalid Input Errors
|
|
163
|
+
InvalidArticleId: '203.M012.001',
|
|
164
|
+
InvalidTitle: '203.M012.003',
|
|
165
|
+
|
|
166
|
+
// Database Errors
|
|
167
|
+
ArticleNotFound: '204.M012.002',
|
|
168
|
+
CurrentArticleContentIsSameAsTheNewOne: '204.M012.003',
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The base turns this hash into constructable error classes on `this.errorHash` (via
|
|
174
|
+
`buildErrorHash()` in the factory). **Throw with `this.errorHash.<Name>.create()`** — validator
|
|
175
|
+
errors bubble out of `resolve()`; state errors are thrown from inside the transaction callback so
|
|
176
|
+
the transaction rolls back. Codes, numbering (`M###`), and the wiring are in
|
|
177
|
+
[errors.md](./references/errors.md).
|
|
178
|
+
|
|
179
|
+
## 4. `generateTransactionCallback()` — one transaction, all writes
|
|
180
|
+
|
|
181
|
+
`generateTransactionCallback({ input, context })` returns an **`async transaction => { ... }`**
|
|
182
|
+
closure that holds **every find and save for the request**. It is handed to
|
|
183
|
+
`Model.beginTransaction(callback)`, which opens a managed transaction and passes it in. Pass that
|
|
184
|
+
`transaction` to **every** query inside.
|
|
185
|
+
|
|
186
|
+
```js
|
|
187
|
+
generateTransactionCallback ({
|
|
188
|
+
input: {
|
|
189
|
+
title,
|
|
190
|
+
content,
|
|
191
|
+
articleId,
|
|
192
|
+
},
|
|
193
|
+
context: {
|
|
194
|
+
now,
|
|
195
|
+
userId,
|
|
196
|
+
},
|
|
197
|
+
}) {
|
|
198
|
+
return async transaction => {
|
|
199
|
+
const article = await this.findArticle({
|
|
200
|
+
articleId,
|
|
201
|
+
transaction,
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
if (!article) {
|
|
205
|
+
throw this.errorHash.ArticleNotFound.create()
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
article.set({
|
|
209
|
+
title,
|
|
210
|
+
content,
|
|
211
|
+
LastModifiedByUserId: userId,
|
|
212
|
+
lastModifiedAt: now,
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
return /** @type {*} */ (
|
|
216
|
+
article.save({
|
|
217
|
+
transaction,
|
|
218
|
+
})
|
|
219
|
+
)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
- **Why one transaction:** a `find` then `save` split across two transactions lets a concurrent
|
|
225
|
+
request interleave (`find1 → find2 → save1 → save2`) and corrupt state. Keeping them in one
|
|
226
|
+
callback serializes them.
|
|
227
|
+
- **`.set()` + `.save()`, never `.update()`** — the backup mixin needs the full row; `.update()`
|
|
228
|
+
can drop fields. Create rows with `Model.create(attributes, { include, transaction })`.
|
|
229
|
+
- **State guards throw inside the callback** (`throw this.errorHash.XxxNotFound.create()`) so the
|
|
230
|
+
transaction rolls back. Existence / ownership / no-op checks belong here, not in the validator.
|
|
231
|
+
|
|
232
|
+
Nested-create `include`, existence-count guards, associations, and post-transaction side effects
|
|
233
|
+
(work that must observe the committed result and runs **after** the commit) are in
|
|
234
|
+
[transaction.md](./references/transaction.md).
|
|
235
|
+
|
|
236
|
+
## 5. `formatResponse()` — return the save result, not a view
|
|
237
|
+
|
|
238
|
+
`formatResponse()` shapes the transaction's result into the GraphQL result type. **Return the
|
|
239
|
+
minimum that identifies what changed — usually just an id** (plus a timestamp for a delete).
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
formatResponse ({
|
|
243
|
+
article,
|
|
244
|
+
}) {
|
|
245
|
+
return {
|
|
246
|
+
articleId: article.id,
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
- **Why minimal:** a Mutation's job is to report *that* the write happened. The frontend re-fetches
|
|
252
|
+
the updated data with a **Query**. Returning a fully rendered object here duplicates the Query and
|
|
253
|
+
couples the two. Keep Mutation and Query concerns separate. See
|
|
254
|
+
[resolve-flow.md](./references/resolve-flow.md#formatresponse).
|
|
255
|
+
|
|
256
|
+
## 6. Input validation → the project's resolver-validator conventions
|
|
257
|
+
|
|
258
|
+
The resolver never inlines value checks. It builds a `*InputValidator` and runs it; the validator
|
|
259
|
+
returns an `InvalidXxx` error (or `null`).
|
|
260
|
+
|
|
261
|
+
```js
|
|
262
|
+
createInputValidator ({
|
|
263
|
+
input,
|
|
264
|
+
}) {
|
|
265
|
+
return UpdateArticleInputValidator.create({
|
|
266
|
+
errorHash: this.errorHash,
|
|
267
|
+
input,
|
|
268
|
+
})
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
validateInput ({
|
|
272
|
+
input,
|
|
273
|
+
}) {
|
|
274
|
+
return this.createInputValidator({
|
|
275
|
+
input,
|
|
276
|
+
})
|
|
277
|
+
.validateInput()
|
|
278
|
+
}
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
Write the `*InputValidator` itself following the project's resolver-validator conventions. Split of
|
|
282
|
+
duty: **shape/format → validator; existence/ownership/state → transaction callback (§4).**
|
|
283
|
+
|
|
284
|
+
## 7. Dependency injection — only when a dependency is needed
|
|
285
|
+
|
|
286
|
+
Simple resolvers need **no** constructor or factory: the base `create({ errorCodeHash })` builds the
|
|
287
|
+
error hash for you. Add a `constructor` + `static create ()` + `static createXxx ()` factory helpers
|
|
288
|
+
**only** when the resolver depends on a tool (token generator, encipher, random-text generator, …)
|
|
289
|
+
that tests must be able to substitute.
|
|
290
|
+
|
|
291
|
+
```js
|
|
292
|
+
constructor ({
|
|
293
|
+
accessTokenGenerator,
|
|
294
|
+
...remainingParams
|
|
295
|
+
}) {
|
|
296
|
+
super(remainingParams)
|
|
297
|
+
|
|
298
|
+
this.accessTokenGenerator = accessTokenGenerator
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
static create ({
|
|
302
|
+
accessTokenGenerator = this.createAccessTokenGenerator(),
|
|
303
|
+
errorCodeHash = this.errorCodeHash,
|
|
304
|
+
} = {}) {
|
|
305
|
+
const errorHash = this.buildErrorHash({
|
|
306
|
+
errorCodeHash,
|
|
307
|
+
})
|
|
308
|
+
|
|
309
|
+
return new this({
|
|
310
|
+
accessTokenGenerator,
|
|
311
|
+
errorHash,
|
|
312
|
+
})
|
|
313
|
+
}
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
- **Why inject:** hard-`new`-ing a token/crypto tool inside a method makes the resolver untestable
|
|
317
|
+
and hides its collaborators. A default-valued factory keeps production calls a plain `.create()`
|
|
318
|
+
while letting a test pass a fake. Full pattern in
|
|
319
|
+
[dependency-injection.md](./references/dependency-injection.md).
|
|
320
|
+
|
|
321
|
+
## 8. Heavy or slow work → a Worker, not the resolver
|
|
322
|
+
|
|
323
|
+
A resolver responds **synchronously**; it must stay fast. If the operation is slow or uncertain
|
|
324
|
+
(external API, AI call, bulk records, file generation), the resolver should **enqueue a job and
|
|
325
|
+
return immediately** — the real work runs in a Worker. Decide following the project's
|
|
326
|
+
execution-placement-pattern conventions, and implement the Worker following the project's
|
|
327
|
+
renchan-job-bullmq conventions. When in doubt, push to the Worker.
|
|
328
|
+
|
|
329
|
+
## Testing
|
|
330
|
+
|
|
331
|
+
Test the resolver following the project's jest rules, split across **two locations by whether
|
|
332
|
+
the test writes to the DB**:
|
|
333
|
+
|
|
334
|
+
- **No writes → `tests/__tests__/`** (mirror the resolver's source path). Static getters
|
|
335
|
+
(`schema`, `errorCodeHash`), `createInputValidator` / `validateInput` (validator **mocked** via
|
|
336
|
+
`jest.spyOn`), `formatResponse` (pure), and the DI factory (§7). Jest auto-discovers every `.js`
|
|
337
|
+
under `__tests__/`; these run independently, in any order, and hit no DB.
|
|
338
|
+
- **Writes → `tests/_orders/<Category>/mutations/<Resolver>.js`**. `generateTransactionCallback`
|
|
339
|
+
(run through `Model.beginTransaction`) and `resolve` (full flow) against the seeded DB — assert a
|
|
340
|
+
valid input persists the row, a missing row throws the `204.*` and rolls back, etc. `<Category>`
|
|
341
|
+
is the **model the resolver writes to** (`CreateArticle` → `Article`). Ordering within a category
|
|
342
|
+
is guaranteed by its `_.test.js`, which `import`s each write file in sequence — add an import line
|
|
343
|
+
there when you add a test, or it never runs.
|
|
344
|
+
|
|
345
|
+
Everything else (unique fake data, `test.each`, `describe` branches, AAA, mocks) follows the
|
|
346
|
+
project-wide jest rules unchanged. Full placement detail in [testing.md](./references/testing.md).
|
|
347
|
+
|
|
348
|
+
## Detail files
|
|
349
|
+
|
|
350
|
+
- [resolve-flow.md](./references/resolve-flow.md) — the full resolver template (every method with
|
|
351
|
+
JSDoc), method order, `createInputValidator`/`validateInput`, and `formatResponse` shapes (§2,§5,§6)
|
|
352
|
+
- [transaction.md](./references/transaction.md) — `generateTransactionCallback` in depth:
|
|
353
|
+
one-transaction rule, `beginTransaction`, nested-create `include`, existence guards, `.set()`+
|
|
354
|
+
`.save()` vs `.update()`, throwing state errors, post-commit side effects (§4)
|
|
355
|
+
- [errors.md](./references/errors.md) — `errorCodeHash` categories (203/204/205), `M###` numbering,
|
|
356
|
+
`this.errorHash.<Name>.create()`, and how the base builds the error hash (§3)
|
|
357
|
+
- [dependency-injection.md](./references/dependency-injection.md) — `constructor` + `static create()`
|
|
358
|
+
+ `static createXxx()` factory helpers, when to inject, `buildErrorHash` wiring (§7)
|
|
359
|
+
- [testing.md](./references/testing.md) — the `tests/__tests__/` (no-write) vs `tests/_orders/`
|
|
360
|
+
(write, ordered by `_.test.js`) placement split, what to test in each, and the category rule
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# Dependency injection — constructor + factory helpers
|
|
2
|
+
|
|
3
|
+
Most mutation resolvers need **no** constructor and no `create()`: the base
|
|
4
|
+
`BaseResolver.create({ errorCodeHash })` builds the error hash and constructs the resolver for you.
|
|
5
|
+
Add the injection triple **only** when the resolver depends on a collaborator that tests must be
|
|
6
|
+
able to replace.
|
|
7
|
+
|
|
8
|
+
## When to inject
|
|
9
|
+
|
|
10
|
+
Inject when the resolver uses a **tool with side effects or nondeterminism** that a test cannot let
|
|
11
|
+
run for real:
|
|
12
|
+
|
|
13
|
+
- a random-text generator (`RandomTextGenerator`) — random ids / tokens,
|
|
14
|
+
- an encipher (`Encipher`) — password hashing / compare,
|
|
15
|
+
- a token generator (`AccessTokenGenerator`) — nondeterministic output,
|
|
16
|
+
- any external client.
|
|
17
|
+
|
|
18
|
+
Do **not** inject models or the validator — models are imported directly and used statically; the
|
|
19
|
+
validator is built inline in `createInputValidator` (a test stubs that method). If the resolver only
|
|
20
|
+
does validate → transaction → format with plain model calls, skip this file entirely.
|
|
21
|
+
|
|
22
|
+
## The triple: constructor, factory, per-dependency creators
|
|
23
|
+
|
|
24
|
+
The example: a `createArticle` resolver that needs a `RandomTextGenerator` to generate a public id.
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
import {
|
|
28
|
+
RandomTextGenerator,
|
|
29
|
+
} from '@openreachtech/renchan-tools'
|
|
30
|
+
|
|
31
|
+
import {
|
|
32
|
+
BaseMutationResolver,
|
|
33
|
+
} from '@openreachtech/renchan'
|
|
34
|
+
|
|
35
|
+
export default class CreateArticleMutationResolver extends BaseMutationResolver {
|
|
36
|
+
/** @override */
|
|
37
|
+
static get schema () {
|
|
38
|
+
return 'createArticle'
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {{
|
|
43
|
+
* randomTextGenerator: RandomTextGenerator
|
|
44
|
+
* errorHash: object
|
|
45
|
+
* }} params
|
|
46
|
+
*/
|
|
47
|
+
constructor ({
|
|
48
|
+
randomTextGenerator,
|
|
49
|
+
...remainingParams
|
|
50
|
+
}) {
|
|
51
|
+
super(remainingParams)
|
|
52
|
+
|
|
53
|
+
this.randomTextGenerator = randomTextGenerator
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Factory method.
|
|
58
|
+
*
|
|
59
|
+
* @param {{
|
|
60
|
+
* randomTextGenerator?: RandomTextGenerator
|
|
61
|
+
* errorCodeHash?: object
|
|
62
|
+
* }} [params]
|
|
63
|
+
* @returns {CreateArticleMutationResolver}
|
|
64
|
+
*/
|
|
65
|
+
static create ({
|
|
66
|
+
randomTextGenerator = this.createRandomTextGenerator(),
|
|
67
|
+
errorCodeHash = this.errorCodeHash,
|
|
68
|
+
} = {}) {
|
|
69
|
+
const errorHash = this.buildErrorHash({
|
|
70
|
+
errorCodeHash,
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
return new this({
|
|
74
|
+
randomTextGenerator,
|
|
75
|
+
errorHash,
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @returns {RandomTextGenerator}
|
|
81
|
+
*/
|
|
82
|
+
static createRandomTextGenerator () {
|
|
83
|
+
return RandomTextGenerator.create()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** @override */
|
|
87
|
+
static get errorCodeHash () {
|
|
88
|
+
return {
|
|
89
|
+
...super.errorCodeHash,
|
|
90
|
+
// ...
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// resolve(), generateTransactionCallback(), etc.
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* @returns {string}
|
|
98
|
+
*/
|
|
99
|
+
generateIdHash () {
|
|
100
|
+
return this.randomTextGenerator.generate()
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The three parts, in order (right after `schema` / before `errorCodeHash` per the method order in the
|
|
106
|
+
[SKILL](../SKILL.md#2-the-resolve-flow-and-method-order)):
|
|
107
|
+
|
|
108
|
+
1. **`constructor ({ <deps>, ...remainingParams })`** — assign each dependency to `this`, and pass
|
|
109
|
+
`remainingParams` (which carries `errorHash`) straight to `super()`. Never swallow `errorHash`.
|
|
110
|
+
2. **`static create ({ <dep> = this.create<Dep>(), errorCodeHash = this.errorCodeHash } = {})`** —
|
|
111
|
+
each dependency **defaults to its creator**, so production calls stay a bare
|
|
112
|
+
`SomeResolver.create()`. Build the error hash with `this.buildErrorHash({ errorCodeHash })` and
|
|
113
|
+
pass it as `errorHash` (the base's own `create()` did this for you; once you override `create()`
|
|
114
|
+
you must do it yourself).
|
|
115
|
+
3. **`static create<Dep> ()`** — one tiny creator per dependency returning the real instance
|
|
116
|
+
(`return RandomTextGenerator.create()`). This is the single seam a test overrides.
|
|
117
|
+
|
|
118
|
+
## Why this shape
|
|
119
|
+
|
|
120
|
+
- **Testability.** A test calls `SomeResolver.create({ randomTextGenerator: fakeGenerator })` (or
|
|
121
|
+
spies on `createRandomTextGenerator`) and asserts behavior deterministically. Hard-`new`-ing the
|
|
122
|
+
tool inside a method would make that impossible.
|
|
123
|
+
- **Production stays trivial.** Because every dependency has a default, callers that don't care
|
|
124
|
+
write `.create()` and get the real wiring — the injection is invisible until a test needs it.
|
|
125
|
+
- **`errorHash` still flows.** Overriding `create()` must not drop the base's error-hash build;
|
|
126
|
+
`...remainingParams` + `buildErrorHash` keep the error mechanism ([errors.md](./errors.md))
|
|
127
|
+
intact.
|
|
128
|
+
|
|
129
|
+
## Use the dependency inside methods via a thin wrapper
|
|
130
|
+
|
|
131
|
+
Reach the injected tool through a one-line instance method, not by scattering `this.<dep>.foo()`
|
|
132
|
+
across the class — it names the intent and gives tests one more seam:
|
|
133
|
+
|
|
134
|
+
```js
|
|
135
|
+
generateIdHash () {
|
|
136
|
+
return this.randomTextGenerator.generate()
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async verifyPassword ({
|
|
140
|
+
originalPassword,
|
|
141
|
+
passwordHash,
|
|
142
|
+
}) {
|
|
143
|
+
return this.encipher.compare(
|
|
144
|
+
originalPassword,
|
|
145
|
+
passwordHash
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
```
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# errorCodeHash, error codes, and throwing
|
|
2
|
+
|
|
3
|
+
Every error a mutation resolver can raise is declared once in `static get errorCodeHash ()`. The
|
|
4
|
+
base turns that hash into constructable error classes on `this.errorHash`, and the resolver throws
|
|
5
|
+
them by name.
|
|
6
|
+
|
|
7
|
+
## Declaring the hash
|
|
8
|
+
|
|
9
|
+
Spread `...super.errorCodeHash` first (so framework-level codes stay), then add this resolver's
|
|
10
|
+
errors grouped by category with a blank line and a comment between groups:
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
/** @override */
|
|
14
|
+
static get errorCodeHash () {
|
|
15
|
+
return {
|
|
16
|
+
...super.errorCodeHash,
|
|
17
|
+
|
|
18
|
+
// Invalid Input Errors
|
|
19
|
+
InvalidEmail: '203.M024.001',
|
|
20
|
+
InvalidPassword: '203.M024.002',
|
|
21
|
+
|
|
22
|
+
// Database Errors
|
|
23
|
+
UserNotFound: '204.M024.001',
|
|
24
|
+
|
|
25
|
+
// Authentication Errors
|
|
26
|
+
InvalidCredentials: '205.M024.001',
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## The code string: `<category>.<M###>.<seq>`
|
|
32
|
+
|
|
33
|
+
Each value is a dotted string with three parts:
|
|
34
|
+
|
|
35
|
+
- **`<category>`** — the leading segment classifies the failure:
|
|
36
|
+
- `203` — **invalid input**. Names are `InvalidXxx` and correspond 1:1 to the validator's
|
|
37
|
+
predicates (`InvalidTitle` ↔ `isValidTitle`), per the project's resolver-validator conventions.
|
|
38
|
+
- `204` — **DB / state**. `XxxNotFound`, `NotAllowedToXxx`, `CurrentXxxIsSameAsTheNewOne`. Thrown
|
|
39
|
+
from inside the transaction callback ([transaction.md](./transaction.md)).
|
|
40
|
+
- `205` — **auth**. `InvalidCredentials` and the like.
|
|
41
|
+
- **`<M###>`** — the resolver's own identifier (`M024`, `M027`, `M043`, …). All codes in one
|
|
42
|
+
resolver share the same `M###`; it is unique per resolver so a code pins down which resolver
|
|
43
|
+
raised it.
|
|
44
|
+
- **`<seq>`** — a zero-padded running number within the resolver (`001`, `002`, …). Numbering is
|
|
45
|
+
usually contiguous within a category; a gap from a removed code is fine — do not renumber existing
|
|
46
|
+
codes (they may be referenced by clients).
|
|
47
|
+
|
|
48
|
+
- **Name = the reason, not the field alone.** `InvalidPublishedAt`, `TagNotFound`,
|
|
49
|
+
`NotAllowedToEditArticle` — read as a sentence at the throw site. No `info`/`data`/`error`
|
|
50
|
+
suffixes.
|
|
51
|
+
|
|
52
|
+
## Throwing
|
|
53
|
+
|
|
54
|
+
The base's factory runs `buildErrorHash({ errorCodeHash })`, which maps each `{ Name: code }` to a
|
|
55
|
+
`RenchanGraphqlError` subclass and stores them on `this.errorHash` (also reachable as `this.Error`).
|
|
56
|
+
Construct and throw with `.create()`:
|
|
57
|
+
|
|
58
|
+
```js
|
|
59
|
+
throw this.errorHash.ArticleNotFound.create()
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- **Input errors** are returned by the validator and re-thrown at the top of `resolve()`
|
|
63
|
+
(`if (validationError) throw validationError`).
|
|
64
|
+
- **State/auth errors** are thrown **inside the transaction callback** so the transaction rolls
|
|
65
|
+
back (`throw this.errorHash.UserNotFound.create()`).
|
|
66
|
+
- Both categories surface to the client as GraphQL errors carrying the declared code.
|
|
67
|
+
|
|
68
|
+
## How the base wires it (for reference)
|
|
69
|
+
|
|
70
|
+
You do not write this — it comes from `BaseResolver` — but knowing it explains why the hash is all
|
|
71
|
+
you declare:
|
|
72
|
+
|
|
73
|
+
```js
|
|
74
|
+
// BaseResolver.create() → buildErrorHash() builds the classes from your codes
|
|
75
|
+
static create ({
|
|
76
|
+
errorCodeHash = this.errorCodeHash,
|
|
77
|
+
} = {}) {
|
|
78
|
+
const errorHash = this.buildErrorHash({
|
|
79
|
+
errorCodeHash,
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
return new this({
|
|
83
|
+
errorHash,
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// buildErrorHash: { Name: code } → { Name: RenchanGraphqlError subclass }
|
|
88
|
+
static buildErrorHash ({
|
|
89
|
+
errorCodeHash = this.errorCodeHash,
|
|
90
|
+
} = {}) {
|
|
91
|
+
return Object.fromEntries(
|
|
92
|
+
Object.entries(errorCodeHash)
|
|
93
|
+
.map(([errorName, code]) => [
|
|
94
|
+
errorName,
|
|
95
|
+
RenchanGraphqlError.declareGraphqlError({
|
|
96
|
+
code,
|
|
97
|
+
}),
|
|
98
|
+
])
|
|
99
|
+
)
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
So: declare `{ Name: 'code' }` in `errorCodeHash`, and throw `this.errorHash.Name.create()`. When a
|
|
104
|
+
resolver injects dependencies via its own `static create()`, it must still call
|
|
105
|
+
`this.buildErrorHash({ errorCodeHash })` and pass the result as `errorHash` to the constructor —
|
|
106
|
+
see [dependency-injection.md](./dependency-injection.md).
|
|
107
|
+
|
|
108
|
+
## Optional: a local ErrorHash typedef
|
|
109
|
+
|
|
110
|
+
For editor help you may add a `@typedef` naming the errors the resolver throws, and annotate the
|
|
111
|
+
throw site. It documents the contract but is optional:
|
|
112
|
+
|
|
113
|
+
```js
|
|
114
|
+
/**
|
|
115
|
+
* @typedef {{
|
|
116
|
+
* ArticleNotFound: RenchanGraphqlErrorCtor
|
|
117
|
+
* NotAllowedToEditArticle: RenchanGraphqlErrorCtor
|
|
118
|
+
* }} ErrorHash
|
|
119
|
+
*/
|
|
120
|
+
```
|