@umituz/web-hono 1.7.9 → 1.8.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/package.json +1 -1
- package/src/docstore.ts +282 -0
- package/src/index.ts +3 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-hono",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.0",
|
|
4
4
|
"description": "API backend platform for Cloudflare Workers + Neon Postgres: createApi skeleton + error envelope layer, full-CRUD resource factory (opt-in create/remove, list params), schema→client type bridge (ClientRow), 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",
|
package/src/docstore.ts
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { and, eq, isNull } from 'drizzle-orm';
|
|
3
|
+
import { drizzle } from 'drizzle-orm/neon-http';
|
|
4
|
+
import { neon } from '@neondatabase/serverless';
|
|
5
|
+
import { validator } from 'hono/validator';
|
|
6
|
+
import type { Context } from 'hono';
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
|
|
9
|
+
import { validateJson } from './validator';
|
|
10
|
+
import type { CrudDb } from './crud';
|
|
11
|
+
import type { ApiEnv } from './env';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The doc-store resource factory for jsonb-wire-faithful architectures:
|
|
15
|
+
* the client owns whole documents (nested shapes, client-generated ids,
|
|
16
|
+
* ISO date strings inside the doc) and the table stores them verbatim in
|
|
17
|
+
* one `data jsonb` column beside the epoch-ms bookkeeping trio. The row
|
|
18
|
+
* never leaks — the wire speaks docs only.
|
|
19
|
+
*
|
|
20
|
+
* One call returns the router (GET list / GET-PUT-PATCH-DELETE by id /
|
|
21
|
+
* POST /batch) AND the motor functions (putDoc/patchDoc/softDeleteDoc/
|
|
22
|
+
* listDocs/getDoc) that seed scripts and server-side workflows call
|
|
23
|
+
* directly. Status machines ride along as declarative `transitions` maps;
|
|
24
|
+
* violations surface as WorkflowError → 400.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
type RequestContext = Context<{ Bindings: ApiEnv }>;
|
|
28
|
+
|
|
29
|
+
export type Doc = Record<string, unknown> & { id: string };
|
|
30
|
+
|
|
31
|
+
export type DocTable = PgTable & { id: PgColumn; data: PgColumn; deletedAt: PgColumn };
|
|
32
|
+
|
|
33
|
+
export interface DocCollectionSpec {
|
|
34
|
+
/** Wire collection name — the URL segment and the batch op key. */
|
|
35
|
+
key: string;
|
|
36
|
+
table: DocTable;
|
|
37
|
+
/** Extra typed columns derived from the doc (users: email/name/flags). */
|
|
38
|
+
columns?: (doc: Doc) => Record<string, unknown>;
|
|
39
|
+
/** Collections that must always write the one fixed id. */
|
|
40
|
+
singletonId?: string;
|
|
41
|
+
/** Status state machine: allowed targets per current status. */
|
|
42
|
+
transitions?: Record<string, string[]>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface DocStoreSpec {
|
|
46
|
+
collections: readonly DocCollectionSpec[];
|
|
47
|
+
/** Injectable db factory (tests, Hyperdrive). Default: per-request neon-http. */
|
|
48
|
+
db?: (c: RequestContext) => CrudDb;
|
|
49
|
+
/** POST /batch op cap. Default 2000. */
|
|
50
|
+
maxBatch?: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export class WorkflowError extends Error {}
|
|
54
|
+
export class UnknownCollectionError extends Error {}
|
|
55
|
+
|
|
56
|
+
/** Status machine check: staying put is always allowed. */
|
|
57
|
+
export function canTransition(map: Record<string, string[]>, from: string, to: string): boolean {
|
|
58
|
+
return from === to || (map[from] ?? []).includes(to);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** ISO string → epoch ms; anything unparsable falls back to now. */
|
|
62
|
+
export function epoch(iso: unknown): number {
|
|
63
|
+
return typeof iso === 'string' && Date.parse(iso) ? Date.parse(iso) : Date.now();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function defaultDb(c: RequestContext): CrudDb {
|
|
67
|
+
return drizzle(neon(c.env.DATABASE_URL));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function docStore(spec: DocStoreSpec) {
|
|
71
|
+
const byKey = new Map(spec.collections.map((col) => [col.key, col]));
|
|
72
|
+
const getDb = spec.db ?? defaultDb;
|
|
73
|
+
const maxBatch = spec.maxBatch ?? 2000;
|
|
74
|
+
|
|
75
|
+
function collectionOf(key: string): DocCollectionSpec | undefined {
|
|
76
|
+
return byKey.get(key);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function requireSpec(key: string): DocCollectionSpec {
|
|
80
|
+
const col = byKey.get(key);
|
|
81
|
+
if (!col) throw new UnknownCollectionError(`Unknown collection '${key}'`);
|
|
82
|
+
return col;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function rowValues(col: DocCollectionSpec, doc: Doc, nowMs: number): Record<string, unknown> {
|
|
86
|
+
const id = String(doc.id);
|
|
87
|
+
return {
|
|
88
|
+
id,
|
|
89
|
+
createdAt: epoch(doc.createdAt) || nowMs,
|
|
90
|
+
updatedAt: epoch(doc.updatedAt) || nowMs,
|
|
91
|
+
deletedAt: null as number | null,
|
|
92
|
+
data: doc,
|
|
93
|
+
...col.columns?.(doc),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function putDoc(db: CrudDb, key: string, doc: Doc): Promise<void> {
|
|
98
|
+
const col = requireSpec(key);
|
|
99
|
+
if (col.singletonId && String(doc.id) !== col.singletonId) {
|
|
100
|
+
throw new WorkflowError(`Singleton collection '${key}' must use id '${col.singletonId}'`);
|
|
101
|
+
}
|
|
102
|
+
const guard = col.transitions;
|
|
103
|
+
if (guard) {
|
|
104
|
+
const [existing] = await db
|
|
105
|
+
.select({ data: col.table.data })
|
|
106
|
+
.from(col.table)
|
|
107
|
+
.where(and(eq(col.table.id, String(doc.id)), isNull(col.table.deletedAt)))
|
|
108
|
+
.limit(1);
|
|
109
|
+
if (existing) {
|
|
110
|
+
const from = (existing.data as Doc).status;
|
|
111
|
+
const to = doc.status;
|
|
112
|
+
if (typeof from === 'string' && typeof to === 'string' && !canTransition(guard, from, to)) {
|
|
113
|
+
throw new WorkflowError(`Invalid ${key} transition ${from} → ${to}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const values = rowValues(col, doc, Date.now());
|
|
118
|
+
await db
|
|
119
|
+
.insert(col.table)
|
|
120
|
+
.values(values as never)
|
|
121
|
+
.onConflictDoUpdate({
|
|
122
|
+
target: [col.table.id],
|
|
123
|
+
set: { updatedAt: values.updatedAt, deletedAt: null, data: values.data } as never,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function patchDoc(db: CrudDb, key: string, id: string, patch: Doc): Promise<Doc | undefined> {
|
|
128
|
+
requireSpec(key);
|
|
129
|
+
const col = byKey.get(key)!;
|
|
130
|
+
const [row] = await db
|
|
131
|
+
.select()
|
|
132
|
+
.from(col.table)
|
|
133
|
+
.where(and(eq(col.table.id, id), isNull(col.table.deletedAt)))
|
|
134
|
+
.limit(1);
|
|
135
|
+
const merged: Doc = row ? { ...(row.data as Doc), ...patch, id } : { ...patch, id };
|
|
136
|
+
merged.updatedAt = new Date().toISOString();
|
|
137
|
+
await putDoc(db, key, merged);
|
|
138
|
+
return merged;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function softDeleteDoc(db: CrudDb, key: string, id: string): Promise<boolean> {
|
|
142
|
+
const col = requireSpec(key);
|
|
143
|
+
const res = await db
|
|
144
|
+
.update(col.table)
|
|
145
|
+
.set({ deletedAt: Date.now() } as never)
|
|
146
|
+
.where(eq(col.table.id, id))
|
|
147
|
+
.returning({ id: col.table.id });
|
|
148
|
+
return res.length > 0;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function listDocs(db: CrudDb, key: string): Promise<Doc[]> {
|
|
152
|
+
const col = requireSpec(key);
|
|
153
|
+
const rows = await db
|
|
154
|
+
.select({ data: col.table.data })
|
|
155
|
+
.from(col.table)
|
|
156
|
+
.where(isNull(col.table.deletedAt))
|
|
157
|
+
.orderBy(col.table.id);
|
|
158
|
+
return rows.map((r) => r.data as Doc);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function getDoc(db: CrudDb, key: string, id: string): Promise<Doc | undefined> {
|
|
162
|
+
const col = requireSpec(key);
|
|
163
|
+
const [row] = await db
|
|
164
|
+
.select({ data: col.table.data })
|
|
165
|
+
.from(col.table)
|
|
166
|
+
.where(and(eq(col.table.id, id), isNull(col.table.deletedAt)))
|
|
167
|
+
.limit(1);
|
|
168
|
+
return row?.data as Doc | undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const docSchema = z.object({ id: z.string().min(1) }).passthrough();
|
|
172
|
+
const patchSchema = z.record(z.string(), z.unknown()).refine((r) => Object.keys(r).length > 0, 'Empty patch');
|
|
173
|
+
const batchSchema = z.object({
|
|
174
|
+
ops: z
|
|
175
|
+
.array(
|
|
176
|
+
z.discriminatedUnion('op', [
|
|
177
|
+
z.object({ op: z.literal('put'), collection: z.string(), doc: docSchema }),
|
|
178
|
+
z.object({ op: z.literal('del'), collection: z.string(), id: z.string().min(1) }),
|
|
179
|
+
]),
|
|
180
|
+
)
|
|
181
|
+
.min(1)
|
|
182
|
+
.max(maxBatch),
|
|
183
|
+
}).strict();
|
|
184
|
+
|
|
185
|
+
const router = new Hono<{ Bindings: ApiEnv }>();
|
|
186
|
+
|
|
187
|
+
router.get('/:collection', async (c) => {
|
|
188
|
+
try {
|
|
189
|
+
requireSpec(c.req.param('collection'));
|
|
190
|
+
} catch {
|
|
191
|
+
return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
|
|
192
|
+
}
|
|
193
|
+
return c.json(await listDocs(getDb(c), c.req.param('collection')));
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
router.get('/:collection/:id', async (c) => {
|
|
197
|
+
try {
|
|
198
|
+
requireSpec(c.req.param('collection'));
|
|
199
|
+
} catch {
|
|
200
|
+
return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
|
|
201
|
+
}
|
|
202
|
+
const doc = await getDoc(getDb(c), c.req.param('collection'), c.req.param('id'));
|
|
203
|
+
return doc ? c.json(doc) : c.json({ error: 'Document not found' }, 404);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
router.put('/:collection/:id', validator('json', validateJson(docSchema, 'Invalid document payload')), async (c) => {
|
|
207
|
+
const key = c.req.param('collection');
|
|
208
|
+
try {
|
|
209
|
+
requireSpec(key);
|
|
210
|
+
} catch {
|
|
211
|
+
return c.json({ error: 'Unknown collection', collection: key }, 404);
|
|
212
|
+
}
|
|
213
|
+
const doc = c.req.valid('json') as unknown as Doc;
|
|
214
|
+
if (doc.id !== c.req.param('id')) {
|
|
215
|
+
return c.json({ error: 'Body id does not match the URL' }, 400);
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
await putDoc(getDb(c), key, doc);
|
|
219
|
+
} catch (err) {
|
|
220
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
|
|
221
|
+
throw err;
|
|
222
|
+
}
|
|
223
|
+
return c.json(doc, 201);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
router.patch('/:collection/:id', validator('json', validateJson(patchSchema, 'Invalid patch payload')), async (c) => {
|
|
227
|
+
const key = c.req.param('collection');
|
|
228
|
+
try {
|
|
229
|
+
requireSpec(key);
|
|
230
|
+
} catch {
|
|
231
|
+
return c.json({ error: 'Unknown collection', collection: key }, 404);
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
const merged = await patchDoc(getDb(c), key, c.req.param('id'), c.req.valid('json') as unknown as Doc);
|
|
235
|
+
return c.json(merged ?? {});
|
|
236
|
+
} catch (err) {
|
|
237
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
|
|
238
|
+
throw err;
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
router.delete('/:collection/:id', async (c) => {
|
|
243
|
+
try {
|
|
244
|
+
requireSpec(c.req.param('collection'));
|
|
245
|
+
} catch {
|
|
246
|
+
return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
|
|
247
|
+
}
|
|
248
|
+
const gone = await softDeleteDoc(getDb(c), c.req.param('collection'), c.req.param('id'));
|
|
249
|
+
return gone ? c.json({ ok: true }) : c.json({ error: 'Document not found' }, 404);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
router.post('/batch', validator('json', validateJson(batchSchema, 'Invalid batch payload')), async (c) => {
|
|
253
|
+
const applied: { collection: string; id: string }[] = [];
|
|
254
|
+
try {
|
|
255
|
+
for (const op of c.req.valid('json').ops) {
|
|
256
|
+
requireSpec(op.collection);
|
|
257
|
+
if (op.op === 'put') {
|
|
258
|
+
await putDoc(getDb(c), op.collection, op.doc as Doc);
|
|
259
|
+
applied.push({ collection: op.collection, id: String(op.doc.id) });
|
|
260
|
+
} else {
|
|
261
|
+
await softDeleteDoc(getDb(c), op.collection, op.id);
|
|
262
|
+
applied.push({ collection: op.collection, id: op.id });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
} catch (err) {
|
|
266
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message, applied: applied.length }, 400);
|
|
267
|
+
if (err instanceof UnknownCollectionError) return c.json({ error: err.message, applied: applied.length }, 404);
|
|
268
|
+
throw err;
|
|
269
|
+
}
|
|
270
|
+
return c.json({ ok: true, applied: applied.length });
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
return {
|
|
274
|
+
router,
|
|
275
|
+
collectionOf,
|
|
276
|
+
putDoc,
|
|
277
|
+
patchDoc,
|
|
278
|
+
softDeleteDoc,
|
|
279
|
+
listDocs,
|
|
280
|
+
getDoc,
|
|
281
|
+
};
|
|
282
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* and SPA-fallback handlers, and the ApiEnv binding types.
|
|
12
12
|
*
|
|
13
13
|
* Entry points:
|
|
14
|
-
* `.` server core (this file)
|
|
14
|
+
* `.` server core (this file) — includes docStore (jsonb doc factories)
|
|
15
15
|
* `/types` Row/NewRow/Serialized/ClientRow — the schema→client type bridge
|
|
16
16
|
* `/validator` validateJson — the zod `{ error, details }` body contract
|
|
17
17
|
* `/client` apiFetch / apiWrite — the same-origin API client
|
|
@@ -25,6 +25,8 @@ export { healthRouter } from './health';
|
|
|
25
25
|
export { ApiError, apiOnError } from './errors';
|
|
26
26
|
export { crudRoutes, listRoutes } from './crud';
|
|
27
27
|
export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec } from './crud';
|
|
28
|
+
export { docStore, canTransition, epoch, WorkflowError, UnknownCollectionError } from './docstore';
|
|
29
|
+
export type { Doc, DocTable, DocCollectionSpec, DocStoreSpec } from './docstore';
|
|
28
30
|
export { getDb } from './db';
|
|
29
31
|
export { uid, pickPatch, patchTypeErrors, normalizeRow, stampUpdate, trio, actor } from './lib';
|
|
30
32
|
export { resolveOrg, orgHasMode, nextNumber } from './org';
|