@umituz/web-hono 0.0.0-stage → 1.1.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 +21 -0
- package/README.md +155 -2
- package/package.json +95 -4
- package/src/client.ts +36 -0
- package/src/crud.ts +60 -0
- package/src/db.ts +15 -0
- package/src/env.ts +13 -0
- package/src/handlers.ts +18 -0
- package/src/index.ts +22 -0
- package/src/lib.ts +37 -0
- package/src/lifecycle.ts +121 -0
- package/src/store-react.ts +75 -0
- package/src/store.ts +88 -0
- package/src/validator.ts +25 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 umituz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,156 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @umituz/web-hono
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
|
|
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
|
+
|
|
7
|
+
## Design philosophy
|
|
8
|
+
|
|
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
|
+
- **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, 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
|
+
- **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
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @umituz/web-hono
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Peer dependencies (install alongside): `hono ^4`, `drizzle-orm ^0.45`, `@neondatabase/serverless ^1`, `zod ^4`.
|
|
21
|
+
|
|
22
|
+
## Entry points
|
|
23
|
+
|
|
24
|
+
| Entry point | Exports | Used by |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| `@umituz/web-hono` | `crudRoutes`, `CrudSpec`/`CrudTable`, `getDb`, `uid`, `pickPatch`, `apiNotFound`, `spaFallback`, `ApiEnv` | `api/index.ts`, area routers, `api/db.ts` |
|
|
27
|
+
| `@umituz/web-hono/validator` | `validateJson(schema, message?)` | every hand-written POST/PATCH route |
|
|
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) |
|
|
31
|
+
| `@umituz/web-hono/lifecycle` | `resetTables`, `snapshotToSeed`, `seedFromSnapshot`, `TableSpec`, `SeedSnapshot` | `scripts/reset.ts` / `snapshot.ts` / `seed.ts` wrappers |
|
|
32
|
+
|
|
33
|
+
## Quick start
|
|
34
|
+
|
|
35
|
+
**1. Worker entry** (`api/index.ts`) — mount list, then close the chain:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { Hono } from 'hono';
|
|
39
|
+
import { apiNotFound, spaFallback } from '@umituz/web-hono';
|
|
40
|
+
import type { ApiEnv } from '@umituz/web-hono';
|
|
41
|
+
import { healthRouter } from './routes/health';
|
|
42
|
+
import { orgRouter } from './routes/org';
|
|
43
|
+
|
|
44
|
+
const app = new Hono<{ Bindings: ApiEnv }>();
|
|
45
|
+
|
|
46
|
+
app.route('/api/health', healthRouter);
|
|
47
|
+
app.route('/api', orgRouter);
|
|
48
|
+
|
|
49
|
+
app.all('/api/*', apiNotFound); // unmatched API stays JSON — never the SPA's index.html
|
|
50
|
+
app.get('*', spaFallback); // client-side routes resolve via the ASSETS binding
|
|
51
|
+
|
|
52
|
+
export default app;
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**2. Factory mounts** (area routers) — plain settings/catalog entities:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { crudRoutes } from '@umituz/web-hono';
|
|
59
|
+
|
|
60
|
+
orgRouter.route('/', crudRoutes({ path: '/branches', table: branches, label: 'Branch', orderBy: { col: branches.name } }));
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Generates `GET /api/branches` (visible rows, ordered) + `PATCH /api/branches/:id` (pickPatch-filtered body, `updatedAt` stamp, `404 'Branch not found'`).
|
|
64
|
+
|
|
65
|
+
**3. Validated writes** — the single definition of the body contract:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { validator } from 'hono/validator';
|
|
69
|
+
import { validateJson } from '@umituz/web-hono/validator';
|
|
70
|
+
|
|
71
|
+
app.post(
|
|
72
|
+
'/products',
|
|
73
|
+
validator('json', validateJson(CreateProductSchema, 'Invalid product payload')),
|
|
74
|
+
(c) => { /* c.req.valid('json') is the parsed zod output */ },
|
|
75
|
+
);
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Failures answer `400 { error: <message>, details: <fieldErrors> }` — the envelope every client toast surfaces.
|
|
79
|
+
|
|
80
|
+
**4. App db wrapper** (`api/db.ts`) — bind your schema once:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { getDb } from '@umituz/web-hono';
|
|
84
|
+
import * as schema from './schema';
|
|
85
|
+
|
|
86
|
+
export const getDbBound = (env: { DATABASE_URL: string }) => getDb(env, schema);
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
**5. Frontend data layer** — the app owns its shape, the package owns the machine:
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
// src/data/store.ts — this file IS the app's data layer now
|
|
93
|
+
import { createStore } from '@umituz/web-hono/store';
|
|
94
|
+
|
|
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';
|
|
109
|
+
```
|
|
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
|
+
|
|
122
|
+
**6. Lifecycle scripts** (`scripts/`) — keep only your `TABLE_SPECS` registry and thin wrappers:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
// scripts/snapshot.ts
|
|
126
|
+
import 'dotenv/config';
|
|
127
|
+
import { snapshotToSeed } from '@umituz/web-hono/lifecycle';
|
|
128
|
+
import { TABLE_SPECS } from './tables';
|
|
129
|
+
|
|
130
|
+
const url = process.env.DATABASE_URL;
|
|
131
|
+
if (!url) throw new Error('DATABASE_URL is required (.env)');
|
|
132
|
+
await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.json.gz', import.meta.url) });
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`resetTables({ specs, prefix, url })` drops only `prefix*` tables (in reverse registry order, CASCADE); `seedFromSnapshot({ specs, url, inPath })` replays idempotently (ON CONFLICT DO NOTHING, 200-row chunks, per-column-type revival of timestamps/dates).
|
|
136
|
+
|
|
137
|
+
## What stays in the app
|
|
138
|
+
|
|
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
|
|
141
|
+
- Domain routers with business rules (order transitions, reservation overlap guards, restock side effects)
|
|
142
|
+
- Zod schemas and per-route error messages
|
|
143
|
+
- Audit/notification/entitlement helpers (they insert into YOUR tables)
|
|
144
|
+
- `api/routes/health.ts` — the `BUILD_MARKER` deploy canary is per-project
|
|
145
|
+
|
|
146
|
+
## Testing
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
npm test
|
|
150
|
+
```
|
|
151
|
+
|
|
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.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,97 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-hono",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.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
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"types": "./src/index.ts",
|
|
8
|
+
"sideEffects": false,
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./src/index.ts",
|
|
11
|
+
"./validator": "./src/validator.ts",
|
|
12
|
+
"./client": "./src/client.ts",
|
|
13
|
+
"./store": "./src/store.ts",
|
|
14
|
+
"./store/react": "./src/store-react.ts",
|
|
15
|
+
"./lifecycle": "./src/lifecycle.ts",
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"typecheck": "tsc --noEmit",
|
|
20
|
+
"lint": "eslint .",
|
|
21
|
+
"test": "vitest run",
|
|
22
|
+
"test:watch": "vitest",
|
|
23
|
+
"prepublishOnly": "npm run typecheck && npm run lint && npm test",
|
|
24
|
+
"version:patch": "npm version patch -m 'chore: release v%s'",
|
|
25
|
+
"version:minor": "npm version minor -m 'chore: release v%s'",
|
|
26
|
+
"version:major": "npm version major -m 'chore: release v%s'"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"hono",
|
|
30
|
+
"hono-api",
|
|
31
|
+
"cloudflare-workers",
|
|
32
|
+
"workers",
|
|
33
|
+
"neon",
|
|
34
|
+
"postgres",
|
|
35
|
+
"drizzle",
|
|
36
|
+
"drizzle-orm",
|
|
37
|
+
"crud",
|
|
38
|
+
"crud-factory",
|
|
39
|
+
"rest-api",
|
|
40
|
+
"spa-fallback",
|
|
41
|
+
"zod",
|
|
42
|
+
"validation",
|
|
43
|
+
"api-client",
|
|
44
|
+
"store",
|
|
45
|
+
"reactive-store",
|
|
46
|
+
"cache",
|
|
47
|
+
"seed",
|
|
48
|
+
"snapshot",
|
|
49
|
+
"database-lifecycle",
|
|
50
|
+
"serverless",
|
|
51
|
+
"typescript",
|
|
52
|
+
"edge"
|
|
53
|
+
],
|
|
54
|
+
"author": "umituz",
|
|
55
|
+
"license": "MIT",
|
|
56
|
+
"repository": {
|
|
57
|
+
"type": "git",
|
|
58
|
+
"url": "git+https://github.com/umituz/web-hono.git"
|
|
59
|
+
},
|
|
60
|
+
"peerDependencies": {
|
|
61
|
+
"@neondatabase/serverless": "^1.0.0",
|
|
62
|
+
"drizzle-orm": "^0.45.4",
|
|
63
|
+
"hono": "^4.0.0",
|
|
64
|
+
"react": "^18.0.0 || ^19.0.0",
|
|
65
|
+
"zod": "^4.0.0"
|
|
66
|
+
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"react": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"devDependencies": {
|
|
73
|
+
"@eslint/js": "^9.32.0",
|
|
74
|
+
"@neondatabase/serverless": "^1.2.0",
|
|
75
|
+
"@types/node": "~22.13.10",
|
|
76
|
+
"@types/react": "^19.1.0",
|
|
77
|
+
"drizzle-orm": "^0.45.4",
|
|
78
|
+
"eslint": "^9.32.0",
|
|
79
|
+
"hono": "^4.13.13",
|
|
80
|
+
"react": "^19.1.0",
|
|
81
|
+
"typescript": "~5.9.2",
|
|
82
|
+
"typescript-eslint": "^8.58.0",
|
|
83
|
+
"vitest": "3.2.4",
|
|
84
|
+
"zod": "^4.6.5"
|
|
85
|
+
},
|
|
86
|
+
"engines": {
|
|
87
|
+
"node": ">=18"
|
|
88
|
+
},
|
|
89
|
+
"publishConfig": {
|
|
90
|
+
"access": "public"
|
|
91
|
+
},
|
|
92
|
+
"files": [
|
|
93
|
+
"src",
|
|
94
|
+
"README.md",
|
|
95
|
+
"LICENSE"
|
|
96
|
+
]
|
|
97
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/* Minimal JSON client for a same-origin Hono API. Throws an Error carrying
|
|
2
|
+
the server's message (zod/404/400 bodies are `{ error }`) so UI toast
|
|
3
|
+
handlers can surface it directly. */
|
|
4
|
+
|
|
5
|
+
export async function apiFetch<T>(path: string, init: { method?: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; json?: unknown } = {}): Promise<T> {
|
|
6
|
+
const res = await fetch(path, {
|
|
7
|
+
method: init.method ?? 'GET',
|
|
8
|
+
headers: init.json !== undefined ? { 'content-type': 'application/json', accept: 'application/json' } : { accept: 'application/json' },
|
|
9
|
+
body: init.json !== undefined ? JSON.stringify(init.json) : undefined,
|
|
10
|
+
});
|
|
11
|
+
if (!res.ok) {
|
|
12
|
+
const body = (await res.json().catch(() => null)) as { error?: string } | null;
|
|
13
|
+
throw new Error(body?.error ?? `API ${path} responded ${res.status}`);
|
|
14
|
+
}
|
|
15
|
+
return (await res.json()) as T;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The repository write idiom in one call: mutate through the API, then
|
|
20
|
+
* refresh the collections the write touched. Refresh only runs when the
|
|
21
|
+
* write succeeded — failures leave the cache untouched.
|
|
22
|
+
*
|
|
23
|
+
* Hosts with a store/cache layer pass their own `refresh` (and usually wrap
|
|
24
|
+
* this in a typed helper binding their collection keys); `keys` stay plain
|
|
25
|
+
* strings here so the package stays store-agnostic.
|
|
26
|
+
*/
|
|
27
|
+
export async function apiWrite<T = void>(
|
|
28
|
+
path: string,
|
|
29
|
+
init: { method: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; json?: unknown },
|
|
30
|
+
keys: string[] = [],
|
|
31
|
+
refresh: (keys: string[]) => Promise<void> = async () => {},
|
|
32
|
+
): Promise<T> {
|
|
33
|
+
const result = await apiFetch<T>(path, init);
|
|
34
|
+
if (keys.length) await refresh(keys);
|
|
35
|
+
return result;
|
|
36
|
+
}
|
package/src/crud.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { and, asc, desc, eq, isNull } from 'drizzle-orm';
|
|
3
|
+
import { drizzle } from 'drizzle-orm/neon-http';
|
|
4
|
+
import { neon } from '@neondatabase/serverless';
|
|
5
|
+
import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
|
|
6
|
+
import { pickPatch } from './lib';
|
|
7
|
+
import type { ApiEnv } from './env';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The standard entity resource: GET list (soft-deleted hidden, ordered) +
|
|
11
|
+
* PATCH /:id (pickPatch-filtered body, updatedAt stamp, 404 on miss).
|
|
12
|
+
* Mount it onto an area router with `.route('/', crudRoutes({ ... }))`.
|
|
13
|
+
*
|
|
14
|
+
* Entities with business rules (role immutability guards, goods-receipt
|
|
15
|
+
* restock, order transitions…) stay hand-written in their area router —
|
|
16
|
+
* the factory is for plain settings/catalog rows only.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export type CrudTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
|
|
20
|
+
|
|
21
|
+
export interface CrudSpec {
|
|
22
|
+
/** Path under /api, e.g. '/products'. */
|
|
23
|
+
path: string;
|
|
24
|
+
table: CrudTable;
|
|
25
|
+
/** Human label for 404s — 'Product' → 'Product not found'. */
|
|
26
|
+
label: string;
|
|
27
|
+
/** List order; defaults to insertion order. */
|
|
28
|
+
orderBy?: { col: PgColumn; dir?: 'asc' | 'desc' };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
32
|
+
const { path, table, label, orderBy } = spec;
|
|
33
|
+
const router = new Hono<{ Bindings: ApiEnv }>();
|
|
34
|
+
|
|
35
|
+
router.get(path, async (c) => {
|
|
36
|
+
// Schema-less drizzle: the factory only runs select/update, which never
|
|
37
|
+
// touch the schema registry (only `db.query.*` does) — so it builds its
|
|
38
|
+
// own instance from the request's binding instead of requiring one.
|
|
39
|
+
const db = drizzle(neon(c.env.DATABASE_URL));
|
|
40
|
+
const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
|
|
41
|
+
if (orderBy) q.orderBy(orderBy.dir === 'desc' ? desc(orderBy.col) : asc(orderBy.col));
|
|
42
|
+
return c.json(await q);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
router.patch(`${path}/:id`, async (c) => {
|
|
46
|
+
const patch = pickPatch(table, await c.req.json().catch(() => null));
|
|
47
|
+
if (!patch) return c.json({ error: 'No updatable fields' }, 400);
|
|
48
|
+
const db = drizzle(neon(c.env.DATABASE_URL));
|
|
49
|
+
const [row] = await db
|
|
50
|
+
.update(table)
|
|
51
|
+
// 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
|
+
.set({ ...patch, updatedAt: new Date() } as never)
|
|
54
|
+
.where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
|
|
55
|
+
.returning();
|
|
56
|
+
return row ? c.json(row) : c.json({ error: `${label} not found` }, 404);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
return router;
|
|
60
|
+
}
|
package/src/db.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { drizzle } from 'drizzle-orm/neon-http';
|
|
2
|
+
import { neon } from '@neondatabase/serverless';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* neon-http driver: fetch-based, serverless-friendly — no connection pool,
|
|
6
|
+
* no Hyperdrive needed. Each request gets its own HTTP call to Neon.
|
|
7
|
+
*
|
|
8
|
+
* `schema` is the app's drizzle schema (`import * as schema from './schema'`)
|
|
9
|
+
* and enables relational `db.query.*` access; plain select/insert/update
|
|
10
|
+
* paths work regardless.
|
|
11
|
+
*/
|
|
12
|
+
export function getDb<TSchema extends Record<string, unknown>>(env: { DATABASE_URL: string }, schema: TSchema) {
|
|
13
|
+
const sql = neon(env.DATABASE_URL);
|
|
14
|
+
return drizzle(sql, { schema });
|
|
15
|
+
}
|
package/src/env.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker bindings — self-contained types (no @cloudflare/workers-types dep).
|
|
3
|
+
* Apps with extra bindings extend this interface; the package's helpers
|
|
4
|
+
* only ever need these two.
|
|
5
|
+
*/
|
|
6
|
+
export interface ApiEnv {
|
|
7
|
+
/** Neon Postgres connection string (wrangler secret / .dev.vars). */
|
|
8
|
+
DATABASE_URL: string;
|
|
9
|
+
/** Static assets binding (Workers Static Assets) for SPA fallback. */
|
|
10
|
+
ASSETS: {
|
|
11
|
+
fetch(input: Request | string, init?: RequestInit): Promise<Response>;
|
|
12
|
+
};
|
|
13
|
+
}
|
package/src/handlers.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Handler } from 'hono';
|
|
2
|
+
import type { ApiEnv } from './env';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Unmatched API paths must stay JSON — without this they'd fall into the
|
|
6
|
+
* SPA fallback and return index.html with a 200.
|
|
7
|
+
* Usage: `app.all('/api/*', apiNotFound)`.
|
|
8
|
+
*/
|
|
9
|
+
export const apiNotFound: Handler<{ Bindings: ApiEnv }> = (c) => c.json({ error: 'Not found' }, 404);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* SPA fallback: client-side routes (e.g. /suppliers) have no asset file.
|
|
13
|
+
* Pass the ORIGINAL request to the assets binding — with
|
|
14
|
+
* `not_found_handling: "single-page-application"` it resolves to index.html
|
|
15
|
+
* in place (no redirect). Fetching "/index.html" explicitly would 307 to "/".
|
|
16
|
+
* Usage: `app.get('*', spaFallback)`.
|
|
17
|
+
*/
|
|
18
|
+
export const spaFallback: Handler<{ Bindings: ApiEnv }> = (c) => c.env.ASSETS.fetch(c.req.raw);
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @umituz/web-hono — the Hono backend contract for single-Worker apps on
|
|
3
|
+
* Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle:
|
|
4
|
+
* the crudRoutes factory, pickPatch/uid helpers, getDb, the JSON-404 and
|
|
5
|
+
* SPA-fallback handlers, and the ApiEnv binding types.
|
|
6
|
+
*
|
|
7
|
+
* Apps keep their schema (with TABLE_PREFIX), domain routers, zod schemas,
|
|
8
|
+
* and business rules — this package owns the cross-cutting API skeleton
|
|
9
|
+
* only.
|
|
10
|
+
*
|
|
11
|
+
* Entry points:
|
|
12
|
+
* `.` server core (this file)
|
|
13
|
+
* `/validator` validateJson — the zod `{ error, details }` body contract
|
|
14
|
+
* `/client` apiFetch / apiWrite — the same-origin API client
|
|
15
|
+
* `/lifecycle` reset / snapshot / seed — the shared-Neon db lifecycle
|
|
16
|
+
*/
|
|
17
|
+
export { crudRoutes } from './crud';
|
|
18
|
+
export type { CrudSpec, CrudTable } from './crud';
|
|
19
|
+
export { getDb } from './db';
|
|
20
|
+
export { uid, pickPatch } from './lib';
|
|
21
|
+
export { apiNotFound, spaFallback } from './handlers';
|
|
22
|
+
export type { ApiEnv } from './env';
|
package/src/lib.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { getTableColumns } from 'drizzle-orm';
|
|
2
|
+
import type { PgTable } from 'drizzle-orm/pg-core';
|
|
3
|
+
|
|
4
|
+
/** Server-side id generation: `${prefix}_${base36 timestamp}${base36 counter}`. */
|
|
5
|
+
let idCounter = 0;
|
|
6
|
+
export function uid(prefix: string): string {
|
|
7
|
+
idCounter += 1;
|
|
8
|
+
return `${prefix}_${Date.now().toString(36)}${idCounter.toString(36)}`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Fields no client may ever patch. */
|
|
12
|
+
const PROTECTED_KEYS = new Set(['id', 'createdAt', 'updatedAt', 'deletedAt']);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Filters a JSON patch body down to the table's own columns (drizzle speaks
|
|
16
|
+
* the camelCase schema PROPERTY names — which are the domain field names).
|
|
17
|
+
* ISO-datetime strings destined for timestamptz columns become Date objects.
|
|
18
|
+
* Returns null when nothing updatable remains.
|
|
19
|
+
*/
|
|
20
|
+
export function pickPatch(table: PgTable, body: unknown): Record<string, unknown> | null {
|
|
21
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;
|
|
22
|
+
const columns = getTableColumns(table) as unknown as Record<string, { columnType: string }>;
|
|
23
|
+
const out: Record<string, unknown> = {};
|
|
24
|
+
for (const [key, value] of Object.entries(body as Record<string, unknown>)) {
|
|
25
|
+
if (PROTECTED_KEYS.has(key)) continue;
|
|
26
|
+
const col = columns[key];
|
|
27
|
+
if (!col || value === undefined) continue;
|
|
28
|
+
if (typeof value === 'string' && col.columnType.includes('Timestamp')) {
|
|
29
|
+
const d = new Date(value);
|
|
30
|
+
if (Number.isNaN(d.getTime())) continue; // '' and junk → skip, not 500
|
|
31
|
+
out[key] = d;
|
|
32
|
+
} else {
|
|
33
|
+
out[key] = value;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
37
|
+
}
|
package/src/lifecycle.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { getTableName, getTableColumns } from 'drizzle-orm';
|
|
2
|
+
import { neon } from '@neondatabase/serverless';
|
|
3
|
+
import { drizzle } from 'drizzle-orm/neon-http';
|
|
4
|
+
import type { PgTable } from 'drizzle-orm/pg-core';
|
|
5
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Database lifecycle for the shared-Neon-project fleet model: one Neon
|
|
10
|
+
* project hosts many products, each living in its own `TABLE_PREFIX*`
|
|
11
|
+
* tables. `specs` is the app's single table registry (foodora's
|
|
12
|
+
* `scripts/tables.ts` shape) shared by all three operations so snapshot
|
|
13
|
+
* and seed can never diverge.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export interface TableSpec {
|
|
17
|
+
/** Snapshot/seed key AND the SQL table name — e.g. 'users' for `foodora_users`. */
|
|
18
|
+
name: string;
|
|
19
|
+
table: PgTable;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The on-disk shape of a seed snapshot (`seed-data.json.gz`). */
|
|
23
|
+
export interface SeedSnapshot {
|
|
24
|
+
generatedAt: string;
|
|
25
|
+
tables: Record<string, Record<string, unknown>[]>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* db:reset step 1 — drops THIS product's prefixed tables (the npm script
|
|
30
|
+
* chain then recreates them with `drizzle-kit push` and replays `db:seed`).
|
|
31
|
+
* Clean-slate lifecycle for a shared Neon project: when a product is paused,
|
|
32
|
+
* reset it; when work resumes, the same command brings it fully back.
|
|
33
|
+
*
|
|
34
|
+
* SAFETY: only tables whose SQL name carries the prefix are dropped — other
|
|
35
|
+
* products sharing the Neon project are never touched. A spec without the
|
|
36
|
+
* prefix stops everything before a single DROP runs.
|
|
37
|
+
*/
|
|
38
|
+
export async function resetTables(opts: { specs: TableSpec[]; prefix: string; url: string }): Promise<string[]> {
|
|
39
|
+
const sql = neon(opts.url);
|
|
40
|
+
|
|
41
|
+
const names = opts.specs.map((spec) => getTableName(spec.table));
|
|
42
|
+
const unsafe = names.find((n) => !n.startsWith(opts.prefix));
|
|
43
|
+
if (unsafe !== undefined) throw new Error(`Safety stop: '${unsafe}' does not carry prefix '${opts.prefix}' — refusing to drop.`);
|
|
44
|
+
|
|
45
|
+
const dropped: string[] = [];
|
|
46
|
+
for (const name of [...names].reverse()) {
|
|
47
|
+
await sql`DROP TABLE IF EXISTS ${sql.unsafe(`"${name}"`)} CASCADE`;
|
|
48
|
+
dropped.push(name);
|
|
49
|
+
console.log(`dropped: ${name}`);
|
|
50
|
+
}
|
|
51
|
+
console.log(`\n${names.length} '${opts.prefix}*' tables dropped.`);
|
|
52
|
+
return dropped;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* db:snapshot — reads EVERY row of every table (soft-deleted included) and
|
|
57
|
+
* writes the gzipped seed file. Run after meaningful data changes; the
|
|
58
|
+
* snapshot is what `seedFromSnapshot` replays into an empty database.
|
|
59
|
+
* Rows are stored with drizzle PROPERTY names (camelCase), which is exactly
|
|
60
|
+
* what `.values()` speaks — no key mapping on the way back in.
|
|
61
|
+
*/
|
|
62
|
+
export async function snapshotToSeed(opts: { specs: TableSpec[]; url: string; outPath: string | URL }): Promise<{ total: number; rawBytes: number }> {
|
|
63
|
+
const db = drizzle(neon(opts.url));
|
|
64
|
+
|
|
65
|
+
const tables: Record<string, unknown[]> = {};
|
|
66
|
+
let total = 0;
|
|
67
|
+
for (const { name, table } of opts.specs) {
|
|
68
|
+
const rows = (await db.select().from(table)) as unknown[];
|
|
69
|
+
tables[name] = rows;
|
|
70
|
+
total += rows.length;
|
|
71
|
+
console.log(`${name.padEnd(20)} ${rows.length}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const payload = JSON.stringify({ generatedAt: new Date().toISOString(), tables });
|
|
75
|
+
writeFileSync(opts.outPath, gzipSync(Buffer.from(payload, 'utf8')));
|
|
76
|
+
console.log(`\nSnapshot: ${total} rows → ${opts.outPath} (${(payload.length / 1024).toFixed(0)} KiB raw)`);
|
|
77
|
+
return { total, rawBytes: payload.length };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
type Row = Record<string, unknown>;
|
|
81
|
+
|
|
82
|
+
/** ISO string → Date for timestamptz columns; trim to YYYY-MM-DD for date columns. */
|
|
83
|
+
function reviveRow(table: PgTable, row: Row): Row {
|
|
84
|
+
const out: Row = { ...row };
|
|
85
|
+
for (const [key, col] of Object.entries(getTableColumns(table))) {
|
|
86
|
+
const v = out[key];
|
|
87
|
+
if (v === null || v === undefined) continue;
|
|
88
|
+
if (col.columnType.includes('Timestamp')) out[key] = new Date(v as string);
|
|
89
|
+
else if (col.columnType.toLowerCase().includes('date')) out[key] = String(v).slice(0, 10);
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* db:seed — replays the snapshot into the database. Idempotent:
|
|
96
|
+
* ON CONFLICT DO NOTHING — first run wins, existing ids skip. JSON
|
|
97
|
+
* round-trip notes: timestamps come back as ISO strings and dates as
|
|
98
|
+
* 'YYYY-MM-DD'; both are converted back per column type (derived from the
|
|
99
|
+
* drizzle schema — no per-table field lists to maintain).
|
|
100
|
+
*/
|
|
101
|
+
export async function seedFromSnapshot(opts: { specs: TableSpec[]; url: string; inPath: string | URL }): Promise<number> {
|
|
102
|
+
const db = drizzle(neon(opts.url));
|
|
103
|
+
|
|
104
|
+
const snapshot = JSON.parse(gunzipSync(readFileSync(opts.inPath)).toString('utf8')) as SeedSnapshot;
|
|
105
|
+
console.log(`Snapshot generated at ${snapshot.generatedAt}`);
|
|
106
|
+
|
|
107
|
+
let inserted = 0;
|
|
108
|
+
for (const { name, table } of opts.specs) {
|
|
109
|
+
const rows = (snapshot.tables[name] ?? []).map((r) => reviveRow(table, r));
|
|
110
|
+
for (let i = 0; i < rows.length; i += 200) {
|
|
111
|
+
const chunk = rows.slice(i, i + 200);
|
|
112
|
+
// `.returning()` (full rows) instead of `returning({ id })`: some tables
|
|
113
|
+
// are singletons keyed by organization_id without an id column.
|
|
114
|
+
const res = (await db.insert(table).values(chunk as never).onConflictDoNothing().returning()) as unknown[];
|
|
115
|
+
inserted += res.length;
|
|
116
|
+
}
|
|
117
|
+
console.log(`${name.padEnd(20)} ${rows.length} offered`);
|
|
118
|
+
}
|
|
119
|
+
console.log(`\nSeed complete: ${inserted} rows inserted (existing ids skipped).`);
|
|
120
|
+
return inserted;
|
|
121
|
+
}
|
|
@@ -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
|
+
}
|
package/src/validator.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The single definition of the API's JSON-body validation contract:
|
|
6
|
+
* zod safeParse behind hono's `validator('json', …)` — failures answer
|
|
7
|
+
* `400 { error, details: fieldErrors }`, successes flow the parsed (and
|
|
8
|
+
* `.strict()`, `.trim()`-ed) data into the handler via `c.req.valid('json')`.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* app.post(
|
|
12
|
+
* '/widgets',
|
|
13
|
+
* validator('json', validateJson(CreateWidgetSchema, 'Invalid widget payload')),
|
|
14
|
+
* (c) => { const input = c.req.valid('json'); … },
|
|
15
|
+
* );
|
|
16
|
+
*/
|
|
17
|
+
export function validateJson<S extends z.ZodType>(schema: S, message = 'Invalid request body') {
|
|
18
|
+
return (value: unknown, c: Context) => {
|
|
19
|
+
const parsed = schema.safeParse(value);
|
|
20
|
+
if (!parsed.success) {
|
|
21
|
+
return c.json({ error: message, details: parsed.error.flatten().fieldErrors }, 400);
|
|
22
|
+
}
|
|
23
|
+
return parsed.data as z.output<S>;
|
|
24
|
+
};
|
|
25
|
+
}
|