@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,40 @@
|
|
|
1
|
+
# Normalization and scaling reads
|
|
2
|
+
|
|
3
|
+
Third normal form as the default table shape, and how to add read capacity when data grows without
|
|
4
|
+
denormalizing the canonical tables. Referenced from [SKILL.md](../SKILL.md); this is the direct
|
|
5
|
+
application of its
|
|
6
|
+
[grand principle](../SKILL.md#grand-principle-the-database-holds-canonical-normalized-truth) to
|
|
7
|
+
redundancy.
|
|
8
|
+
|
|
9
|
+
## Normalize to third normal form; denormalize only as a separate, additive structure
|
|
10
|
+
|
|
11
|
+
Design every table to **third normal form (3NF)** by default: each non-key column depends on the
|
|
12
|
+
whole key and nothing but the key, and no fact is stored in two places. When read performance
|
|
13
|
+
degrades as data grows, **do not** denormalize the canonical tables — add a **separate** structure
|
|
14
|
+
beside them:
|
|
15
|
+
|
|
16
|
+
- a **summary / read-model table**, named with a **`summary_` prefix** (`summary_order_listings`),
|
|
17
|
+
rebuilt from the canonical tables; or
|
|
18
|
+
- an external **search database** (Elasticsearch, etc.) for full-text or faceted search.
|
|
19
|
+
|
|
20
|
+
- **Why**: normalization keeps the responsibility boundaries sharp and the structure flexible (the
|
|
21
|
+
[grand principle](../SKILL.md#grand-principle-the-database-holds-canonical-normalized-truth)). A
|
|
22
|
+
denormalized column copied into the core (e.g. a customer's name cached onto every order row) has
|
|
23
|
+
two owners: it drifts the instant the source changes, and it freezes the schema because now two
|
|
24
|
+
places must be updated together. Putting the derived data in a **separate, prefixed, rebuildable**
|
|
25
|
+
table (or a search DB) keeps the canonical tables as the sole source of truth — the summary can be
|
|
26
|
+
dropped and regenerated at any time without data loss.
|
|
27
|
+
- The `summary_` prefix / a distinct search DB is a **signal**: "this is derived, not
|
|
28
|
+
authoritative." Never let application writes treat a summary row as the source of truth.
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
-- Good: canonical stays normalized; the fast read path is a separate, rebuildable table
|
|
32
|
+
orders (id, CustomerId, OrderStatusId, ordered_at, ...) -- canonical truth
|
|
33
|
+
customers (id, name, ...) -- canonical truth
|
|
34
|
+
summary_order_listings (id, OrderId, customer_name, status_label, ...) -- derived, rebuildable
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
-- Avoid: customer_name copied onto the canonical table "to make the listing query fast"
|
|
39
|
+
orders (id, CustomerId, customer_name, ...) -- drifts when the customer is renamed; two owners
|
|
40
|
+
```
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Update history (the archive pattern)
|
|
2
|
+
|
|
3
|
+
How to retain a table's change history without bloating the live table. Referenced from
|
|
4
|
+
[SKILL.md](../SKILL.md). The mixin that implements this is written per `hor-sequelize-model`.
|
|
5
|
+
|
|
6
|
+
## Keep a table's update log with the archive pattern
|
|
7
|
+
|
|
8
|
+
When you need to retain the **update history** of a table, use the **archive pattern** as the base
|
|
9
|
+
pattern: keep the live table holding only the **current** row, and on every save **append** a copy
|
|
10
|
+
of the row's business attributes — as a new generation — to a **parallel archive table**. Do not
|
|
11
|
+
keep history by piling every revision into the live table (a `is_current` flag, per-row version
|
|
12
|
+
numbers).
|
|
13
|
+
|
|
14
|
+
- **Why**: the live table stays small and single-purpose — "the current state" — so ordinary
|
|
15
|
+
queries need no "and it's the current one" filter and its indexes/constraints stay simple. The
|
|
16
|
+
full history lives in an **append-only** companion that never complicates the main table. Folding
|
|
17
|
+
current and historical rows into one table bloats it, slows every query, and muddies uniqueness
|
|
18
|
+
constraints. History is a separate, additive structure (the
|
|
19
|
+
[grand principle](../SKILL.md#grand-principle-the-database-holds-canonical-normalized-truth)),
|
|
20
|
+
exactly like the summary tables in [normalization.md](./normalization.md).
|
|
21
|
+
- **Mechanics**: renchan implements the archive pattern with `BackupMixinModel` + a `*_bk` table
|
|
22
|
+
(e.g. `customer_orders` → `customer_orders_bk`): on `afterSave` it appends the business attributes
|
|
23
|
+
(excluding `id` / `created_at` / `updated_at` / `deleted_at`) plus a `saved_at` generation marker.
|
|
24
|
+
Pass the mixin from the live model; see the mixin catalog in `hor-sequelize-model`.
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
-- Good: live table = current state; archive table = append-only generations
|
|
28
|
+
customer_orders (id, CustomerId, OrderStatusId, ...) -- current row only
|
|
29
|
+
customer_orders_bk (id, CustomerOrderId, ...business attrs, saved_at) -- one appended row per save
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
-- Avoid: history crammed into the live table
|
|
34
|
+
customer_orders (id, ..., version_no, is_current) -- every query filters is_current; table bloats
|
|
35
|
+
```
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-execution-placement-pattern
|
|
3
|
+
description: >
|
|
4
|
+
Decide where a piece of processing (especially a write / state change) should be implemented in
|
|
5
|
+
a web system: as a synchronous GraphQL / REST API operation, or as a renchan-job-bullmq
|
|
6
|
+
background worker triggered from an API handler, from a post-worker after the response, or on a
|
|
7
|
+
schedule. Use this skill whenever the user is turning a requirement into an implementation and
|
|
8
|
+
needs to choose the execution location, including where an external-integration write belongs.
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# Execution Placement Pattern (deciding where processing lives)
|
|
12
|
+
|
|
13
|
+
A skill for deciding, the moment you receive a requirement, **where that processing should be
|
|
14
|
+
implemented**. Before diving into the implementation details (how to write the job, how to write the
|
|
15
|
+
resolver, etc.), first lock down the "placement". Once the placement is decided, you can hand it off
|
|
16
|
+
to the individual implementation skills (`hor-renchan-job-bullmq`, etc.).
|
|
17
|
+
|
|
18
|
+
## Grand principle: write processing lives in only two places — "API" or "Worker"
|
|
19
|
+
|
|
20
|
+
In a web system, **processing that changes state (writes)** only ever happens in one of two places.
|
|
21
|
+
Every requirement must resolve into this binary choice. The deciding axis is **how heavy / how
|
|
22
|
+
long-running the processing is**.
|
|
23
|
+
|
|
24
|
+
| Placement | Execution model | What it holds |
|
|
25
|
+
| --- | --- | --- |
|
|
26
|
+
| **API** | Responds **synchronously** to the request | Things that are **light and finish quickly** |
|
|
27
|
+
| **Worker** | Runs **asynchronously** in the background | Things that are **heavy and take time** |
|
|
28
|
+
|
|
29
|
+
- **Why only two places**: a write can only originate from "an external request (API)" or "processing
|
|
30
|
+
the system drives on its own (Worker)". Creating a third place scatters responsibility, monitoring,
|
|
31
|
+
and retry paths so they can no longer be traced.
|
|
32
|
+
- **Why split by weight**: a request must return quickly. If you run heavy processing inside the API,
|
|
33
|
+
the response never comes back and it times out; if it is cut off midway, it cannot recover. Push it
|
|
34
|
+
to a Worker and the API can respond immediately, while retries, progress notifications, and scaling
|
|
35
|
+
work independently.
|
|
36
|
+
- **When the boundary is unclear, lean toward Worker.** Why: if "probably fast" processing turns out
|
|
37
|
+
slow at production data volumes, an API implementation becomes a timeout incident. A Worker does not
|
|
38
|
+
break when it gets slow. As a rule of thumb, anything involving external I/O, AI calls, large record
|
|
39
|
+
counts, or file generation counts as the heavy side.
|
|
40
|
+
|
|
41
|
+
> Read-only (non-state-changing) processing is not the main subject of this skill. As a rule it just
|
|
42
|
+
> returns synchronously via the API (GraphQL query / REST GET) and is not turned into a Worker.
|
|
43
|
+
|
|
44
|
+
## Decision flow
|
|
45
|
+
|
|
46
|
+
1. **Is it a write?** If read-only, return it via an API query / GET and you're done.
|
|
47
|
+
2. **Is it light & short-lived?** → **API** ([1](#1-put-it-in-the-api-light-short-lived)).
|
|
48
|
+
3. **Is it heavy / time-consuming / uncertain due to external dependencies?** → **Worker** ([2](#2-put-it-in-a-worker-heavy-time-consuming)).
|
|
49
|
+
4. **What triggers the Worker?**
|
|
50
|
+
- User actions, external integrations, etc. — **request-based** → enqueue from inside the API handler ([2.1](#21-request-based)).
|
|
51
|
+
- A side effect unrelated to the main processing, run **after the response** → dispatch from a **post-worker** ([2.2](#22-post-worker)).
|
|
52
|
+
- Automatic, by time / interval → **schedule-based** ([2.3](#23-schedule-based)).
|
|
53
|
+
|
|
54
|
+
| Nature of the processing | Placement | Concretely |
|
|
55
|
+
| --- | --- | --- |
|
|
56
|
+
| Light, short-lived, needs a synchronous response | **API** | GraphQL resolver / REST renderer |
|
|
57
|
+
| Heavy, time-consuming, **request-based** | **Worker (API-triggered)** | renchan-job-bullmq (enqueue from resolver/renderer) |
|
|
58
|
+
| A **side effect** unrelated to main processing, run **after the response** | **Worker (post-worker-triggered)** | post-worker only dispatches (e.g. sending an email after signup) |
|
|
59
|
+
| Heavy, **automatic by interval/time** | **Worker (scheduled)** | renchan-job-bullmq (cron / interval scheduler) |
|
|
60
|
+
|
|
61
|
+
## 1. Put it in the API (light, short-lived)
|
|
62
|
+
|
|
63
|
+
The API has two families: **GraphQL** and **REST API**. Choose based on the caller in the requirement.
|
|
64
|
+
|
|
65
|
+
- **GraphQL** — resolvers under `server/graphql/resolvers/<role>/actual/{mutations,queries}/`.
|
|
66
|
+
Ordinary reads/writes from your own frontend default to this.
|
|
67
|
+
- **REST API (renderer)** — renderers under `server/restfulapi/renderers/v1/{post,get}/*Renderer.js`.
|
|
68
|
+
Use for file uploads, endpoints hit by external systems, and non-GraphQL clients.
|
|
69
|
+
|
|
70
|
+
Rule of thumb for what goes here: simple CRUD against the DB, input validation, and short
|
|
71
|
+
aggregations/updates that complete within a single request.
|
|
72
|
+
|
|
73
|
+
- **Why the API**: for short processing where the user waits for the result immediately, responding
|
|
74
|
+
synchronously is the shortest path. Turning it into a job instead introduces the complexity of
|
|
75
|
+
enqueue → progress notification → polling/subscription, which isn't worth it.
|
|
76
|
+
|
|
77
|
+
```js
|
|
78
|
+
// Good: a short DB update is handled synchronously inside the resolver and returned immediately
|
|
79
|
+
const updated = await context.share.transaction(async tx => this.updateProfile({ input, tx }))
|
|
80
|
+
return { profile: updated }
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
```js
|
|
84
|
+
// Avoid: running even heavy processing synchronously inside the resolver → the response never returns and times out
|
|
85
|
+
const content = await generateContentWithAi({ accessToken }) // takes tens of seconds
|
|
86
|
+
return { content }
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## 2. Put it in a Worker (heavy, time-consuming)
|
|
90
|
+
|
|
91
|
+
Workers are implemented with **`@openreachtech/renchan-job-bullmq`**. Place the Manifest / Worker /
|
|
92
|
+
Dispatcher under `app/jobs/<kebab-name>/`. Follow the
|
|
93
|
+
`hor-renchan-job-bullmq` skill for how to write them.
|
|
94
|
+
|
|
95
|
+
They split into three kinds by trigger ([2.1](#21-request-based) request-based /
|
|
96
|
+
[2.2](#22-post-worker) post-worker / [2.3](#23-schedule-based) schedule).
|
|
97
|
+
**In all three, the shape is the same: "the real work is in the Worker, the trigger is elsewhere"** —
|
|
98
|
+
don't put logic beyond dispatch in the trigger.
|
|
99
|
+
|
|
100
|
+
### 2.1 Request-based
|
|
101
|
+
|
|
102
|
+
The pattern of **enqueuing from inside the API handler**. Triggered by a user action or external
|
|
103
|
+
integration, the API (resolver / renderer) **only enqueues and responds immediately**, while the real
|
|
104
|
+
work is handled by a Worker in the Daemon. Progress is returned via a subscription or similar.
|
|
105
|
+
|
|
106
|
+
- Examples (this repo): heavy AI content generation = `app/jobs/content-generation-internal` /
|
|
107
|
+
`app/jobs/content-generation-public-lp`; report email sending = `app/jobs/send-report-email`.
|
|
108
|
+
They enqueue with `dispatchJob` from a resolver/renderer.
|
|
109
|
+
|
|
110
|
+
- **Why enqueue**: running heavy processing inside the API means it can't return. Enqueue instead and
|
|
111
|
+
the API can respond immediately, while the Worker side handles retry / progress notification /
|
|
112
|
+
concurrency control. **The API side sticks to "just enqueuing"** (no real work).
|
|
113
|
+
|
|
114
|
+
```js
|
|
115
|
+
// Good: heavy processing is enqueued and the response returns immediately (the real work is in the Worker)
|
|
116
|
+
await context.share.jobDispatcherProvider.dispatchJob({
|
|
117
|
+
DispatcherCtor: ContentGenerationPublicLpJobDispatcher,
|
|
118
|
+
body: {
|
|
119
|
+
accessToken,
|
|
120
|
+
},
|
|
121
|
+
})
|
|
122
|
+
return { accepted: true }
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### 2.2 post-worker
|
|
126
|
+
|
|
127
|
+
renchan's **post-worker** (`BaseGraphqlPostWorker`) is the mechanism for **running side effects
|
|
128
|
+
unrelated to the API's main processing, after the response**. It fires as an `onResolved` hook per
|
|
129
|
+
GraphQL operation, running after the main resolver has returned.
|
|
130
|
+
|
|
131
|
+
**A post-worker holds only the dispatch to the Worker. Don't put complex logic here** (the real work
|
|
132
|
+
always belongs on the Worker side).
|
|
133
|
+
|
|
134
|
+
- **Why dispatch only**: a post-worker is a thin hook that runs after the response. If you write heavy
|
|
135
|
+
processing or complex logic here, logic accumulates in a place where **neither retry, progress
|
|
136
|
+
notification, nor monitoring apply**, and failures get swallowed. Keep it to dispatch and the real
|
|
137
|
+
work rides on the Worker's machinery (retries, observability), while the post-worker stays
|
|
138
|
+
predictably thin — "just enqueuing" (the same principle as "the trigger only enqueues" in
|
|
139
|
+
[2.1](#21-request-based)).
|
|
140
|
+
- **Choosing between 2.1 and this**: if **the user is requesting** that processing (waits for the
|
|
141
|
+
result, or it's part of the response), enqueue inside the handler ([2.1](#21-request-based)). If you
|
|
142
|
+
only want to run a **side effect unrelated to the main processing** afterward without making the
|
|
143
|
+
response wait, use a post-worker.
|
|
144
|
+
- Example: dispatch **sending a welcome email after signup** from a post-worker (the signup response
|
|
145
|
+
isn't kept waiting; the email send is streamed to a Worker afterward).
|
|
146
|
+
- Current state of this repo: the server engine has `postWorkersPath: null` (not wired). To use it,
|
|
147
|
+
set the engine's `postWorkersPath` and place a post-worker that extends `BaseGraphqlPostWorker`.
|
|
148
|
+
|
|
149
|
+
```js
|
|
150
|
+
// Good: a post-worker only dispatches (the real work of the side effect is on the Worker side)
|
|
151
|
+
/** @override */
|
|
152
|
+
async onResolved ({ variables, context, response: { output, error } }) {
|
|
153
|
+
if (error) {
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
await context.share.jobDispatcherProvider.dispatchJob({
|
|
158
|
+
DispatcherCtor: SendWelcomeEmailJobDispatcher,
|
|
159
|
+
body: {
|
|
160
|
+
customerId: output.customer.id,
|
|
161
|
+
},
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
```js
|
|
167
|
+
// Avoid: writing email-body assembly or sending logic directly in the post-worker
|
|
168
|
+
// → real work accumulates in a post-response place where failures get swallowed, and neither retry nor monitoring apply. Put the real work in the Worker.
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### 2.3 Schedule-based
|
|
172
|
+
|
|
173
|
+
Processing that starts **automatically by time / interval** rather than from a user. Register a cron /
|
|
174
|
+
interval scheduler (`*CronJobScheduler.js` / `*IntervalJobScheduler.js`,
|
|
175
|
+
`hor-renchan-job-bullmq` skill).
|
|
176
|
+
|
|
177
|
+
- Example (this repo): cleaning up expired sessions = `app/jobs/purge-expired-content-sessions`
|
|
178
|
+
(`PurgeExpiredContentSessionsCronJobScheduler.js`).
|
|
179
|
+
|
|
180
|
+
- **Why a scheduler**: periodic batches, cleanups, reminders, re-aggregations, and the like need to
|
|
181
|
+
run even without an external request. They don't ride the API path, so start them from a scheduler.
|
|
182
|
+
|
|
183
|
+
```js
|
|
184
|
+
// Avoid: substituting a periodic cleanup with "an admin presses a button and the resolver runs a long loop"
|
|
185
|
+
// → forgotten presses, double execution, and timeouts occur. Put periodic processing in a scheduler.
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
## 3. Placement of external integrations
|
|
189
|
+
|
|
190
|
+
Integrations with external systems must also ride on one of the two places above (API / Worker).
|
|
191
|
+
Organize them by direction.
|
|
192
|
+
|
|
193
|
+
- **inbound (receiving calls from outside)**: **often a REST API (renderer)**, but **not necessarily**
|
|
194
|
+
(it can be received via GraphQL). Choose the receiving method based on the other system's
|
|
195
|
+
constraints. If the processing after receiving is heavy, the renderer sticks to enqueuing and hands
|
|
196
|
+
the real work to a Worker ([2.1](#21-request-based)).
|
|
197
|
+
- Example: `server/restfulapi/renderers/v1/post/IntegrationReportPostRenderer.js`.
|
|
198
|
+
- **outbound (calling an external API)**: call it via the rocket-client Launcher
|
|
199
|
+
(`hor-external-api-client` skill).
|
|
200
|
+
External calls are slow and uncertain, so call them from a Worker if they would block the user's
|
|
201
|
+
response.
|
|
202
|
+
|
|
203
|
+
- **Why "not necessarily REST"**: the integration method (REST / GraphQL / Webhook, etc.) is usually
|
|
204
|
+
decided by the other system and won't always match our default (REST renderer). **The receiving
|
|
205
|
+
method follows the other party's spec, and the placement (API or Worker) follows this skill's weight
|
|
206
|
+
criterion** — decide the two axes separately.
|
|
207
|
+
|
|
208
|
+
## Finishing checklist
|
|
209
|
+
|
|
210
|
+
- [ ] Is this processing a **write**? (If a read, return it via query/GET and you're done.)
|
|
211
|
+
- [ ] Did you resolve it into the binary of **light → API / heavy → Worker**, leaning toward Worker when unsure?
|
|
212
|
+
- [ ] If placing it in the API, did you choose **GraphQL resolver** or **REST renderer** based on the caller?
|
|
213
|
+
- [ ] If placing it in a Worker, did you choose one of **request-based (enqueue)** / **post-worker** / **schedule-based** by trigger?
|
|
214
|
+
- [ ] For the request-based case, does **the API side only enqueue** (no real work written in the resolver/renderer)?
|
|
215
|
+
- [ ] If running a side effect unrelated to main processing after the response, did you write **only a dispatch in the post-worker** and keep the real work in the Worker?
|
|
216
|
+
- [ ] For external integrations, did you decide the **receiving method (other party's constraints)** and the **placement (weight criterion)** separately?
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-external-api-client
|
|
3
|
+
description: >
|
|
4
|
+
Implement a client for an external HTTP/REST API using
|
|
5
|
+
`@openreachtech/mentsu-rocket-client` (the Launcher / Payload / Capsule three-class
|
|
6
|
+
structure). Use this skill whenever the user asks to add or change an external API
|
|
7
|
+
integration — a new service client, a new API operation, request/response key
|
|
8
|
+
conversion, authorization headers, or wrapping a vendor SDK — under
|
|
9
|
+
`app/<serviceName>Client/`. For the raw source guide see the doc linked at the bottom.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# External API Client
|
|
13
|
+
|
|
14
|
+
How to implement a client for an external HTTP/REST API with `@openreachtech/mentsu-rocket-client`
|
|
15
|
+
(rocket-client from here on). One external request is split across three classes —
|
|
16
|
+
**Launcher / Payload / Capsule**. The conventions are divided into the detail files listed at the
|
|
17
|
+
bottom; read the one that matches what you are doing.
|
|
18
|
+
|
|
19
|
+
## First principle: confine every difference from the external API to Payload / Capsule (anti-corruption layer)
|
|
20
|
+
|
|
21
|
+
Every convention in this skill follows from one goal: **an external API's interface differences must
|
|
22
|
+
stay out of application code.** Key names, value formats, paths, authentication and response shapes
|
|
23
|
+
of an external API can all change, and they disagree with our own naming conventions anyway. Confine
|
|
24
|
+
those differences to **a single layer (the anti-corruption layer)** so the caller (a resolver or a
|
|
25
|
+
job) never has to know about them.
|
|
26
|
+
|
|
27
|
+
- **Differences on the way in** (key names, value formats, path, query, authentication) belong to
|
|
28
|
+
**`Payload`**.
|
|
29
|
+
- **Differences on the way out** (response key names, nesting, missing fields) belong to
|
|
30
|
+
**`Capsule`'s `extractXxx()`**.
|
|
31
|
+
- The caller only builds a `Payload` and pulls values out of a `Capsule`. **If the external API's raw
|
|
32
|
+
shape reaches the caller, this layer has failed.**
|
|
33
|
+
- **Why**: without this layer — or with a thin one — every change to the external API forces edits in
|
|
34
|
+
resolvers and jobs, and the reach of a change becomes impossible to see. Collecting the differences
|
|
35
|
+
in one place is what keeps a spec change contained to `Payload` / `Capsule`. When an individual
|
|
36
|
+
rule leaves you unsure, decide it by extending this principle: which class owns this difference?
|
|
37
|
+
|
|
38
|
+
## Cross-cutting rules (they apply to every layer)
|
|
39
|
+
|
|
40
|
+
### HTTP goes through the native `fetch` only — no axios, no HTTP client of your own
|
|
41
|
+
|
|
42
|
+
In the direct-HTTP pattern, communication is handled by the **Node.js native `fetch`** built into
|
|
43
|
+
`BaseLauncher`. **Do not add another HTTP client module such as axios**, and do not implement an HTTP
|
|
44
|
+
client or Fetcher class of your own. Wrap an SDK only when the vendor publishes an official one
|
|
45
|
+
([sdk-wrapper.md](./references/sdk-wrapper.md) — an interim implementation).
|
|
46
|
+
|
|
47
|
+
- **Why**: because the transport is centralized in `BaseLauncher`, retries, error conversion and
|
|
48
|
+
swapping in a stub for tests all take effect in one place. If each client brings its own axios, that
|
|
49
|
+
benefit is gone and the transport ends up implemented differently per operation.
|
|
50
|
+
|
|
51
|
+
### Decide failure with `capsule.hasError()`, not `try-catch`
|
|
52
|
+
|
|
53
|
+
`launchRequest()` catches `fetch` exceptions and body-parse failures internally and returns the
|
|
54
|
+
`Capsule` for the corresponding error kind. The caller **writes no `try-catch`** and decides failure
|
|
55
|
+
from the returned `capsule.hasError()`.
|
|
56
|
+
|
|
57
|
+
- **Why**: funnelling missing authentication, invalid input, network failure, parse failure and a
|
|
58
|
+
status >= 400 into one path — the "error `Capsule`" — is this module's design. A caller that adds
|
|
59
|
+
`try-catch` on top handles errors through two channels, the caught exception and the `Capsule`, and
|
|
60
|
+
a case will fall through the gap.
|
|
61
|
+
|
|
62
|
+
### Return `null` (or an empty array) for a missing value, never `undefined`
|
|
63
|
+
|
|
64
|
+
When an `extractXxx()` or a getter cannot produce a value, return **`null`** — or an **empty array**
|
|
65
|
+
for something that returns an array, or whatever the intended default is — not `undefined`.
|
|
66
|
+
|
|
67
|
+
- **Why**: `undefined` cannot be told apart from "undefined behaviour / not implemented yet". `null`
|
|
68
|
+
(or an empty array) states the intent: the value was looked for and was not there. Details in
|
|
69
|
+
[capsule.md](./references/capsule.md).
|
|
70
|
+
|
|
71
|
+
### Write comments in code in English
|
|
72
|
+
|
|
73
|
+
Comments in the real code you generate (`.js`) — `//`, `/* */`, JSDoc — are written in **English**, to
|
|
74
|
+
match the rest of the codebase. The ```js``` blocks in this skill are real code too, so their JSDoc
|
|
75
|
+
and comments are shown in English as well.
|
|
76
|
+
|
|
77
|
+
### Naming, and one class per file
|
|
78
|
+
|
|
79
|
+
**One class per file**, with a single `export default`. Name a derived launcher
|
|
80
|
+
`<Operation>Launcher`, and the payload and capsule `<Operation>Payload` / `<Operation>Capsule`, so the
|
|
81
|
+
operation is readable from the name. Pick the verb of a retrieval method by where the value comes
|
|
82
|
+
from (`fetch~` = external API, `find~` = the database, `extract~` = pulled out of a `Capsule`). The
|
|
83
|
+
remaining general coding conventions are in [conventions.md](./references/conventions.md).
|
|
84
|
+
|
|
85
|
+
## Detail files
|
|
86
|
+
|
|
87
|
+
- [architecture.md](./references/architecture.md) — the whole picture (the three classes, the data flow, directory layout, the classes the module provides)
|
|
88
|
+
- [launcher.md](./references/launcher.md) — Launcher (base and derived / direct HTTP, the members of `BaseLauncher`)
|
|
89
|
+
- [payload.md](./references/payload.md) — Payload (input definition, `method`/`pathname`, schema, key conversion)
|
|
90
|
+
- [capsule.md](./references/capsule.md) — Capsule (the response wrapper, `extractXxx()`, null guards)
|
|
91
|
+
- [authorization.md](./references/authorization.md) — authentication (`AuthorizationBuilderCtor` / `authorizationApiKey`)
|
|
92
|
+
- [sdk-wrapper.md](./references/sdk-wrapper.md) — the SDK-wrapping pattern (an interim implementation that overrides `launchRequest()`)
|
|
93
|
+
- [usage.md](./references/usage.md) — the implementation steps, and use from the caller (resolver / job), DI and hooks
|
|
94
|
+
- [testing.md](./references/testing.md) — unit tests for Payload / Capsule / Launcher
|
|
95
|
+
- [conventions.md](./references/conventions.md) — the naming and coding convention checklist
|
|
96
|
+
|
|
97
|
+
> This skill was made from the repository's external API client implementation guide. For reference
|
|
98
|
+
> material — rocket-client's own export list, its type definitions, examples of existing clients — see
|
|
99
|
+
> the "reference files" section at the end of that guide.
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# Architecture (the whole picture: three classes, data flow, layout)
|
|
2
|
+
|
|
3
|
+
The whole picture of rocket-client: how one request is split across **Launcher / Payload / Capsule**,
|
|
4
|
+
the data flow between them, the directory layout, and the classes the module provides for you to swap
|
|
5
|
+
in. Referenced from [SKILL.md](../SKILL.md). For how to write each individual layer, see
|
|
6
|
+
[launcher.md](./launcher.md) / [payload.md](./payload.md) / [capsule.md](./capsule.md).
|
|
7
|
+
|
|
8
|
+
## Split the responsibilities across three classes
|
|
9
|
+
|
|
10
|
+
One external API request is always implemented in these three layers. All of them are `import`ed from
|
|
11
|
+
`@openreachtech/mentsu-rocket-client`.
|
|
12
|
+
|
|
13
|
+
| Layer | Base class | Role | Granularity |
|
|
14
|
+
| :-- | :-- | :-- | :-- |
|
|
15
|
+
| **Launcher** | `BaseLauncher` | Runs the request. Has `fetch` built in; `launchRequest()` covers sending through to producing the `Capsule` | Per service (base) plus per API operation (derived) |
|
|
16
|
+
| **Payload** | `BasePayload` | The input definition of one request. Holds method / path / query / body / authentication / key and value conversion | Per API operation |
|
|
17
|
+
| **Capsule** | `BaseCapsule` | The response wrapper. Provides `body` / `statusCode` / `hasError()`, and pulls values out with `extractXxx()` | Per API operation |
|
|
18
|
+
|
|
19
|
+
- **Per service** (say, some SaaS's REST API) there is **one** **base launcher**
|
|
20
|
+
(`Base<Service>Launcher`) holding `clientConfig` (base URL and so on).
|
|
21
|
+
- **Per API operation** (say, creating a document) there is **one set** of `Payload` / `Capsule` plus
|
|
22
|
+
the **derived launcher** (`<Operation>Launcher`) that ties them together.
|
|
23
|
+
- **Why this granularity**: connection settings (base URL, credentials) are shared across the service,
|
|
24
|
+
so they are collected in the base; input and output differences vary per operation, so they are
|
|
25
|
+
split per operation. Adding a new operation is then "add three derived files" and nothing about the
|
|
26
|
+
existing operations changes.
|
|
27
|
+
|
|
28
|
+
## Data flow: the caller only assembles and hands over
|
|
29
|
+
|
|
30
|
+
The caller builds a `Payload` and calls `launcher.launchRequest({ payload })` — that is all.
|
|
31
|
+
`launchRequest()` (provided by `BaseLauncher`) then runs this flow.
|
|
32
|
+
|
|
33
|
+
```
|
|
34
|
+
caller
|
|
35
|
+
│ pathParameterHash / query / body / optionHash
|
|
36
|
+
▼
|
|
37
|
+
Launcher.createPayload({ ... }) ← shortcut for Payload.create()
|
|
38
|
+
│ payload
|
|
39
|
+
▼
|
|
40
|
+
launcher.launchRequest({ payload, hooks }) ← provided by BaseLauncher
|
|
41
|
+
│
|
|
42
|
+
├─ payload.hasAuthorization() ─ false ─▶ Capsule (no-authorization error)
|
|
43
|
+
├─ payload.hasInvalidParameterHash() ─ true ─▶ Capsule (invalid-input error)
|
|
44
|
+
├─ hooks.beforeRequest(payload) ─ true ─▶ Capsule (aborted-by-hooks)
|
|
45
|
+
│
|
|
46
|
+
├─ payload.createFetchRequest({ baseUrl }) ← assembles path, query, body, headers
|
|
47
|
+
│ │ Request
|
|
48
|
+
│ ▼
|
|
49
|
+
│ BaseLauncher.fetch(request) ← native fetch (exceptions swallowed into null)
|
|
50
|
+
│ │ Response | null
|
|
51
|
+
│ ▼
|
|
52
|
+
│ ResponseBodyParser.parseBody() ← JSON parsing by default
|
|
53
|
+
│
|
|
54
|
+
├─ network failure ─▶ Capsule (network error)
|
|
55
|
+
├─ parse failure ─▶ Capsule (response-body-parse error)
|
|
56
|
+
└─ success ─▶ Capsule (holding rawResponse / body)
|
|
57
|
+
│
|
|
58
|
+
▼
|
|
59
|
+
hooks.afterRequest(capsule)
|
|
60
|
+
│
|
|
61
|
+
▼
|
|
62
|
+
capsule.hasError() / capsule.extractXxx() ← the caller pulls values out
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- Before sending, the `Payload` **validates itself** with `hasAuthorization()` and
|
|
66
|
+
`hasInvalidParameterHash()`, and on invalid input returns an error `Capsule` without calling `fetch`.
|
|
67
|
+
- `fetch` exceptions and body-parse failures are caught inside `BaseLauncher` and converted into the
|
|
68
|
+
`Capsule` for the corresponding error kind. **That is why the caller decides failure with
|
|
69
|
+
`capsule.hasError()` rather than `try-catch`**
|
|
70
|
+
([SKILL.md](../SKILL.md#decide-failure-with-capsulehaserror-not-try-catch)).
|
|
71
|
+
|
|
72
|
+
## Directory layout
|
|
73
|
+
|
|
74
|
+
| What | Where | Example |
|
|
75
|
+
| :-- | :-- | :-- |
|
|
76
|
+
| Implementation | `app/<serviceName>Client/` | `app/documentApiClient/` |
|
|
77
|
+
| Tests | `tests/__tests__/app/<serviceName>Client/` | `tests/__tests__/app/documentApiClient/` |
|
|
78
|
+
|
|
79
|
+
The files for one operation (the service base plus the operation's three):
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
app/documentApiClient/
|
|
83
|
+
BaseDocumentApiLauncher.js ← base launcher (clientConfig = BASE_URL, fetch, …)
|
|
84
|
+
CreateDocumentLauncher.js ← derived launcher (ties Payload / Capsule together)
|
|
85
|
+
CreateDocumentPayload.js ← input definition (method / pathname / schema / authentication)
|
|
86
|
+
CreateDocumentCapsule.js ← output extraction (extractXxx)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
- **Why separate files**: one class per file is a repository-wide convention
|
|
90
|
+
([conventions.md](./conventions.md)). The base launcher and the derived launcher are separate files
|
|
91
|
+
too, so that what is shared across the service (connection settings) and what is specific to the
|
|
92
|
+
operation (tying Payload/Capsule together) are kept in separate files.
|
|
93
|
+
|
|
94
|
+
## The classes the module provides (swapped in from `Payload` / `Capsule` / `Launcher`)
|
|
95
|
+
|
|
96
|
+
The behaviour of a `Payload` or a `Capsule` is swapped by returning one of the classes below from the
|
|
97
|
+
corresponding getter. All of them are exported from `@openreachtech/mentsu-rocket-client`.
|
|
98
|
+
|
|
99
|
+
| Kind | Class | Purpose | Where it is used |
|
|
100
|
+
| :-- | :-- | :-- | :-- |
|
|
101
|
+
| Core | `BaseLauncher` / `BasePayload` / `BaseCapsule` | The base classes of the three layers | The `extends` of each layer |
|
|
102
|
+
| Authentication | `BearerAuthorizationBuilder` / `BasicAuthorizationBuilder` (base `BaseAuthorizationBuilder`) | How the `Authorization` header is produced | The payload's `AuthorizationBuilderCtor` ([authorization.md](./authorization.md)) |
|
|
103
|
+
| Request key conversion | `SnakeCasedKeyRequestQuery` / `SnakeCasedKeyRequestBody` | Internal camelCase → outgoing snake_case | The payload's `RequestQueryCtor` / `RequestBodyCtor` ([payload.md](./payload.md)) |
|
|
104
|
+
| Response key conversion | `CamelCasedKeyResponseBody` (base `ResponseBody`) | Incoming snake_case → internal camelCase | The capsule's `ResponseBodyCtor` ([capsule.md](./capsule.md)) |
|
|
105
|
+
| Body formatting | `JsonRequestBodyStringifier` / `NdjsonRequestBodyStringifier` (base `BaseRequestBodyStringifier`) | How the request body is stringified | Payload |
|
|
106
|
+
| Response parsing | `JsonResponseBodyParser` / `BlobResponseBodyParser` (base `BaseResponseBodyParser`) | How the response body is parsed | The launcher's `ResponseBodyParser` (JSON by default) |
|
|
107
|
+
| Constants | `REST_METHOD` / `LAUNCH_ABORTED_REASON` | The HTTP method enum / the abort-reason enum | The payload's `method`, and so on |
|
|
108
|
+
|
|
109
|
+
- The scalars used in `querySchema` / `bodySchema` (`TextScalar` / `KeywordScalar` / `IntegerScalar` /
|
|
110
|
+
`DatetimeScalar`, …) are `import`ed from **`@openreachtech/mentsu-schema`**, not from rocket-client.
|
|
111
|
+
- **Installing**: `npm install @openreachtech/mentsu-rocket-client` — it is published to npmjs.com,
|
|
112
|
+
so no registry configuration or authentication is required.
|
|
113
|
+
|
|
114
|
+
## The two transport patterns
|
|
115
|
+
|
|
116
|
+
A launcher that calls an external API comes in two patterns, depending on the transport. The way
|
|
117
|
+
differences are absorbed (input in the `Payload`, output in the `Capsule`) is the same in both; **only
|
|
118
|
+
the transport step differs**.
|
|
119
|
+
|
|
120
|
+
| Pattern | Transport | When to use | Implementation |
|
|
121
|
+
| :-- | :-- | :-- | :-- |
|
|
122
|
+
| **Direct HTTP** (default) | The `fetch` built into `BaseLauncher` | No vendor SDK / hitting REST directly | Nothing extra to implement. Define `clientConfig` / `Payload` / `Capsule` ([launcher.md](./launcher.md)) |
|
|
123
|
+
| **SDK wrapping** | The SDK the vendor provides | An official SDK/client exists | The launcher holds the SDK and overrides `launchRequest()` ([sdk-wrapper.md](./sdk-wrapper.md) — an interim implementation) |
|
|
124
|
+
|
|
125
|
+
- A new REST integration is **direct HTTP** by default. SDK wrapping is an **interim
|
|
126
|
+
implementation** until rocket-client supports it properly, so use it only where an SDK is
|
|
127
|
+
provided.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Authorization
|
|
2
|
+
|
|
3
|
+
How the `Authorization` header is decided. Authentication is a difference on the way in, so it is
|
|
4
|
+
**confined to the `Payload`** ([payload.md](./payload.md)). Referenced from [SKILL.md](../SKILL.md).
|
|
5
|
+
|
|
6
|
+
The `Authorization` header is decided by the payload's `AuthorizationBuilderCtor` and
|
|
7
|
+
`authorizationApiKey` — or by the per-request `optionHash`.
|
|
8
|
+
|
|
9
|
+
## Pick the implementation by how the credential is held
|
|
10
|
+
|
|
11
|
+
| How the credential is held | Implementation |
|
|
12
|
+
| :-- | :-- |
|
|
13
|
+
| **A key shared across the service** (an API token in `env`, …) | Return `BearerAuthorizationBuilder` from `AuthorizationBuilderCtor` and `env.XXX` from `authorizationApiKey`. The header is generated for you |
|
|
14
|
+
| **A per-request token** (a user's access token, …) | Set `AuthorizationBuilderCtor`, leave `authorizationApiKey` as `null`, and pass `optionHash.headers.Authorization` when building the payload |
|
|
15
|
+
| **Basic authentication** | Return `BasicAuthorizationBuilder` from `AuthorizationBuilderCtor` and `'user:pass'` from `authorizationApiKey` (it is Base64-encoded for you) |
|
|
16
|
+
| **No authentication** | Override nothing (`AuthorizationBuilderCtor` defaults to `null`) |
|
|
17
|
+
|
|
18
|
+
## Declare a service-wide key with `AuthorizationBuilderCtor` plus `authorizationApiKey`
|
|
19
|
+
|
|
20
|
+
For an operation authenticated with an API token from `env`, implement two getters on the payload. The
|
|
21
|
+
builder assembles the header string (`Bearer xxx`), so do not write `headers` by hand.
|
|
22
|
+
|
|
23
|
+
- **Why**: turning the generation scheme (Bearer / Basic) and the key into declarations confines the
|
|
24
|
+
header-assembly difference to the payload. Written by hand, you risk a missing `Bearer ` prefix or
|
|
25
|
+
a forgotten Base64 encoding.
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
import {
|
|
29
|
+
env,
|
|
30
|
+
} from '../globals/_.js'
|
|
31
|
+
|
|
32
|
+
import {
|
|
33
|
+
BasePayload,
|
|
34
|
+
BearerAuthorizationBuilder,
|
|
35
|
+
REST_METHOD,
|
|
36
|
+
} from '@openreachtech/mentsu-rocket-client'
|
|
37
|
+
|
|
38
|
+
export default class FindDocumentsPayload extends BasePayload {
|
|
39
|
+
/** @override */
|
|
40
|
+
static get method () {
|
|
41
|
+
return REST_METHOD.GET
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @override */
|
|
45
|
+
static get pathname () {
|
|
46
|
+
return '/v1/projects/[projectId]/documents'
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* get: AuthorizationBuilder constructor.
|
|
51
|
+
*
|
|
52
|
+
* @override
|
|
53
|
+
* @returns {typeof BearerAuthorizationBuilder}
|
|
54
|
+
*/
|
|
55
|
+
static get AuthorizationBuilderCtor () {
|
|
56
|
+
return BearerAuthorizationBuilder
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* get: authorization API key.
|
|
61
|
+
*
|
|
62
|
+
* @override
|
|
63
|
+
* @returns {string}
|
|
64
|
+
*/
|
|
65
|
+
static get authorizationApiKey () {
|
|
66
|
+
return env.DOCUMENT_API_TOKEN
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Pass a per-request token through `optionHash.headers.Authorization`
|
|
72
|
+
|
|
73
|
+
For a token that changes per request, such as a user's access token, set `AuthorizationBuilderCtor` on
|
|
74
|
+
the payload but leave `authorizationApiKey` as `null`, and pass the header through `optionHash` when
|
|
75
|
+
building the payload.
|
|
76
|
+
|
|
77
|
+
- **Why keep `AuthorizationBuilderCtor`**: so that "make a missing token an error", below, takes effect.
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
const payload = FindDocumentsPayload.create({
|
|
81
|
+
pathParameterHash: {
|
|
82
|
+
projectId: 'fake-project-id-001',
|
|
83
|
+
},
|
|
84
|
+
query: {
|
|
85
|
+
keyword: 'fake-keyword-001',
|
|
86
|
+
limit: 20,
|
|
87
|
+
},
|
|
88
|
+
optionHash: {
|
|
89
|
+
headers: {
|
|
90
|
+
Authorization: `Bearer ${accessToken}`,
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
})
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## To make a missing token an error, always set `AuthorizationBuilderCtor`
|
|
97
|
+
|
|
98
|
+
When `AuthorizationBuilderCtor` is `null` (the default), `hasAuthorization()` is always `true` — no
|
|
99
|
+
validation. To have a missing token treated as a "no-authorization error `Capsule`", set
|
|
100
|
+
`AuthorizationBuilderCtor`.
|
|
101
|
+
|
|
102
|
+
- **Why**: with no builder set, rocket-client reads that as "no authentication needed" and skips the
|
|
103
|
+
check. Omitting the builder on an operation that does need authentication sends the `fetch` without a
|
|
104
|
+
token and leaves you relying on the external API's 401 — the benefit of validating before sending is
|
|
105
|
+
gone. Do not omit the builder where authentication is required.
|