@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,281 @@
|
|
|
1
|
+
# Validator pattern (template, base contract, integration, testing)
|
|
2
|
+
|
|
3
|
+
The full `*InputValidator` template, the `BaseInputValidator` contract, resolver wiring, and testing.
|
|
4
|
+
Referenced from [SKILL.md](../SKILL.md).
|
|
5
|
+
|
|
6
|
+
## Full template
|
|
7
|
+
|
|
8
|
+
A validator extends `BaseInputValidator`, overrides `generateValidationEntries()`, and adds one
|
|
9
|
+
`isValidX()` predicate per rule plus small `create*` helpers for the sub-validators / inspectors it
|
|
10
|
+
uses. This is the standard shape (a query validator that reuses pagination):
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
import {
|
|
14
|
+
IntegerValueInspector,
|
|
15
|
+
} from '@openreachtech/mentsu-value-inspector'
|
|
16
|
+
|
|
17
|
+
import BaseInputValidator from '../../BaseInputValidator.js'
|
|
18
|
+
import PaginationInputValidator from '../../NormalPaginationInputValidator.js'
|
|
19
|
+
|
|
20
|
+
const VALID_SORT_COLUMNS = [
|
|
21
|
+
'labelName',
|
|
22
|
+
'fieldPath',
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Class for validating input of the emailInsertableVariables query
|
|
27
|
+
*
|
|
28
|
+
* @extends {BaseInputValidator<ErrorHash, EmailInsertableVariablesInput>}
|
|
29
|
+
*/
|
|
30
|
+
export default class EmailInsertableVariablesInputValidator extends BaseInputValidator {
|
|
31
|
+
/**
|
|
32
|
+
* Generate validation entries
|
|
33
|
+
*
|
|
34
|
+
* @override
|
|
35
|
+
* @returns {Array<[() => boolean, RenchanGraphqlErrorCtor]>}
|
|
36
|
+
*/
|
|
37
|
+
generateValidationEntries () {
|
|
38
|
+
const paginationInputValidator = this.createPaginationInputValidator()
|
|
39
|
+
|
|
40
|
+
return [
|
|
41
|
+
[
|
|
42
|
+
() => paginationInputValidator.isValidLimit(),
|
|
43
|
+
this.errorHash.InvalidPaginationLimit,
|
|
44
|
+
],
|
|
45
|
+
[
|
|
46
|
+
() => paginationInputValidator.isValidOffset(),
|
|
47
|
+
this.errorHash.InvalidPaginationOffset,
|
|
48
|
+
],
|
|
49
|
+
[
|
|
50
|
+
() => paginationInputValidator.isValidSort(),
|
|
51
|
+
this.errorHash.InvalidPaginationSort,
|
|
52
|
+
],
|
|
53
|
+
[
|
|
54
|
+
() => this.isValidKeyword(),
|
|
55
|
+
this.errorHash.InvalidKeyword,
|
|
56
|
+
],
|
|
57
|
+
[
|
|
58
|
+
() => this.isValidOriginObjectCategoryId(),
|
|
59
|
+
this.errorHash.InvalidOriginObjectCategoryId,
|
|
60
|
+
],
|
|
61
|
+
]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Create a PaginationInputValidator instance
|
|
66
|
+
*
|
|
67
|
+
* @param {{
|
|
68
|
+
* input?: EmailInsertableVariablesInput
|
|
69
|
+
* }} [params]
|
|
70
|
+
* @returns {PaginationInputValidator}
|
|
71
|
+
*/
|
|
72
|
+
createPaginationInputValidator ({
|
|
73
|
+
input = this.input,
|
|
74
|
+
} = {}) {
|
|
75
|
+
return PaginationInputValidator.create({
|
|
76
|
+
input,
|
|
77
|
+
validColumns: VALID_SORT_COLUMNS,
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Validate keyword
|
|
83
|
+
*
|
|
84
|
+
* @returns {boolean}
|
|
85
|
+
*/
|
|
86
|
+
isValidKeyword () {
|
|
87
|
+
const {
|
|
88
|
+
keyword = null,
|
|
89
|
+
} = this.input
|
|
90
|
+
|
|
91
|
+
if (!keyword) {
|
|
92
|
+
return true
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return typeof keyword === 'string'
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Validate originObjectCategoryId
|
|
100
|
+
*
|
|
101
|
+
* @returns {boolean}
|
|
102
|
+
*/
|
|
103
|
+
isValidOriginObjectCategoryId () {
|
|
104
|
+
const inspector = this.createIntegerValueInspector({
|
|
105
|
+
value: this.input.originObjectCategoryId,
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
// the module has no isPositiveInteger — compose it (string-tolerant *Like)
|
|
109
|
+
return inspector.isIntegerLike()
|
|
110
|
+
&& inspector.isPositiveNumberLike()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Create an IntegerValueInspector instance
|
|
115
|
+
*
|
|
116
|
+
* @param {{
|
|
117
|
+
* value: number | string
|
|
118
|
+
* }} params
|
|
119
|
+
* @returns {IntegerValueInspector}
|
|
120
|
+
*/
|
|
121
|
+
createIntegerValueInspector ({
|
|
122
|
+
value,
|
|
123
|
+
}) {
|
|
124
|
+
return IntegerValueInspector.create({
|
|
125
|
+
value,
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @typedef {{
|
|
132
|
+
* InvalidKeyword: RenchanGraphqlErrorCtor
|
|
133
|
+
* InvalidOriginObjectCategoryId: RenchanGraphqlErrorCtor
|
|
134
|
+
* InvalidPaginationLimit: RenchanGraphqlErrorCtor
|
|
135
|
+
* InvalidPaginationOffset: RenchanGraphqlErrorCtor
|
|
136
|
+
* InvalidPaginationSort: RenchanGraphqlErrorCtor
|
|
137
|
+
* }} ErrorHash
|
|
138
|
+
*/
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @typedef {import('../../BaseInputValidator.js').RenchanGraphqlErrorCtor} RenchanGraphqlErrorCtor
|
|
142
|
+
*/
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @typedef {graphql.EmailInsertableVariablesInput} EmailInsertableVariablesInput
|
|
146
|
+
*/
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## `BaseInputValidator` contract
|
|
150
|
+
|
|
151
|
+
The base (`app/validator/forResolver/BaseInputValidator.js`) provides the logic so subclasses
|
|
152
|
+
only declare rules:
|
|
153
|
+
|
|
154
|
+
- **Instance state:** `this.input` (the resolver input) and `this.errorHash` (the resolver's error
|
|
155
|
+
constructors), supplied through the factory.
|
|
156
|
+
- **`generateValidationEntries()`** — abstract; the subclass returns
|
|
157
|
+
`Array<[() => boolean, RenchanGraphqlErrorCtor]>`.
|
|
158
|
+
- **Run entrypoint** — iterates the entries and, for the first entry whose predicate returns
|
|
159
|
+
`false`, raises that `ErrorCtor`. (Shown as `validate()` in the wiring below; use whatever the
|
|
160
|
+
actual base names it.)
|
|
161
|
+
- Generic JSDoc `@extends {BaseInputValidator<ErrorHash, InputType>}` documents the error hash and
|
|
162
|
+
input shapes for that validator.
|
|
163
|
+
|
|
164
|
+
## Predicate conventions
|
|
165
|
+
|
|
166
|
+
- **One `isValidX()` per rule**, returning a boolean, reading `this.input`. Never throw inside a
|
|
167
|
+
predicate — returning `false` is how a rule fails; the base turns that into the error.
|
|
168
|
+
- **Optional fields pass when absent:** destructure with a default and short-circuit, e.g.
|
|
169
|
+
`const { keyword = null } = this.input; if (!keyword) { return true }`.
|
|
170
|
+
- **Value-shape checks go through an inspector** via a `create*ValueInspector({ value })` helper —
|
|
171
|
+
e.g. `this.createIntegerValueInspector({ value })` then compose
|
|
172
|
+
`isIntegerLike() && isPositiveNumberLike()` (there is no `isPositiveInteger` in the module). See
|
|
173
|
+
[inspector-api.md](./inspector-api.md).
|
|
174
|
+
|
|
175
|
+
## Compose shared validators (don't re-implement pagination)
|
|
176
|
+
|
|
177
|
+
Pagination (limit / offset / sort) is validated by the shared `PaginationInputValidator`
|
|
178
|
+
(`NormalPaginationInputValidator.js`). Create it with the input and the allowed sort columns, then
|
|
179
|
+
reference its `isValidLimit()` / `isValidOffset()` / `isValidSort()` from your entries — as the
|
|
180
|
+
template does. Do the same for any other cross-cutting validator rather than duplicating its rules.
|
|
181
|
+
|
|
182
|
+
## Resolver wiring
|
|
183
|
+
|
|
184
|
+
The resolver declares the error codes (so each `InvalidXxx` has a code) and runs the validator with
|
|
185
|
+
its own `input` and `errorHash`:
|
|
186
|
+
|
|
187
|
+
```js
|
|
188
|
+
/** @override */
|
|
189
|
+
static get errorCodeHash () {
|
|
190
|
+
return {
|
|
191
|
+
...super.errorCodeHash,
|
|
192
|
+
|
|
193
|
+
InvalidKeyword: '400.C001.001',
|
|
194
|
+
InvalidOriginObjectCategoryId: '400.C001.002',
|
|
195
|
+
InvalidPaginationLimit: '400.C001.003',
|
|
196
|
+
InvalidPaginationOffset: '400.C001.004',
|
|
197
|
+
InvalidPaginationSort: '400.C001.005',
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** @override */
|
|
202
|
+
async resolve ({
|
|
203
|
+
variables: {
|
|
204
|
+
input,
|
|
205
|
+
},
|
|
206
|
+
context,
|
|
207
|
+
}) {
|
|
208
|
+
EmailInsertableVariablesInputValidator
|
|
209
|
+
.create({
|
|
210
|
+
input,
|
|
211
|
+
errorHash: this.errorHash,
|
|
212
|
+
})
|
|
213
|
+
.validate()
|
|
214
|
+
|
|
215
|
+
// ... input is now trusted ...
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
- The error names in the validator's `ErrorHash` typedef must match keys in the resolver's
|
|
220
|
+
`errorCodeHash`.
|
|
221
|
+
- `create({ input, errorHash })` and the run entrypoint come from `BaseInputValidator`; align with
|
|
222
|
+
the actual base API.
|
|
223
|
+
|
|
224
|
+
## Testing
|
|
225
|
+
|
|
226
|
+
Predicates are pure, so unit-test them directly with the `hoc-jest` skill — no
|
|
227
|
+
resolver, no DB. Instantiate the validator with a stub `errorHash` and assert each `isValidX()`, and
|
|
228
|
+
assert that invalid input raises the matching `InvalidXxx` through the run entrypoint.
|
|
229
|
+
|
|
230
|
+
```js
|
|
231
|
+
describe('EmailInsertableVariablesInputValidator', () => {
|
|
232
|
+
describe('isValidOriginObjectCategoryId', () => {
|
|
233
|
+
/* eslint-disable */
|
|
234
|
+
},
|
|
235
|
+
{
|
|
236
|
+
input: {
|
|
237
|
+
originObjectCategory const cases = [
|
|
238
|
+
{
|
|
239
|
+
input: {
|
|
240
|
+
originObjectCategoryId: 1,
|
|
241
|
+
},
|
|
242
|
+
expected: true,
|
|
243
|
+
Id: '1',
|
|
244
|
+
},
|
|
245
|
+
expected: true,
|
|
246
|
+
},
|
|
247
|
+
{
|
|
248
|
+
input: {
|
|
249
|
+
originObjectCategoryId: 0,
|
|
250
|
+
},
|
|
251
|
+
expected: false,
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
input: {
|
|
255
|
+
originObjectCategoryId: -1,
|
|
256
|
+
},
|
|
257
|
+
expected: false,
|
|
258
|
+
},
|
|
259
|
+
{
|
|
260
|
+
input: {
|
|
261
|
+
originObjectCategoryId: 'abc',
|
|
262
|
+
},
|
|
263
|
+
expected: false,
|
|
264
|
+
},
|
|
265
|
+
]
|
|
266
|
+
/* eslint-enable */
|
|
267
|
+
|
|
268
|
+
test.each(cases)('input $input', ({
|
|
269
|
+
input,
|
|
270
|
+
expected,
|
|
271
|
+
}) => {
|
|
272
|
+
const validator = EmailInsertableVariablesInputValidator.create({
|
|
273
|
+
input,
|
|
274
|
+
errorHash: {},
|
|
275
|
+
})
|
|
276
|
+
|
|
277
|
+
expect(validator.isValidOriginObjectCategoryId()).toBe(expected)
|
|
278
|
+
})
|
|
279
|
+
})
|
|
280
|
+
})
|
|
281
|
+
```
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-restfulapi-architecture
|
|
3
|
+
description: >
|
|
4
|
+
Understand and build the RESTful API layer of a renchan-style backend: the renderer architecture
|
|
5
|
+
under server/restfulapi/. Use this skill whenever the user asks how the REST API is structured,
|
|
6
|
+
where a REST endpoint lives, or how to add or edit one — a GET / POST / PUT / PATCH / DELETE
|
|
7
|
+
Renderer, its route and version, the render() entry point, the response and error hashes, the
|
|
8
|
+
per-request context and share, the engine's auth filter, and response flushers.
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# RESTful API Architecture
|
|
12
|
+
|
|
13
|
+
A skill for understanding the **REST API layer** of a renchan-style backend — the code under
|
|
14
|
+
`server/restfulapi/`. Structurally it **mirrors the GraphQL layer**: there is a per-request
|
|
15
|
+
**context**, a per-process **share**, an **engine** that wires everything to the server, and an error
|
|
16
|
+
hash declared up front. The difference is the surface: instead of a resolver returning a plain
|
|
17
|
+
object, a **renderer** returns a **`RestfulApiResponse`** carrying an HTTP **status code** plus
|
|
18
|
+
`content` or `error`, and a **flusher** writes it to the response.
|
|
19
|
+
|
|
20
|
+
> This skill is self-contained. Support classes (`BaseRestfulApiServerEngine`,
|
|
21
|
+
> `BaseGetRenderer` / `BasePostRenderer`, `RestfulApiResponse`, `BaseRestfulApiContext` /
|
|
22
|
+
> `BaseRestfulApiShare`, `BaseRestfulApiResponseFlusher`) come from the framework
|
|
23
|
+
> (`@openreachtech/renchan`). Examples use generic entities (`Article`) and generic routes;
|
|
24
|
+
> substitute your own. Some conventions below are the **target** shape — where the current repo
|
|
25
|
+
> diverges (notably input validation, §5), the improved form is described.
|
|
26
|
+
|
|
27
|
+
## Core principle: a renderer is a resolver with an HTTP envelope
|
|
28
|
+
|
|
29
|
+
One request → one **renderer**. A renderer does the same job a GraphQL resolver does — validate,
|
|
30
|
+
touch the DB / an external system, shape a result — but it speaks HTTP:
|
|
31
|
+
|
|
32
|
+
- Its return value is a **`RestfulApiResponse`** (`statusCode` + `content` / `error`), not a bare
|
|
33
|
+
object. Errors are **returned**, not thrown: `return this.errorResponseHash.Xxx.createAsError()`.
|
|
34
|
+
- It is bound to an **HTTP method + route** (`GET /v1/articles`), discovered from a **versioned
|
|
35
|
+
directory** (`renderers/v1/get/…`), not from a schema name.
|
|
36
|
+
- Everything else — the per-request **context** (`now`, `share`, `env`, the authenticated user),
|
|
37
|
+
the **error hash** declared up front, an optional **DI factory** — is the same idea as the
|
|
38
|
+
GraphQL side.
|
|
39
|
+
|
|
40
|
+
Three rules matter most:
|
|
41
|
+
|
|
42
|
+
1. **Return responses, never throw.** Every exit is a `RestfulApiResponse` — success via
|
|
43
|
+
`RestfulApiResponse.create({ statusCode, content })`, failure via
|
|
44
|
+
`this.errorResponseHash.Xxx.createAsError()`. HTTP always needs a status code, so an error
|
|
45
|
+
without one is meaningless here (§4).
|
|
46
|
+
2. **The engine owns cross-cutting concerns; the renderer owns one endpoint.** Auth (the visa
|
|
47
|
+
filter), middleware, versioning, and the standard error envelopes live on the engine (§3). The
|
|
48
|
+
renderer only knows its route, its errors, and its `render()` (§2).
|
|
49
|
+
3. **Validate at the boundary, then delegate.** REST input arrives split across `body` / `query` /
|
|
50
|
+
path params and is all string-like; normalize and validate it before touching the DB (§5).
|
|
51
|
+
|
|
52
|
+
- **Comments: English for code, the surrounding language for domain notes.** Match the neighbors.
|
|
53
|
+
|
|
54
|
+
## Layer map
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
HTTP request
|
|
58
|
+
│
|
|
59
|
+
┌────────────────────▼─────────────────────┐
|
|
60
|
+
│ Engine (BaseRestfulApiServerEngine) │ app-wide: routes, middleware,
|
|
61
|
+
│ config: pathPrefix + renderersPath │ auth filter (visa), Share/Context,
|
|
62
|
+
│ generateFilterHandler(), visaIssuers │ standardErrorEnvelopHash
|
|
63
|
+
└────────────────────┬─────────────────────┘
|
|
64
|
+
│ builds per request
|
|
65
|
+
┌────────────────────▼─────────────────────┐
|
|
66
|
+
│ Context (per request) + Share (per proc) │ now, env, share, user,
|
|
67
|
+
│ hasAuthenticated / hasAuthorized / … │ hasPathPermission (§3)
|
|
68
|
+
└────────────────────┬─────────────────────┘
|
|
69
|
+
│ render input = { body, query, context, request }
|
|
70
|
+
┌────────────────────▼─────────────────────┐
|
|
71
|
+
│ Renderer (BaseGetRenderer/BasePostRenderer)│ routePath, errorStructureHash,
|
|
72
|
+
│ passesFilter, render() → RestfulApiResponse│ passesFilter, render() (§1,§2)
|
|
73
|
+
└────────────────────┬─────────────────────┘
|
|
74
|
+
│ returns RestfulApiResponse (status + content/error) (§4)
|
|
75
|
+
┌────────────────────▼─────────────────────┐
|
|
76
|
+
│ Flusher (BaseRestfulApiResponseFlusher) │ writes status + headers + body
|
|
77
|
+
│ Json (default) / Html / Csv / Redirect │ contentType, flushResponseBody (§4)
|
|
78
|
+
└────────────────────┬─────────────────────┘
|
|
79
|
+
▼
|
|
80
|
+
HTTP response
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Request lifecycle
|
|
84
|
+
|
|
85
|
+
For each incoming request the framework's routes builder:
|
|
86
|
+
|
|
87
|
+
1. Builds the **render input** `{ body, query, context, request }` — `body` is the multer-fulfilled
|
|
88
|
+
request body, `query` is `expressRequest.query`, `context` is created async (resolves the user +
|
|
89
|
+
visa), `request` wraps the express request (path-param proxy).
|
|
90
|
+
2. If the renderer's **`passesFilter`** is `true`, skips the filter; otherwise runs the engine's
|
|
91
|
+
**filter handler** (auth). If the filter returns an error response, that short-circuits `render()`.
|
|
92
|
+
3. Calls **`renderer.render(input)`**, which returns a `RestfulApiResponse`.
|
|
93
|
+
4. Any **thrown** error is caught and converted to a `500` `RestfulApiResponse` (Unknown) — so
|
|
94
|
+
renderers should still return their own typed errors rather than relying on this.
|
|
95
|
+
5. The renderer's **flusher** writes the response (status, headers, body).
|
|
96
|
+
|
|
97
|
+
## 1. Directory, versioning, and route binding
|
|
98
|
+
|
|
99
|
+
Renderers live under `server/restfulapi/renderers/`, split **by version then by HTTP method**:
|
|
100
|
+
|
|
101
|
+
```
|
|
102
|
+
server/restfulapi/
|
|
103
|
+
AppRestfulApiServerEngine.js # the engine (§3)
|
|
104
|
+
contexts/
|
|
105
|
+
AppRestfulApiContext.js # per-request context (§3)
|
|
106
|
+
AppRestfulApiShare.js # per-process share (§3)
|
|
107
|
+
flushers/ # custom response flushers (§4)
|
|
108
|
+
renderers/
|
|
109
|
+
v1/
|
|
110
|
+
get/ <Name>Renderer.js # one file per endpoint
|
|
111
|
+
post/ <Name>Renderer.js
|
|
112
|
+
v2/
|
|
113
|
+
get/ …
|
|
114
|
+
post/ …
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
- **`renderers/<version>/<method>/<Name>Renderer.js`** — the directory encodes the **version**
|
|
118
|
+
(`v1`, `v2`) and the **HTTP method** (`get`, `post`, …). Keep the method out of the class name and
|
|
119
|
+
let the folder carry it (the repo has both `FooRenderer` and `FooGetRenderer` — prefer the
|
|
120
|
+
folder-only form for new files).
|
|
121
|
+
- **The engine selects the version.** `config.renderersPath` points at **one** version directory
|
|
122
|
+
(`renderers/v1/`) and `config.pathPrefix` (`/v1`) is prepended to every `routePath`. So
|
|
123
|
+
`routePath = '/articles'` in `renderers/v1/get/` serves **`GET /v1/articles`**. Serve another
|
|
124
|
+
version by pointing an engine at `renderers/v2/` with prefix `/v2`.
|
|
125
|
+
- **The route is `pathPrefix + routePath`, method = the renderer's `method`.** The framework
|
|
126
|
+
discovers every renderer under `renderersPath`, reads its `routePath` and `method`, and registers
|
|
127
|
+
the express route — you never wire routes by hand.
|
|
128
|
+
|
|
129
|
+
Detail in [renderers.md](./references/renderers.md).
|
|
130
|
+
|
|
131
|
+
## 2. The renderer
|
|
132
|
+
|
|
133
|
+
A renderer extends the method base (`BaseGetRenderer` / `BasePostRenderer` / `BasePutRenderer` / …)
|
|
134
|
+
and implements a small, fixed surface:
|
|
135
|
+
|
|
136
|
+
```js
|
|
137
|
+
import {
|
|
138
|
+
BaseGetRenderer,
|
|
139
|
+
RestfulApiResponse,
|
|
140
|
+
} from '@openreachtech/renchan'
|
|
141
|
+
|
|
142
|
+
export default class ArticleGetRenderer extends BaseGetRenderer {
|
|
143
|
+
/** @override */
|
|
144
|
+
static get routePath () {
|
|
145
|
+
return '/articles'
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** @override */
|
|
149
|
+
static get errorStructureHash () {
|
|
150
|
+
return {
|
|
151
|
+
ArticleNotFound: {
|
|
152
|
+
statusCode: 404,
|
|
153
|
+
errorMessage: 'Article not found',
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** @override */
|
|
159
|
+
get passesFilter () {
|
|
160
|
+
return true // public endpoint → skip the engine auth filter
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* @override
|
|
165
|
+
* @param {RestfulApiType.RenderInput<*, *>} input
|
|
166
|
+
* @returns {Promise<RestfulApiType.RenderResponse>}
|
|
167
|
+
*/
|
|
168
|
+
async render ({
|
|
169
|
+
query,
|
|
170
|
+
context,
|
|
171
|
+
request,
|
|
172
|
+
}) {
|
|
173
|
+
const article = await this.findArticle({
|
|
174
|
+
articleId: request.pathParameterHashProxy.articleId,
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
if (!article) {
|
|
178
|
+
return this.errorResponseHash.ArticleNotFound.createAsError()
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return RestfulApiResponse.create({
|
|
182
|
+
statusCode: 200,
|
|
183
|
+
content: this.formatResponseContent({
|
|
184
|
+
article,
|
|
185
|
+
}),
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ... findArticle(), formatResponseContent() ...
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
- **`render({ body, query, context, request })`** is the entry point. `body` = parsed request body
|
|
194
|
+
(POST/PUT/PATCH), `query` = query string params, `context` = the per-request context (`now`,
|
|
195
|
+
`share`, `env`, user — §3), `request` = the wrapped express request (`expressRequest`, and a
|
|
196
|
+
`pathParameterHashProxy` that returns `null` for missing path params).
|
|
197
|
+
- **`static get routePath()`** — the route (prefixed by the engine, §1).
|
|
198
|
+
- **`get passesFilter()`** — `true` skips the engine's auth filter (public); default `false` runs it.
|
|
199
|
+
- **Dependency injection** — add `constructor` + `static create()` + `static createXxx()` only when
|
|
200
|
+
a tool must be substitutable in tests (same factory pattern as the GraphQL side).
|
|
201
|
+
|
|
202
|
+
Method-verb subclasses, `render()` input shape, DI, and file uploads (multer via
|
|
203
|
+
`fileFieldsConfigHash`) are in [renderers.md](./references/renderers.md).
|
|
204
|
+
|
|
205
|
+
## 3. Engine, context, and share (the app-wide layer)
|
|
206
|
+
|
|
207
|
+
These three set up the whole REST surface, mirroring the GraphQL engine/context/share:
|
|
208
|
+
|
|
209
|
+
- **Engine** (`AppRestfulApiServerEngine extends BaseRestfulApiServerEngine`) — declares `config`
|
|
210
|
+
(`pathPrefix` / `renderersPath` / `staticPath`), wires `static get Share()` / `static get
|
|
211
|
+
Context()`, the **`standardErrorEnvelopHash`** (cross-cutting errors: `Unknown`,
|
|
212
|
+
`Unauthenticated`, `Unauthorized`, `Database`, …), the express **middleware**
|
|
213
|
+
(`collectMiddleware()`), the **auth filter** (`generateFilterHandler()`), and the **visa issuers**
|
|
214
|
+
(`visaIssuers`: `hasAuthenticated` / `hasAuthorized` / `hasPathPermission`).
|
|
215
|
+
- **Context** (`AppRestfulApiContext extends BaseRestfulApiContext`) — built per request. Override
|
|
216
|
+
`static async findUser()` to resolve the authenticated user from the access-token header. Exposes
|
|
217
|
+
`now`, `userId`, `userEntity`, `share`, `env`, and the visa predicates
|
|
218
|
+
(`hasAuthenticated()` / `hasAuthorized()` / `hasPathPermission()`).
|
|
219
|
+
- **Share** (`AppRestfulApiShare extends BaseRestfulApiShare`) — the per-process object (holds `env`;
|
|
220
|
+
put shared clients/providers here). Often a `// noop` subclass.
|
|
221
|
+
|
|
222
|
+
Detail in [engine-and-context.md](./references/engine-and-context.md).
|
|
223
|
+
|
|
224
|
+
## 4. Response, error hash, and flusher
|
|
225
|
+
|
|
226
|
+
- **`RestfulApiResponse`** is the return type. Success:
|
|
227
|
+
`RestfulApiResponse.create({ statusCode, headers?, content })`. Error: from the built error hash,
|
|
228
|
+
`this.errorResponseHash.Xxx.createAsError()`.
|
|
229
|
+
- **Error hash** — like the GraphQL error code hash, a renderer declares its errors up front in
|
|
230
|
+
`static get errorStructureHash()`. **Unlike** GraphQL (code only), each REST entry also carries a
|
|
231
|
+
`statusCode` and `errorMessage`, because an HTTP response needs a status. The framework turns the
|
|
232
|
+
hash into constructable `RestfulApiResponse` subclasses on `this.errorResponseHash`. Cross-cutting
|
|
233
|
+
errors live on the engine's `standardErrorEnvelopHash`.
|
|
234
|
+
- **Extending the response** — when you need a non-default body shape or behavior, subclass
|
|
235
|
+
`RestfulApiResponse` in the app and return that.
|
|
236
|
+
- **Flusher** — a `BaseRestfulApiResponseFlusher` writes the response (status → headers → body).
|
|
237
|
+
Default is JSON (`{ content, error }`); the framework also ships Html and Csv; a renderer selects
|
|
238
|
+
one via `static get FlusherCtor()`, and the app can define custom flushers (e.g. a redirect).
|
|
239
|
+
|
|
240
|
+
Detail in [response-and-flusher.md](./references/response-and-flusher.md).
|
|
241
|
+
|
|
242
|
+
## 5. Input validation (the target shape)
|
|
243
|
+
|
|
244
|
+
The current repo validates REST input **ad hoc** inside `render()` (an inline `isValidRequestBody()`).
|
|
245
|
+
The **target** is to validate with the **same validator structure as GraphQL**: a
|
|
246
|
+
`BaseInputValidator` subclass whose `generateValidationEntries()` returns `[predicate, ErrorCtor]`
|
|
247
|
+
pairs and whose `validateInput()` returns the first failing error (or `null`).
|
|
248
|
+
|
|
249
|
+
The catch is the input shape. A GraphQL validator receives a single typed `input` object; REST input
|
|
250
|
+
arrives split across **`body` / `query` / path params**, all strings. So a REST renderer needs an
|
|
251
|
+
**adapter**: a small class that reads `{ body, query, request }` and produces the normalized `input`
|
|
252
|
+
object the validator expects. The renderer flow becomes **adapter → input → validator → (on failure)
|
|
253
|
+
map to the renderer's `errorResponseHash` entry**.
|
|
254
|
+
|
|
255
|
+
There is also a **type-mismatch** to bridge: a GraphQL-style validator yields a code-only error,
|
|
256
|
+
while REST needs a **status-bearing** `RestfulApiResponse`. The wiring must map each validation
|
|
257
|
+
failure to the matching `errorStructureHash` entry (status + message).
|
|
258
|
+
|
|
259
|
+
The adapter, the validator contract, and the error mapping are in
|
|
260
|
+
[validation.md](./references/validation.md).
|
|
261
|
+
|
|
262
|
+
## Detail files
|
|
263
|
+
|
|
264
|
+
- [renderers.md](./references/renderers.md) — the renderer file: method-verb subclasses, directory
|
|
265
|
+
& versioning, `routePath`, `render()` input (`body` / `query` / `context` / `request`),
|
|
266
|
+
`passesFilter`, the DI factory, and multipart file uploads (§1, §2)
|
|
267
|
+
- [engine-and-context.md](./references/engine-and-context.md) — the engine (`config`,
|
|
268
|
+
`renderersPath` / `pathPrefix`, `Share` / `Context`, `standardErrorEnvelopHash`, middleware,
|
|
269
|
+
filter handler, visa issuers) and the per-request context / per-process share (§3)
|
|
270
|
+
- [response-and-flusher.md](./references/response-and-flusher.md) — `RestfulApiResponse`
|
|
271
|
+
(success / `createAsError`), `errorStructureHash` → `errorResponseHash`, extending the response,
|
|
272
|
+
and flushers (JSON / Html / Csv / custom, `FlusherCtor`, `contentType`) (§4)
|
|
273
|
+
- [validation.md](./references/validation.md) — the target validator (`BaseInputValidator`,
|
|
274
|
+
`generateValidationEntries`, `validateInput`), the REST-input → `input` adapter, and mapping a
|
|
275
|
+
validation failure to a status-bearing response (§5)
|