@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.
Files changed (126) hide show
  1. package/LICENSE +201 -0
  2. package/README.ja.md +135 -0
  3. package/README.md +135 -0
  4. package/dist/skills/hor-agent-loop/SKILL.md +123 -0
  5. package/dist/skills/hor-agent-loop/references/core.md +485 -0
  6. package/dist/skills/hor-agent-loop/references/graphql-integration.md +178 -0
  7. package/dist/skills/hor-agent-loop/references/renchan-job-integration.md +368 -0
  8. package/dist/skills/hor-agent-loop/references/testing.md +492 -0
  9. package/dist/skills/hor-ai-agent-structure/SKILL.md +403 -0
  10. package/dist/skills/hor-ai-agent-structure/references/loop-and-actions.md +100 -0
  11. package/dist/skills/hor-ai-prompt-document-store/SKILL.md +220 -0
  12. package/dist/skills/hor-ai-prompt-document-store/references/models-and-composition.md +156 -0
  13. package/dist/skills/hor-backend-testing/SKILL.md +118 -0
  14. package/dist/skills/hor-backend-testing/references/placement-and-ordering.md +89 -0
  15. package/dist/skills/hor-backend-testing/references/purity-and-mocks.md +82 -0
  16. package/dist/skills/hor-backend-testing/references/running-tests.md +186 -0
  17. package/dist/skills/hor-bank-id/SKILL.md +91 -0
  18. package/dist/skills/hor-build-e2e-test-environment/SKILL.md +609 -0
  19. package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +368 -0
  20. package/dist/skills/hor-build-e2e-test-environment/references/edge-and-proxy.md +287 -0
  21. package/dist/skills/hor-build-e2e-test-environment/references/environment-and-ports.md +201 -0
  22. package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +330 -0
  23. package/dist/skills/hor-build-e2e-test-environment/references/seed-data.md +145 -0
  24. package/dist/skills/hor-build-e2e-test-environment/references/windows-runner.md +146 -0
  25. package/dist/skills/hor-constant-definition/SKILL.md +139 -0
  26. package/dist/skills/hor-cookie-authentication/SKILL.md +33 -0
  27. package/dist/skills/hor-cookie-authentication/references/auth-filter.md +55 -0
  28. package/dist/skills/hor-cookie-authentication/references/cookie-context.md +53 -0
  29. package/dist/skills/hor-cookie-authentication/references/dev-login-seeder.md +22 -0
  30. package/dist/skills/hor-cookie-authentication/references/environment.md +64 -0
  31. package/dist/skills/hor-cookie-authentication/references/error-codes.md +24 -0
  32. package/dist/skills/hor-cookie-authentication/references/migrations.md +18 -0
  33. package/dist/skills/hor-cookie-authentication/references/resolvers.md +97 -0
  34. package/dist/skills/hor-cookie-authentication/references/session-clerk.md +41 -0
  35. package/dist/skills/hor-cookie-authentication/references/token-models.md +125 -0
  36. package/dist/skills/hor-database-design/SKILL.md +54 -0
  37. package/dist/skills/hor-database-design/references/column-types.md +92 -0
  38. package/dist/skills/hor-database-design/references/datetimes.md +88 -0
  39. package/dist/skills/hor-database-design/references/master-tables.md +117 -0
  40. package/dist/skills/hor-database-design/references/normalization.md +40 -0
  41. package/dist/skills/hor-database-design/references/update-history.md +35 -0
  42. package/dist/skills/hor-execution-placement-pattern/SKILL.md +216 -0
  43. package/dist/skills/hor-external-api-client/SKILL.md +99 -0
  44. package/dist/skills/hor-external-api-client/references/architecture.md +127 -0
  45. package/dist/skills/hor-external-api-client/references/authorization.md +105 -0
  46. package/dist/skills/hor-external-api-client/references/capsule.md +130 -0
  47. package/dist/skills/hor-external-api-client/references/conventions.md +68 -0
  48. package/dist/skills/hor-external-api-client/references/launcher.md +138 -0
  49. package/dist/skills/hor-external-api-client/references/payload.md +176 -0
  50. package/dist/skills/hor-external-api-client/references/sdk-wrapper.md +291 -0
  51. package/dist/skills/hor-external-api-client/references/testing.md +130 -0
  52. package/dist/skills/hor-external-api-client/references/usage.md +152 -0
  53. package/dist/skills/hor-graphql-schema/SKILL.md +360 -0
  54. package/dist/skills/hor-graphql-server-engine/SKILL.md +356 -0
  55. package/dist/skills/hor-light-rag/SKILL.md +242 -0
  56. package/dist/skills/hor-light-rag/references/retrieval-internals.md +143 -0
  57. package/dist/skills/hor-multi-llm-provider/SKILL.md +288 -0
  58. package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +153 -0
  59. package/dist/skills/hor-mutation-resolver/SKILL.md +360 -0
  60. package/dist/skills/hor-mutation-resolver/references/dependency-injection.md +148 -0
  61. package/dist/skills/hor-mutation-resolver/references/errors.md +120 -0
  62. package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +275 -0
  63. package/dist/skills/hor-mutation-resolver/references/testing.md +125 -0
  64. package/dist/skills/hor-mutation-resolver/references/transaction.md +197 -0
  65. package/dist/skills/hor-post-worker/SKILL.md +320 -0
  66. package/dist/skills/hor-query-resolver/SKILL.md +246 -0
  67. package/dist/skills/hor-query-resolver/references/anatomy.md +384 -0
  68. package/dist/skills/hor-query-resolver/references/data-access.md +248 -0
  69. package/dist/skills/hor-query-resolver/references/errors-and-context.md +172 -0
  70. package/dist/skills/hor-query-resolver/references/testing.md +241 -0
  71. package/dist/skills/hor-renchan-job-bullmq/SKILL.md +178 -0
  72. package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +182 -0
  73. package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +106 -0
  74. package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +189 -0
  75. package/dist/skills/hor-renchan-job-bullmq/references/queues.md +74 -0
  76. package/dist/skills/hor-renchan-job-bullmq/references/subscriptions.md +113 -0
  77. package/dist/skills/hor-resolver-share/SKILL.md +262 -0
  78. package/dist/skills/hor-resolver-validator/SKILL.md +194 -0
  79. package/dist/skills/hor-resolver-validator/references/inspector-api.md +115 -0
  80. package/dist/skills/hor-resolver-validator/references/validator-pattern.md +281 -0
  81. package/dist/skills/hor-restfulapi-architecture/SKILL.md +275 -0
  82. package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +192 -0
  83. package/dist/skills/hor-restfulapi-architecture/references/renderers.md +204 -0
  84. package/dist/skills/hor-restfulapi-architecture/references/response-and-flusher.md +118 -0
  85. package/dist/skills/hor-restfulapi-architecture/references/validation.md +229 -0
  86. package/dist/skills/hor-security-audit/SKILL.md +110 -0
  87. package/dist/skills/hor-security-audit/references/application-surface.md +90 -0
  88. package/dist/skills/hor-security-audit/references/auth-and-transport.md +147 -0
  89. package/dist/skills/hor-security-audit/references/code-safety.md +74 -0
  90. package/dist/skills/hor-security-audit/references/dependencies.md +72 -0
  91. package/dist/skills/hor-security-audit/references/network-and-logging.md +56 -0
  92. package/dist/skills/hor-security-audit/references/secrets.md +95 -0
  93. package/dist/skills/hor-sequelize-migration/SKILL.md +336 -0
  94. package/dist/skills/hor-sequelize-migration/references/alter-table.md +147 -0
  95. package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +107 -0
  96. package/dist/skills/hor-sequelize-migration/references/indexes.md +149 -0
  97. package/dist/skills/hor-sequelize-migration/references/notation.md +215 -0
  98. package/dist/skills/hor-sequelize-model/SKILL.md +69 -0
  99. package/dist/skills/hor-sequelize-model/references/associations.md +218 -0
  100. package/dist/skills/hor-sequelize-model/references/default-methods.md +244 -0
  101. package/dist/skills/hor-sequelize-model/references/mixins.md +247 -0
  102. package/dist/skills/hor-sequelize-model/references/notation.md +225 -0
  103. package/dist/skills/hor-sequelize-model/references/timestamps.md +74 -0
  104. package/dist/skills/hor-sequelize-seeder/SKILL.md +275 -0
  105. package/dist/skills/hor-sequelize-seeder/references/development-coverage.md +74 -0
  106. package/dist/skills/hor-sequelize-seeder/references/directory-structure.md +113 -0
  107. package/dist/skills/hor-sequelize-seeder/references/id-numbering.md +133 -0
  108. package/dist/skills/hor-sequelize-seeder/references/naming.md +59 -0
  109. package/dist/skills/hor-sequelize-seeder/references/notation.md +170 -0
  110. package/dist/skills/hor-sequelize-subquery/SKILL.md +369 -0
  111. package/dist/skills/hor-strategy-pattern/SKILL.md +371 -0
  112. package/dist/skills/hor-stub-api/SKILL.md +330 -0
  113. package/dist/skills/hor-subscription-resolver/SKILL.md +105 -0
  114. package/dist/skills/hor-subscription-resolver/references/authentication.md +99 -0
  115. package/dist/skills/hor-subscription-resolver/references/basic-notation.md +116 -0
  116. package/dist/skills/hor-subscription-resolver/references/design-philosophy.md +68 -0
  117. package/dist/skills/hor-type-interface/SKILL.md +200 -0
  118. package/docs/skills.ja.md +40 -0
  119. package/docs/skills.md +40 -0
  120. package/lib/equip/CommandLineArguments.js +178 -0
  121. package/lib/equip/HoraSkillsCli.js +590 -0
  122. package/lib/equip/SkillsInstaller.js +443 -0
  123. package/lib/equip/SkillsManifestFile.js +260 -0
  124. package/lib/equip/constants/CLI_COMMAND.js +8 -0
  125. package/lib/equip/hora-skills-ort-renchan.js +8 -0
  126. package/package.json +51 -0
