@umituz/web-hono 1.0.0 → 1.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.
- package/README.md +34 -9
- package/package.json +16 -3
- package/src/crud.ts +32 -7
- package/src/index.ts +3 -3
- package/src/lib.ts +22 -0
- package/src/store-react.ts +75 -0
- package/src/store.ts +88 -0
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @umituz/web-hono
|
|
2
2
|
|
|
3
|
-
The Hono backend contract for single-Worker apps on Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle. It packages the cross-cutting API skeleton proven in production by the pilot app [foodora](https://foodora.umituz998.workers.dev): the `crudRoutes` factory, `pickPatch`/`uid`, `getDb`, the JSON-404 and SPA-fallback handlers, the zod body-validation contract, the same-origin API client, and the shared-Neon database lifecycle scripts.
|
|
3
|
+
The Hono backend contract for single-Worker apps on Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle. It packages the cross-cutting API skeleton proven in production by the pilot app [foodora](https://foodora.umituz998.workers.dev): the `crudRoutes` factory, `pickPatch`/`uid`, `getDb`, the JSON-404 and SPA-fallback handlers, the zod body-validation contract, the same-origin API client, the fetch-backed reactive store (+React hooks), and the shared-Neon database lifecycle scripts.
|
|
4
4
|
|
|
5
5
|
The package is **source-distributed** (published as raw TypeScript in `src/`). Wrangler, Vite, and tsc all compile it alongside your app; no prebuilt bundle ships.
|
|
6
6
|
|
|
@@ -8,7 +8,7 @@ The package is **source-distributed** (published as raw TypeScript in `src/`). W
|
|
|
8
8
|
|
|
9
9
|
- **Contract, not framework.** The package owns cross-cutting conventions only — the error envelope (`{ error, details? }`), the soft-delete list read, the setting-patch idiom, literal status codes. Your schema, `TABLE_PREFIX`, zod schemas, domain routers, and business rules stay in your app.
|
|
10
10
|
- **The factory has a hard scope.** `crudRoutes` covers list + setting-patch ONLY: "does this PATCH merely change a column value?" Entities with business rules (transitions, restock, overlap guards) stay hand-written in their area router — writing factory-covered code by hand and stuffing out-of-scope behavior into the factory are both contract violations.
|
|
11
|
-
- **Store-agnostic client.** `apiFetch`/`apiWrite` never import your store
|
|
11
|
+
- **Store-agnostic client, batteries-included store.** `apiFetch`/`apiWrite` never import your store — but `createStore` gives you the whole client cache machine (hydrate-once, targeted refresh, pub/sub, store-bound `apiWrite`) in one call. Your app supplies only what IS the app: the `Database` shape, the collection→endpoint map, the empty state.
|
|
12
12
|
- **Shared-Neon safety.** The lifecycle scripts drop only tables carrying your project's `TABLE_PREFIX` and refuse to run the moment they see a prefix-less table — one Neon project hosts a whole fleet of products.
|
|
13
13
|
|
|
14
14
|
## Installation
|
|
@@ -26,6 +26,8 @@ Peer dependencies (install alongside): `hono ^4`, `drizzle-orm ^0.45`, `@neondat
|
|
|
26
26
|
| `@umituz/web-hono` | `crudRoutes`, `CrudSpec`/`CrudTable`, `getDb`, `uid`, `pickPatch`, `apiNotFound`, `spaFallback`, `ApiEnv` | `api/index.ts`, area routers, `api/db.ts` |
|
|
27
27
|
| `@umituz/web-hono/validator` | `validateJson(schema, message?)` | every hand-written POST/PATCH route |
|
|
28
28
|
| `@umituz/web-hono/client` | `apiFetch<T>`, `apiWrite<T>` | `src/data/http.ts`, repositories |
|
|
29
|
+
| `@umituz/web-hono/store` | `createStore`, `StoreConfig`, `REFETCH_ALL` | `src/data/store.ts` (the app's whole cache layer) |
|
|
30
|
+
| `@umituz/web-hono/store/react` | `makeStoreHooks(store)` → `useQuery`, `useDbValue`, `QueryResult` | `src/core/useQuery.ts` (react is an optional peer) |
|
|
29
31
|
| `@umituz/web-hono/lifecycle` | `resetTables`, `snapshotToSeed`, `seedFromSnapshot`, `TableSpec`, `SeedSnapshot` | `scripts/reset.ts` / `snapshot.ts` / `seed.ts` wrappers |
|
|
30
32
|
|
|
31
33
|
## Quick start
|
|
@@ -84,17 +86,39 @@ import * as schema from './schema';
|
|
|
84
86
|
export const getDbBound = (env: { DATABASE_URL: string }) => getDb(env, schema);
|
|
85
87
|
```
|
|
86
88
|
|
|
87
|
-
**5. Frontend
|
|
89
|
+
**5. Frontend data layer** — the app owns its shape, the package owns the machine:
|
|
88
90
|
|
|
89
91
|
```ts
|
|
90
|
-
|
|
91
|
-
import {
|
|
92
|
+
// src/data/store.ts — this file IS the app's data layer now
|
|
93
|
+
import { createStore } from '@umituz/web-hono/store';
|
|
92
94
|
|
|
93
|
-
export {
|
|
94
|
-
export
|
|
95
|
-
|
|
95
|
+
export interface Database { orders: Order[]; loyalty: LoyaltyProgram; /* … */ }
|
|
96
|
+
export type CollectionKey = keyof Database;
|
|
97
|
+
|
|
98
|
+
const ENDPOINTS: Record<CollectionKey, string> = { orders: '/api/orders', loyalty: '/api/loyalty', /* … */ };
|
|
99
|
+
const emptyDatabase = (): Database => ({ orders: [], loyalty: EMPTY_LOYALTY });
|
|
100
|
+
|
|
101
|
+
export const store = createStore<Database>({ endpoints: ENDPOINTS, empty: emptyDatabase });
|
|
102
|
+
export const { ensureHydrated, refresh, getDb, subscribe, apiWrite } = store;
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
// src/data/http.ts — two re-exports, nothing else
|
|
107
|
+
export { apiFetch } from '@umituz/web-hono/client';
|
|
108
|
+
export { apiWrite } from './store';
|
|
96
109
|
```
|
|
97
110
|
|
|
111
|
+
```ts
|
|
112
|
+
// src/core/useQuery.ts — hooks bound to the store (react: optional peer)
|
|
113
|
+
import { makeStoreHooks } from '@umituz/web-hono/store/react';
|
|
114
|
+
import { store } from '@/data/store';
|
|
115
|
+
|
|
116
|
+
export const { useQuery, useDbValue } = makeStoreHooks(store);
|
|
117
|
+
export type { QueryResult } from '@umituz/web-hono/store/react';
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The machine: first read hydrates every collection in parallel (deduped, retried on failure); repositories read synchronously via `getDb()`; writes go through `store.apiWrite(path, init, keys)` which refreshes only the touched collections on success and leaves the cache untouched on failure; per-collection pub/sub (plus the `__refetch_all__` wildcard) drives the hooks. Singleton collections (org-per-row settings like `loyalty`) load with the same call — no special-casing.
|
|
121
|
+
|
|
98
122
|
**6. Lifecycle scripts** (`scripts/`) — keep only your `TABLE_SPECS` registry and thin wrappers:
|
|
99
123
|
|
|
100
124
|
```ts
|
|
@@ -113,6 +137,7 @@ await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.js
|
|
|
113
137
|
## What stays in the app
|
|
114
138
|
|
|
115
139
|
- `api/schema.ts` — every table, the project's `TABLE_PREFIX`, fleet column standards (time trio, soft delete, jsonb nesting)
|
|
140
|
+
- The `Database` interface, `ENDPOINTS` map and empty state of `src/data/store.ts` — that shape IS the app
|
|
116
141
|
- Domain routers with business rules (order transitions, reservation overlap guards, restock side effects)
|
|
117
142
|
- Zod schemas and per-route error messages
|
|
118
143
|
- Audit/notification/entitlement helpers (they insert into YOUR tables)
|
|
@@ -124,7 +149,7 @@ await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.js
|
|
|
124
149
|
npm test
|
|
125
150
|
```
|
|
126
151
|
|
|
127
|
-
|
|
152
|
+
28 vitest cases cover the pure logic and DB-free short-circuit paths (pickPatch filters, uid shape, the 400/404 envelopes, validator contract, client error mapping, reset safety stop, and the store machine: hydration dedupe/retry, refresh selectivity, pub/sub semantics, apiWrite success/failure). Live-DB paths (list/PATCH success, snapshot/seed, hydration against the real API) are proven by the consuming app's E2E — the pilot is foodora.
|
|
128
153
|
|
|
129
154
|
## License
|
|
130
155
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-hono",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Hono backend contract for Cloudflare Workers + Neon Postgres: crudRoutes factory, pickPatch, validateJson, apiFetch/apiWrite client, and db lifecycle scripts (reset / snapshot / seed)",
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Hono backend contract for Cloudflare Workers + Neon Postgres: crudRoutes factory, pickPatch, validateJson, apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), and db lifecycle scripts (reset / snapshot / seed)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
7
7
|
"types": "./src/index.ts",
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
".": "./src/index.ts",
|
|
11
11
|
"./validator": "./src/validator.ts",
|
|
12
12
|
"./client": "./src/client.ts",
|
|
13
|
+
"./store": "./src/store.ts",
|
|
14
|
+
"./store/react": "./src/store-react.ts",
|
|
13
15
|
"./lifecycle": "./src/lifecycle.ts",
|
|
14
16
|
"./package.json": "./package.json"
|
|
15
17
|
},
|
|
@@ -39,6 +41,9 @@
|
|
|
39
41
|
"zod",
|
|
40
42
|
"validation",
|
|
41
43
|
"api-client",
|
|
44
|
+
"store",
|
|
45
|
+
"reactive-store",
|
|
46
|
+
"cache",
|
|
42
47
|
"seed",
|
|
43
48
|
"snapshot",
|
|
44
49
|
"database-lifecycle",
|
|
@@ -50,21 +55,29 @@
|
|
|
50
55
|
"license": "MIT",
|
|
51
56
|
"repository": {
|
|
52
57
|
"type": "git",
|
|
53
|
-
"url": "https://github.com/umituz/web-hono"
|
|
58
|
+
"url": "git+https://github.com/umituz/web-hono.git"
|
|
54
59
|
},
|
|
55
60
|
"peerDependencies": {
|
|
56
61
|
"@neondatabase/serverless": "^1.0.0",
|
|
57
62
|
"drizzle-orm": "^0.45.4",
|
|
58
63
|
"hono": "^4.0.0",
|
|
64
|
+
"react": "^18.0.0 || ^19.0.0",
|
|
59
65
|
"zod": "^4.0.0"
|
|
60
66
|
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"react": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
71
|
+
},
|
|
61
72
|
"devDependencies": {
|
|
62
73
|
"@eslint/js": "^9.32.0",
|
|
63
74
|
"@neondatabase/serverless": "^1.2.0",
|
|
64
75
|
"@types/node": "~22.13.10",
|
|
76
|
+
"@types/react": "^19.1.0",
|
|
65
77
|
"drizzle-orm": "^0.45.4",
|
|
66
78
|
"eslint": "^9.32.0",
|
|
67
79
|
"hono": "^4.13.13",
|
|
80
|
+
"react": "^19.1.0",
|
|
68
81
|
"typescript": "~5.9.2",
|
|
69
82
|
"typescript-eslint": "^8.58.0",
|
|
70
83
|
"vitest": "3.2.4",
|
package/src/crud.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { and, asc, desc, eq, isNull } from 'drizzle-orm';
|
|
|
3
3
|
import { drizzle } from 'drizzle-orm/neon-http';
|
|
4
4
|
import { neon } from '@neondatabase/serverless';
|
|
5
5
|
import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
|
|
6
|
-
import { pickPatch } from './lib';
|
|
6
|
+
import { pickPatch, stampUpdate } from './lib';
|
|
7
7
|
import type { ApiEnv } from './env';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -11,6 +11,9 @@ import type { ApiEnv } from './env';
|
|
|
11
11
|
* PATCH /:id (pickPatch-filtered body, updatedAt stamp, 404 on miss).
|
|
12
12
|
* Mount it onto an area router with `.route('/', crudRoutes({ ... }))`.
|
|
13
13
|
*
|
|
14
|
+
* listRoutes is its GET-only sibling for append-only collections (event
|
|
15
|
+
* logs, activities, users) whose rows are written server-side only.
|
|
16
|
+
*
|
|
14
17
|
* Entities with business rules (role immutability guards, goods-receipt
|
|
15
18
|
* restock, order transitions…) stay hand-written in their area router —
|
|
16
19
|
* the factory is for plain settings/catalog rows only.
|
|
@@ -18,14 +21,35 @@ import type { ApiEnv } from './env';
|
|
|
18
21
|
|
|
19
22
|
export type CrudTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
|
|
20
23
|
|
|
21
|
-
export interface
|
|
22
|
-
/** Path under /api, e.g. '/
|
|
24
|
+
export interface ListSpec {
|
|
25
|
+
/** Path under /api, e.g. '/activities'. */
|
|
23
26
|
path: string;
|
|
27
|
+
table: PgTable & { deletedAt: PgColumn };
|
|
28
|
+
/** List order; defaults to insertion order. */
|
|
29
|
+
orderBy?: { col: PgColumn; dir?: 'asc' | 'desc' };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface CrudSpec extends ListSpec {
|
|
24
33
|
table: CrudTable;
|
|
25
34
|
/** Human label for 404s — 'Product' → 'Product not found'. */
|
|
26
35
|
label: string;
|
|
27
|
-
|
|
28
|
-
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** GET-only list (soft-deleted hidden) for append-only collections — event
|
|
39
|
+
* logs, activities, users. No PATCH: these rows are written server-side. */
|
|
40
|
+
export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
|
|
41
|
+
const { path, table, orderBy } = spec;
|
|
42
|
+
const router = new Hono<{ Bindings: ApiEnv }>();
|
|
43
|
+
|
|
44
|
+
router.get(path, async (c) => {
|
|
45
|
+
// Schema-less drizzle: see the note in crudRoutes.
|
|
46
|
+
const db = drizzle(neon(c.env.DATABASE_URL));
|
|
47
|
+
const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
|
|
48
|
+
if (orderBy) q.orderBy(orderBy.dir === 'desc' ? desc(orderBy.col) : asc(orderBy.col));
|
|
49
|
+
return c.json(await q);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
return router;
|
|
29
53
|
}
|
|
30
54
|
|
|
31
55
|
export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
@@ -49,8 +73,9 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
|
49
73
|
const [row] = await db
|
|
50
74
|
.update(table)
|
|
51
75
|
// Generic tables can't carry per-table set types — values are already
|
|
52
|
-
// column-filtered by pickPatch, so the cast is purely type-level.
|
|
53
|
-
|
|
76
|
+
// column-filtered by pickPatch, so the cast is purely type-level. The
|
|
77
|
+
// updatedAt stamp matches the table's column type (date vs timestamp).
|
|
78
|
+
.set({ ...patch, ...stampUpdate(table) } as never)
|
|
54
79
|
.where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
|
|
55
80
|
.returning();
|
|
56
81
|
return row ? c.json(row) : c.json({ error: `${label} not found` }, 404);
|
package/src/index.ts
CHANGED
|
@@ -14,9 +14,9 @@
|
|
|
14
14
|
* `/client` apiFetch / apiWrite — the same-origin API client
|
|
15
15
|
* `/lifecycle` reset / snapshot / seed — the shared-Neon db lifecycle
|
|
16
16
|
*/
|
|
17
|
-
export { crudRoutes } from './crud';
|
|
18
|
-
export type { CrudSpec, CrudTable } from './crud';
|
|
17
|
+
export { crudRoutes, listRoutes } from './crud';
|
|
18
|
+
export type { CrudSpec, CrudTable, ListSpec } from './crud';
|
|
19
19
|
export { getDb } from './db';
|
|
20
|
-
export { uid, pickPatch } from './lib';
|
|
20
|
+
export { uid, pickPatch, stampUpdate } from './lib';
|
|
21
21
|
export { apiNotFound, spaFallback } from './handlers';
|
|
22
22
|
export type { ApiEnv } from './env';
|
package/src/lib.ts
CHANGED
|
@@ -11,6 +11,28 @@ export function uid(prefix: string): string {
|
|
|
11
11
|
/** Fields no client may ever patch. */
|
|
12
12
|
const PROTECTED_KEYS = new Set(['id', 'createdAt', 'updatedAt', 'deletedAt']);
|
|
13
13
|
|
|
14
|
+
/** Local calendar day as 'YYYY-MM-DD' — the stamp for date-string columns. */
|
|
15
|
+
function localDateStamp(): string {
|
|
16
|
+
const d = new Date();
|
|
17
|
+
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
|
18
|
+
const dd = String(d.getDate()).padStart(2, '0');
|
|
19
|
+
return `${d.getFullYear()}-${mm}-${dd}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* updatedAt stamp matching the table's column type. Fleet-standard tables
|
|
24
|
+
* (timestamp withTimezone) get a Date — unchanged from previous versions.
|
|
25
|
+
* Domains that model updatedAt as a calendar date column (date string,
|
|
26
|
+
* e.g. polaris) get today's local 'YYYY-MM-DD' instead of a Date that the
|
|
27
|
+
* column cannot carry.
|
|
28
|
+
*/
|
|
29
|
+
export function stampUpdate(table: PgTable): Record<string, unknown> {
|
|
30
|
+
const columns = getTableColumns(table) as unknown as Record<string, { columnType: string }>;
|
|
31
|
+
return columns.updatedAt?.columnType.includes('Timestamp')
|
|
32
|
+
? { updatedAt: new Date() }
|
|
33
|
+
: { updatedAt: localDateStamp() };
|
|
34
|
+
}
|
|
35
|
+
|
|
14
36
|
/**
|
|
15
37
|
* Filters a JSON patch body down to the table's own columns (drizzle speaks
|
|
16
38
|
* the camelCase schema PROPERTY names — which are the domain field names).
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/* React bindings for a createStore instance. The store is framework-free;
|
|
2
|
+
apps that don't use React never import this entry. Binding pattern:
|
|
3
|
+
|
|
4
|
+
const store = createStore(config);
|
|
5
|
+
export const { useQuery, useDbValue } = makeStoreHooks(store); */
|
|
6
|
+
|
|
7
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
8
|
+
import { REFETCH_ALL, type createStore } from './store';
|
|
9
|
+
|
|
10
|
+
export interface QueryResult<T> {
|
|
11
|
+
data: T | undefined;
|
|
12
|
+
status: 'loading' | 'success' | 'error';
|
|
13
|
+
error?: string;
|
|
14
|
+
refetch: () => void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type Store<Database extends object> = ReturnType<typeof createStore<Database>>;
|
|
18
|
+
|
|
19
|
+
export function makeStoreHooks<Database extends object>(store: Store<Database>) {
|
|
20
|
+
/** Async queries with loading/error states; re-runs when the underlying
|
|
21
|
+
* collections change (via the store's pub/sub) or when the key changes. */
|
|
22
|
+
function useQuery<T>(key: unknown[], fetcher: () => Promise<T>, enabled = true): QueryResult<T> {
|
|
23
|
+
const keyStr = JSON.stringify(key);
|
|
24
|
+
const fetcherRef = useRef(fetcher);
|
|
25
|
+
fetcherRef.current = fetcher;
|
|
26
|
+
|
|
27
|
+
const [tick, setTick] = useState(0);
|
|
28
|
+
const [state, setState] = useState<{ data?: T; status: 'loading' | 'success' | 'error'; error?: string }>({
|
|
29
|
+
status: 'loading',
|
|
30
|
+
});
|
|
31
|
+
const requestId = useRef(0);
|
|
32
|
+
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
if (!enabled) return;
|
|
35
|
+
const id = ++requestId.current;
|
|
36
|
+
let alive = true;
|
|
37
|
+
setState((s) => ({ ...s, status: 'loading' }));
|
|
38
|
+
fetcherRef.current().then(
|
|
39
|
+
(data) => {
|
|
40
|
+
if (alive && id === requestId.current) setState({ data, status: 'success' });
|
|
41
|
+
},
|
|
42
|
+
(err) => {
|
|
43
|
+
if (alive && id === requestId.current)
|
|
44
|
+
setState({ data: undefined, status: 'error', error: err instanceof Error ? err.message : 'Request failed' });
|
|
45
|
+
},
|
|
46
|
+
);
|
|
47
|
+
return () => {
|
|
48
|
+
alive = false;
|
|
49
|
+
};
|
|
50
|
+
}, [keyStr, tick, enabled]);
|
|
51
|
+
|
|
52
|
+
useEffect(() => {
|
|
53
|
+
const keys: string[] = JSON.parse(keyStr);
|
|
54
|
+
return store.subscribe([...keys, REFETCH_ALL], () => setTick((t) => t + 1));
|
|
55
|
+
}, [keyStr]);
|
|
56
|
+
|
|
57
|
+
const refetch = useCallback(() => setTick((t) => t + 1), []);
|
|
58
|
+
return { data: state.data, status: state.status, error: state.error, refetch };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Non-promise variant for synchronous derived reads that should still
|
|
62
|
+
* refresh when collections change. */
|
|
63
|
+
function useDbValue<T>(compute: () => T, keys: string[]): T {
|
|
64
|
+
const [, force] = useState(0);
|
|
65
|
+
const computeRef = useRef(compute);
|
|
66
|
+
computeRef.current = compute;
|
|
67
|
+
const valueRef = useRef<T>(compute());
|
|
68
|
+
valueRef.current = computeRef.current();
|
|
69
|
+
// deps: the joined key string — the subscription only changes when it does
|
|
70
|
+
useEffect(() => store.subscribe(keys, () => force((v) => v + 1)), [keys.join(',')]);
|
|
71
|
+
return valueRef.current;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return { useQuery, useDbValue };
|
|
75
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/* Fetch-backed reactive cache — the client twin of the thin-read/fat-write
|
|
2
|
+
doctrine. The app owns its Database shape, endpoint map and empty-state
|
|
3
|
+
factory (that IS the app); this module owns the machine: hydrate-every-
|
|
4
|
+
collection-once, targeted refresh after writes, synchronous reads and
|
|
5
|
+
per-collection pub/sub. `apiWrite` comes back bound to the store, so the
|
|
6
|
+
whole client glue per app is one `createStore` call. */
|
|
7
|
+
|
|
8
|
+
import { apiFetch, apiWrite as clientApiWrite } from './client';
|
|
9
|
+
|
|
10
|
+
export interface StoreConfig<Database extends object> {
|
|
11
|
+
/** API endpoint per collection key (e.g. orders → '/api/orders'). */
|
|
12
|
+
endpoints: Record<keyof Database & string, string>;
|
|
13
|
+
/** Fresh empty cache — the pre-hydration state (arrays, singleton defaults). */
|
|
14
|
+
empty: () => Database;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Wildcard channel: every emit also pings its subscribers (useQuery). */
|
|
18
|
+
export const REFETCH_ALL = '__refetch_all__';
|
|
19
|
+
|
|
20
|
+
type Listener = () => void;
|
|
21
|
+
|
|
22
|
+
export function createStore<Database extends object>(config: StoreConfig<Database>) {
|
|
23
|
+
const { endpoints, empty } = config;
|
|
24
|
+
const keys = Object.keys(endpoints) as (keyof Database & string)[];
|
|
25
|
+
const cache: Database = empty(); // mutated in place as collections load
|
|
26
|
+
let hydration: Promise<void> | null = null;
|
|
27
|
+
|
|
28
|
+
const listeners = new Map<string, Set<Listener>>();
|
|
29
|
+
|
|
30
|
+
function emit(key: string) {
|
|
31
|
+
listeners.get(key)?.forEach((l) => l());
|
|
32
|
+
listeners.get(REFETCH_ALL)?.forEach((l) => l());
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function loadCollection(key: keyof Database & string): Promise<void> {
|
|
36
|
+
// Rows arrive domain-shaped (drizzle serializes property names; dates as
|
|
37
|
+
// ISO strings). Singleton collections return their one row — same call.
|
|
38
|
+
(cache as Record<string, unknown>)[key] = await apiFetch<unknown>(endpoints[key]);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Fetch every collection once (parallel) and populate the cache. */
|
|
42
|
+
function ensureHydrated(): Promise<void> {
|
|
43
|
+
if (!hydration) {
|
|
44
|
+
hydration = (async () => {
|
|
45
|
+
await Promise.all(keys.map((key) => loadCollection(key)));
|
|
46
|
+
keys.forEach(emit); // per-collection subscribers
|
|
47
|
+
emit(REFETCH_ALL); // useQuery subscribers
|
|
48
|
+
})().catch((err) => {
|
|
49
|
+
hydration = null; // next reader retries
|
|
50
|
+
throw err;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return hydration;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Re-fetch the given collections after a write, then invalidate subscribers. */
|
|
57
|
+
async function refresh(collectionKeys: ReadonlyArray<keyof Database & string>): Promise<void> {
|
|
58
|
+
await Promise.all(collectionKeys.map((key) => loadCollection(key)));
|
|
59
|
+
collectionKeys.forEach(emit);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Synchronous cache read (empty until first hydration completes). */
|
|
63
|
+
function getDb(): Database {
|
|
64
|
+
return cache;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function subscribe(collectionKeys: string[], cb: Listener): () => void {
|
|
68
|
+
const disposers = collectionKeys.map((key) => {
|
|
69
|
+
if (!listeners.has(key)) listeners.set(key, new Set());
|
|
70
|
+
listeners.get(key)!.add(cb);
|
|
71
|
+
return () => listeners.get(key)?.delete(cb);
|
|
72
|
+
});
|
|
73
|
+
return () => disposers.forEach((d) => d());
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The repository write idiom, bound: mutate through the API, then refresh
|
|
77
|
+
* the collections the write touched. Refresh only runs when the write
|
|
78
|
+
* succeeded — failures leave the cache untouched. */
|
|
79
|
+
function apiWrite<T = void>(
|
|
80
|
+
path: string,
|
|
81
|
+
init: { method: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; json?: unknown },
|
|
82
|
+
collectionKeys: ReadonlyArray<keyof Database & string> = [],
|
|
83
|
+
): Promise<T> {
|
|
84
|
+
return clientApiWrite<T>(path, init, [...collectionKeys], (keys) => refresh(keys as (keyof Database & string)[]));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return { ensureHydrated, refresh, getDb, subscribe, emit, apiWrite };
|
|
88
|
+
}
|