@try-works/dsh-minimal-router 0.0.0-stage → 0.2.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.
@@ -0,0 +1,52 @@
1
+ // @dsh-local-router/plugin — request handlers for the Router Settings pages
2
+ // (Run 25). Kept out of lib/index.js so the semantics are unit-testable:
3
+ // the page sends the rev it loaded in If-Match and can only write on a match.
4
+ //
5
+ // Run 25 repair (review B3/B4): the request body is closed, like the store's
6
+ // document. Only the two fragments are accepted; the page also sends its rev as
7
+ // expectedRev (the If-Match header is authoritative, the duplicate is tolerated,
8
+ // not trusted), and anything else is a 400 naming the offending key instead of
9
+ // being silently dropped. The 409 payload is the shape the page reads:
10
+ // { ok:false, conflict:true, current, error:{ field, message } }.
11
+
12
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
13
+
14
+ const PATCH_KEYS = new Set(["context", "roles"])
15
+ const BODY_KEYS = new Set([...PATCH_KEYS, "expectedRev"])
16
+
17
+ const invalid = (field, message) => ({ status: 400, payload: { ok: false, error: { field, message } } })
18
+
19
+ export const createSettingsHandlers = (store) => ({
20
+ get: () => ({ status: 200, payload: store.get() }),
21
+ put: (body, ifMatch) => {
22
+ const expectedRev = Number.parseInt(String(ifMatch ?? ""), 10)
23
+ if (!Number.isInteger(expectedRev)) {
24
+ return invalid("if-match", "If-Match must carry the rev the page loaded")
25
+ }
26
+ if (!isRecord(body)) {
27
+ return invalid("body", "body must be an object")
28
+ }
29
+ const unknown = Object.keys(body).find((key) => !BODY_KEYS.has(key))
30
+ if (unknown !== undefined) {
31
+ return invalid(unknown, "unknown field")
32
+ }
33
+ const result = store.write({ context: body.context, roles: body.roles }, expectedRev)
34
+ if (result.ok === true) return { status: 200, payload: result.settings }
35
+ if (result.storage === true) {
36
+ // Run 25 T5: a failed persist is a server-side failure, never a Saved 200.
37
+ return { status: 500, payload: { ok: false, error: { field: "storage", message: result.message } } }
38
+ }
39
+ if (result.conflict === true) {
40
+ return {
41
+ status: 409,
42
+ payload: {
43
+ ok: false,
44
+ conflict: true,
45
+ current: result.current,
46
+ error: { field: "rev", message: "settings changed elsewhere" }
47
+ }
48
+ }
49
+ }
50
+ return invalid(result.field, result.message)
51
+ }
52
+ })