@@ -0,0 +1,275 @@
1
+ # The resolver template (resolve flow, validator wiring, formatResponse)
2
+
3
+ The full shape of a mutation resolver, with every standard method filled in. Copy this skeleton and
4
+ replace the operation-specific parts (models, guards, columns). Keep the method **order** and the
5
+ `resolve()` **flow** identical across resolvers — see the [SKILL](../SKILL.md#2-the-resolve-flow-and-method-order).
6
+
7
+ > Examples use a generic `Article` entity (fields `title` / `content`, audit columns
8
+ > `CreatedByUserId` / `LastModifiedByUserId` / `lastModifiedAt`). Swap in your own model.
9
+
10
+ ## Full template
11
+
12
+ ```js
13
+ import {
14
+ BaseMutationResolver,
15
+ } from '@openreachtech/renchan'
16
+
17
+ import UpdateArticleInputValidator from '../../../../../../app/validator/forResolver/user/mutations/UpdateArticleInputValidator.js'
18
+
19
+ import Article from '../../../../../../sequelize/models/Article.js'
20
+
21
+ export default class UpdateArticleMutationResolver extends BaseMutationResolver {
22
+ /** @override */
23
+ static get schema () {
24
+ return 'updateArticle'
25
+ }
26
+
27
+ /** @override */
28
+ static get errorCodeHash () {
29
+ return {
30
+ ...super.errorCodeHash,
31
+
32
+ // Invalid Input Errors
33
+ InvalidArticleId: '203.M012.001',
34
+ InvalidContent: '203.M012.002',
35
+ InvalidTitle: '203.M012.003',
36
+
37
+ // Database Errors
38
+ ArticleNotFound: '204.M012.002',
39
+ CurrentArticleContentIsSameAsTheNewOne: '204.M012.003',
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Resolve method
45
+ *
46
+ * @param {{
47
+ * variables: {
48
+ * input: server.graphql.user.UpdateArticleInput
49
+ * }
50
+ * context: UserGraphqlContext
51
+ * }} params
52
+ * @returns {Promise<server.graphql.user.UpdateArticleResult>}
53
+ */
54
+ async resolve ({
55
+ variables: {
56
+ input,
57
+ },
58
+ context,
59
+ }) {
60
+ const validationError = this.validateInput({
61
+ input,
62
+ })
63
+
64
+ if (validationError) {
65
+ throw validationError
66
+ }
67
+
68
+ const callback = this.generateTransactionCallback({
69
+ input,
70
+ context,
71
+ })
72
+
73
+ const article = await Article.beginTransaction(callback)
74
+
75
+ return this.formatResponse({
76
+ article,
77
+ })
78
+ }
79
+
80
+ /**
81
+ * Create an input validator instance
82
+ *
83
+ * @param {{ input: server.graphql.user.UpdateArticleInput }} params
84
+ * @returns {UpdateArticleInputValidator}
85
+ */
86
+ createInputValidator ({
87
+ input,
88
+ }) {
89
+ return UpdateArticleInputValidator.create({
90
+ errorHash: this.errorHash,
91
+ input,
92
+ })
93
+ }
94
+
95
+ /**
96
+ * Validate the input
97
+ *
98
+ * @param {{ input: server.graphql.user.UpdateArticleInput }} params
99
+ * @returns {import('@openreachtech/renchan').RenchanGraphqlError | null}
100
+ */
101
+ validateInput ({
102
+ input,
103
+ }) {
104
+ return this.createInputValidator({
105
+ input,
106
+ })
107
+ .validateInput()
108
+ }
109
+
110
+ /**
111
+ * Generate the transaction callback
112
+ *
113
+ * @param {{
114
+ * input: server.graphql.user.UpdateArticleInput
115
+ * context: UserGraphqlContext
116
+ * }} params
117
+ * @returns {(transaction?: import('sequelize').Transaction) => Promise<model.ArticleEntity>}
118
+ */
119
+ generateTransactionCallback ({
120
+ input: {
121
+ title,
122
+ content,
123
+ articleId,
124
+ },
125
+ context: {
126
+ now,
127
+ userId,
128
+ },
129
+ }) {
130
+ return async transaction => {
131
+ const article = await this.findArticle({
132
+ articleId,
133
+ transaction,
134
+ })
135
+
136
+ if (!article) {
137
+ throw this.errorHash.ArticleNotFound.create()
138
+ }
139
+
140
+ if (
141
+ article.content === content
142
+ && article.title === title
143
+ ) {
144
+ throw this.errorHash.CurrentArticleContentIsSameAsTheNewOne.create()
145
+ }
146
+
147
+ article.set({
148
+ title,
149
+ content,
150
+ LastModifiedByUserId: userId,
151
+ lastModifiedAt: now,
152
+ })
153
+
154
+ return /** @type {*} */ (
155
+ article.save({
156
+ transaction,
157
+ })
158
+ )
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Find an article by id
164
+ *
165
+ * @param {{
166
+ * articleId: number
167
+ * transaction: import('sequelize').Transaction
168
+ * }} params
169
+ * @returns {Promise<model.ArticleEntity>}
170
+ */
171
+ async findArticle ({
172
+ articleId,
173
+ transaction,
174
+ }) {
175
+ return /** @type {*} */ (
176
+ Article.findOne({
177
+ where: {
178
+ id: articleId,
179
+ },
180
+ transaction,
181
+ })
182
+ )
183
+ }
184
+
185
+ /**
186
+ * Format the response
187
+ *
188
+ * @param {{ article: model.ArticleEntity }} params
189
+ * @returns {server.graphql.user.UpdateArticleResult}
190
+ */
191
+ formatResponse ({
192
+ article,
193
+ }) {
194
+ return {
195
+ articleId: article.id,
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * @typedef {import('../../../../contexts/UserGraphqlContext.js').default} UserGraphqlContext
202
+ */
203
+ ```
204
+
205
+ ## `resolve()` — the fixed four steps
206
+
207
+ `resolve()` never grows a fifth concern. It only:
208
+
209
+ 1. **validate** — `validateInput({ input })`; if it returns an error, `throw` it (fail before any
210
+ write).
211
+ 2. **build** — `generateTransactionCallback({ input, context })` returns the closure; it does not
212
+ run yet.
213
+ 3. **run** — `await <Model>.beginTransaction(callback)` executes the closure in one transaction and
214
+ returns its result.
215
+ 4. **format** — `return this.formatResponse({ ... })`.
216
+
217
+ Anything else (a post-commit side effect) is an explicit extra line **between step 3 and step 4**,
218
+ never logic hidden inside the four calls. Keep `resolve()` readable top-to-bottom.
219
+
220
+ - **`context`** carries `now` (request timestamp — use it, do not call `new Date()` yourself so all
221
+ rows in the request share one time) and the actor (`userId` or `user`). Destructure only what the
222
+ callback needs, and forward it into `generateTransactionCallback`.
223
+ - **Which model to call `beginTransaction` on?** Any model participating in the write works — pick
224
+ the primary entity of the operation (create → the model being created; update/delete → the model
225
+ being changed). The transaction spans all models regardless.
226
+
227
+ ## `createInputValidator` / `validateInput`
228
+
229
+ Two thin methods, always the same:
230
+
231
+ - `createInputValidator({ input })` builds the `*InputValidator` with `{ errorHash: this.errorHash,
232
+ input }` so the validator raises the resolver's own error codes.
233
+ - `validateInput({ input })` runs it and returns the error or `null`.
234
+
235
+ Keeping them as named methods (rather than inlining) lets tests stub the validator and keeps
236
+ `resolve()` at one altitude. Write the `*InputValidator` itself following the project's
237
+ resolver-validator conventions.
238
+
239
+ ## `formatResponse`
240
+
241
+ Return the **minimum identifying result**, matching the GraphQL result type:
242
+
243
+ ```js
244
+ // create / update → the id
245
+ formatResponse ({
246
+ article,
247
+ }) {
248
+ return {
249
+ articleId: article.id,
250
+ }
251
+ }
252
+
253
+ // delete → id + when it happened
254
+ formatResponse ({
255
+ article,
256
+ }) {
257
+ return {
258
+ articleId: article.id,
259
+ deletedAt: article.lastModifiedAt,
260
+ }
261
+ }
262
+ ```
263
+
264
+ Do not assemble a display object here. The mutation reports the write; the frontend re-queries for
265
+ the rendered data. A `formatResponse` that maps/sorts/joins rows is a sign business logic leaked
266
+ out of the transaction callback, or that a Query's job crept into the Mutation — pull it back. (A
267
+ resolver that skips the validator, runs no transaction, and returns a fully-built, sorted list
268
+ straight from `resolve()` is the shape to avoid.)
269
+
270
+ ## Endpoint differences
271
+
272
+ Only the **context type** and the **import depth** change between endpoints (`user` / `customer` /
273
+ `admin` / `portal`). The class skeleton, method order, and flow are identical. Keep the
274
+ `@typedef` for the context pointing at the right
275
+ `server/graphql/contexts/<Endpoint>GraphqlContext.js`.
@@ -0,0 +1,125 @@
1
+ # Testing a mutation resolver
2
+
3
+ A mutation resolver is split across **two test locations** by one question: **does the test write to
4
+ the database?** No-write tests go in `tests/__tests__/`; write tests go in `tests/_orders/`.
5
+ Everything else — `test.each`, `describe` structure, unique fake data, AAA, `jest.spyOn` mocks —
6
+ follows the project's jest rules unchanged.
7
+
8
+ > Examples use a generic `Article` resolver. Swap in your own resolver/model names.
9
+
10
+ ## Placement rule
11
+
12
+ | Test hits the DB? | Location | Discovered how | Order |
13
+ | --- | --- | --- | --- |
14
+ | **No** (pure / mocked) | `tests/__tests__/` (mirror the resolver's source path) | jest `testMatch` picks up **every `.js`** under `__tests__/` | none (independent) |
15
+ | **Yes** (real transaction) | `tests/_orders/<Category>/mutations/<Resolver>.js` | imported by the category's `_.test.js` | **guaranteed** within the category |
16
+
17
+ - **Why the split:** `__tests__` tests are independent and run in any order, so jest matches each
18
+ file directly. `_orders` tests run against the **seeded DB** and mutate shared rows — their outcome
19
+ depends on running in a fixed sequence. So jest matches **only** each category's `_.test.js`, and
20
+ that file `import`s the write tests in order. The individual write files are named `<Resolver>.js`
21
+ (not `*.test.js`) so jest does **not** pick them up on their own — they run only when `_.test.js`
22
+ imports them.
23
+
24
+ ## What goes in `tests/__tests__/` (no writes)
25
+
26
+ Mirror the resolver's source location under `tests/__tests__/`, then test the members that need no
27
+ DB — using `.create()` and `jest.spyOn` to substitute collaborators:
28
+
29
+ ```
30
+ server/graphql/resolvers/user/actual/mutations/CreateArticleMutationResolver.js
31
+ ↔ tests/__tests__/server/graphql/resolvers/user/mutations/CreateArticleMutationResolver.js
32
+ ```
33
+
34
+ Cover here:
35
+
36
+ - **`.get:schema`** and **`.get:errorCodeHash`** — static getters (single `test()` is fine; static
37
+ getters are the exception to `test.each` in the project's jest rules).
38
+ - **`#createInputValidator()` / `#validateInput()`** — assert they build/run the validator, with the
39
+ validator **mocked** (`jest.spyOn(resolver, 'createInputValidator').mockReturnValue(...)`); never
40
+ reach the real DB.
41
+ - **`#formatResponse()`** — pure shaping; feed an entity, assert the returned ids.
42
+ - **the factory / creators** (§7 DI) — `static create()` defaults and `static createXxx()` seams.
43
+
44
+ ```js
45
+ import CreateArticleMutationResolver from '../../../../../../../server/graphql/resolvers/user/actual/mutations/CreateArticleMutationResolver.js'
46
+
47
+ describe('CreateArticleMutationResolver', () => {
48
+ describe('.get:schema', () => {
49
+ test('returns the schema name', () => {
50
+ expect(CreateArticleMutationResolver.schema)
51
+ .toBe('createArticle')
52
+ })
53
+ })
54
+ })
55
+ ```
56
+
57
+ ## What goes in `tests/_orders/` (writes)
58
+
59
+ The members that actually persist — **`#generateTransactionCallback()`** (run through
60
+ `Model.beginTransaction(callback)`) and **`#resolve()`** (the full flow) — go under the category of
61
+ the **model the resolver writes to**:
62
+
63
+ ```
64
+ tests/_orders/<Category>/mutations/<Resolver>.js
65
+ ```
66
+
67
+ - **`<Category>` is the primary written model's name**, not the operation's. `CreateArticle` /
68
+ `UpdateArticle` → `tests/_orders/Article/mutations/`. When the operation writes a different model
69
+ than its name suggests (e.g. a `publishArticle` that writes an `ArticleStatus` row), the category
70
+ follows the **written** model — `tests/_orders/ArticleStatus/mutations/`.
71
+ - The file drives the real transaction against the seeded DB:
72
+
73
+ ```js
74
+ import Article from '../../../../sequelize/models/Article.js'
75
+
76
+ import CreateArticleMutationResolver from '../../../../server/graphql/resolvers/user/actual/mutations/CreateArticleMutationResolver.js'
77
+
78
+ describe('CreateArticleMutationResolver', () => {
79
+ describe('#generateTransactionCallback()', () => {
80
+ // ... cases with unique, explicit-fake seed values ...
81
+ test.each(cases)('...', async ({
82
+ params,
83
+ expected,
84
+ }) => {
85
+ const resolver = CreateArticleMutationResolver.create()
86
+
87
+ const callback = resolver.generateTransactionCallback(params)
88
+
89
+ // real write
90
+ const actual = await Article.beginTransaction(callback)
91
+
92
+ expect(actual)
93
+ .toEqual(expected)
94
+ })
95
+ })
96
+ })
97
+ ```
98
+
99
+ Cover here the write-path behavior: a valid input **creates/updates** the expected row; a missing
100
+ row throws the `204.*` `XxxNotFound`; an ownership violation throws `NotAllowedToXxx`; a no-op input
101
+ throws `CurrentXxxIsSameAsTheNewOne`. Use `describe` (not `if`) to separate the success and failure
102
+ branches — per the project's jest rules.
103
+
104
+ ## The category `_.test.js` (ordering entry point)
105
+
106
+ Each `tests/_orders/<Category>/` holds one `_.test.js` — the only file jest matches in the category.
107
+ It `import`s the category's write tests in the intended run order:
108
+
109
+ ```js
110
+ // tests/_orders/Article/_.test.js
111
+ import './mutations/CreateArticleMutationResolver.js'
112
+ import './mutations/UpdateArticleMutationResolver.js'
113
+ import './mutations/DeleteArticleMutationResolver.js'
114
+ ```
115
+
116
+ When you add a new write test, create the `<Resolver>.js` file under the category's `mutations/` and
117
+ **add one `import` line to that category's `_.test.js`** in the correct position. Without the import
118
+ line the test never runs.
119
+
120
+ ## Everything else → the project's jest rules
121
+
122
+ Data conventions (all fields unique, explicit-fake values — `title: 'string'` is weak; prefer
123
+ distinct values), `describe`/`test.each` structure, the AAA layout, and `jest.spyOn` mocking are the
124
+ same as any class test. Follow the project's jest rules; this page only adds
125
+ the **placement** rule specific to resolvers.
@@ -0,0 +1,197 @@
1
+ # generateTransactionCallback — one transaction, all writes
2
+
3
+ `generateTransactionCallback({ input, context })` is where the resolver's real work lives. It
4
+ returns a single **`async transaction => { ... }`** closure that performs **every find and save for
5
+ the request**, and it is run by `Model.beginTransaction(callback)`. This file covers the rules that
6
+ keep that closure correct.
7
+
8
+ > Examples use a generic `Article` entity (with a `Tag` many-side and a nested `ArticleCategory`
9
+ > association). Swap in your own models — the rules are what transfer.
10
+
11
+ ## The closure is built, then run
12
+
13
+ `generateTransactionCallback` returns the closure — it does not execute it. `resolve()` hands the
14
+ closure to `beginTransaction`, which opens a managed transaction, invokes the closure with the live
15
+ `transaction`, commits on success, and rolls back if the closure throws.
16
+
17
+ ```js
18
+ const callback = this.generateTransactionCallback({
19
+ input,
20
+ context,
21
+ })
22
+
23
+ // opens the transaction, runs the callback, commits (or rolls back on throw)
24
+ const article = await Article.beginTransaction(callback)
25
+ ```
26
+
27
+ - Destructure `input` and `context` **in the parameter list** of `generateTransactionCallback` so
28
+ the closure body reads flat. Pull out exactly the fields the writes need (`now`, `userId`, and the
29
+ input columns).
30
+ - The closure's return value is what `beginTransaction` resolves to and what `resolve()` passes to
31
+ `formatResponse`.
32
+
33
+ ## Rule 1 — every query takes the same `transaction`
34
+
35
+ Pass the `transaction` the closure received into **every** `findOne` / `findAll` / `create` /
36
+ `save` inside it. A query without it runs outside the transaction and defeats the point.
37
+
38
+ ```js
39
+ return async transaction => {
40
+ // every query takes the same `transaction`
41
+ const article = await this.findArticle({
42
+ articleId,
43
+ transaction,
44
+ })
45
+
46
+ // ...
47
+
48
+ return article.save({
49
+ transaction,
50
+ })
51
+ }
52
+ ```
53
+
54
+ - **Why one transaction for the whole request:** a `find` and its dependent `save` split across two
55
+ transactions let a concurrent request interleave — `find1 → find2 → save1 → save2` — and write
56
+ duplicate or stale state. One transaction serializes the read-modify-write.
57
+
58
+ ## Rule 2 — guard state inside the closure; throw to roll back
59
+
60
+ Existence, ownership, and no-op checks belong **here**, not in the validator (the validator only
61
+ knows input shape, not the DB). Throw the matching `204.*` error from `this.errorHash`; the throw
62
+ rolls the transaction back.
63
+
64
+ ```js
65
+ return async transaction => {
66
+ const article = await this.findArticle({
67
+ articleId: input.articleId,
68
+ transaction,
69
+ })
70
+
71
+ // 204.* — not found
72
+ if (!article) {
73
+ throw this.errorHash.ArticleNotFound.create()
74
+ }
75
+
76
+ // 204.* — ownership
77
+ if (
78
+ !this.isArticleAuthor({
79
+ article,
80
+ context,
81
+ })
82
+ ) {
83
+ throw this.errorHash.NotAllowedToEditArticle.create()
84
+ }
85
+
86
+ // ... proceed with the writes ...
87
+ }
88
+ ```
89
+
90
+ ```js
91
+ isArticleAuthor ({
92
+ article,
93
+ context,
94
+ }) {
95
+ return article.CreatedByUserId === context.userId
96
+ }
97
+ ```
98
+
99
+ - **A "nothing changed" guard is legitimate**: if the new values equal the current ones, throw a
100
+ `CurrentXxxIsSameAsTheNewOne` (`204.*`) rather than issuing a pointless write.
101
+ - Use early `if (...) throw` — no nested branches, no `else`. One guard per `if`.
102
+
103
+ ## Rule 3 — `.set()` + `.save()` to update; `.create()` to insert; never `.update()`
104
+
105
+ The models use a backup mixin that snapshots the full row, so a partial `.update()` can lose
106
+ fields. Always load, mutate, and save the whole instance.
107
+
108
+ ```js
109
+ // update: load → set → save
110
+ article.set({
111
+ title,
112
+ content,
113
+ LastModifiedByUserId: userId,
114
+ lastModifiedAt: now,
115
+ })
116
+
117
+ return article.save({
118
+ transaction,
119
+ })
120
+ ```
121
+
122
+ ```js
123
+ // create: one call, with nested associations via `include`
124
+ return Article.create({
125
+ title,
126
+ content,
127
+ CreatedByUserId: userId,
128
+ LastModifiedByUserId: userId,
129
+ lastModifiedAt: now,
130
+ savedAt: now,
131
+ isDeleted: false,
132
+
133
+ // nested association row
134
+ ArticleCategory: {
135
+ CategoryId: categoryId,
136
+ },
137
+ }, {
138
+ // list the child model(s) for the nested create
139
+ include: [
140
+ ArticleCategory,
141
+ ],
142
+ transaction,
143
+ })
144
+ ```
145
+
146
+ - **Nested create:** to insert an entity together with its associations in one statement, put the
147
+ child object(s) under the association name and list the child model(s) in `include`.
148
+ - **FK columns start uppercase** (`CreatedByUserId`, `CategoryId`) — the association's naming
149
+ convention, mirrored from the migration/model side.
150
+ - **Bulk existence guard:** when the input carries an id array, dedupe and count before writing —
151
+
152
+ ```js
153
+ const uniqueTagIds = [...new Set(tagIds)]
154
+
155
+ const tags = await this.findTags({
156
+ tagIds: uniqueTagIds,
157
+ transaction,
158
+ })
159
+
160
+ if (tags.length !== uniqueTagIds.length) {
161
+ throw this.errorHash.TagNotFound.create()
162
+ }
163
+ ```
164
+
165
+ Use `map` / `filter` / `Set`, not `Array#forEach` / `for`.
166
+
167
+ ## Extracting attribute-building
168
+
169
+ When the create payload is large, build it in a separate `buildXxxAttributes({ ... })` method that
170
+ returns the plain object, and keep the closure to *find-guard-create*. Place `buildXxxAttributes`
171
+ next to the closure that calls it. This keeps the transaction closure readable and the attribute
172
+ shape unit-testable on its own.
173
+
174
+ ## Side effects that must run after commit
175
+
176
+ Work that must observe the **committed** result — refreshing a denormalized read model, updating a
177
+ cache, notifying another system — runs in `resolve()` **after** `beginTransaction` returns, not
178
+ inside the closure. It reads the returned entity and does its own work.
179
+
180
+ ```js
181
+ const article = await Article.beginTransaction(callback)
182
+
183
+ // after commit: propagate the persisted row to the read side
184
+ await this.refreshReadModel({
185
+ article,
186
+ })
187
+
188
+ return this.formatResponse({
189
+ article,
190
+ })
191
+ ```
192
+
193
+ - **Why after, not inside:** the side effect should reflect data that actually committed; running it
194
+ in the transaction would act on rows that a later rollback discards.
195
+ - **If the side effect is slow or unreliable** (large re-index, external call, bulk fan-out), do not
196
+ run it inline at all — enqueue a Worker and return. Decide following the project's
197
+ execution-placement-pattern conventions.