@umituz/web-hono 1.8.9 → 1.10.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 +1 -1
- package/package.json +1 -1
- package/src/activity.ts +27 -9
- package/src/api.ts +30 -0
- package/src/client.ts +19 -4
- package/src/docstore.ts +155 -41
- package/src/index.ts +2 -2
- package/src/store.ts +0 -0
- package/src/validator.ts +2 -0
package/README.md
CHANGED
|
@@ -153,7 +153,7 @@ const { status, error, retry } = useHydration();
|
|
|
153
153
|
const orders = useCollection('orders'); // typed, re-renders on its channel
|
|
154
154
|
```
|
|
155
155
|
|
|
156
|
-
The machine: first read hydrates every collection in
|
|
156
|
+
The machine: first read hydrates every collection through `GET /api/bootstrap` in small sequential batches (default 12 paths per request — the server replays its own list routes in-process and answers one bundle; collections emit progressively as their batch lands, so the database wakes once instead of once per collection; APIs predating the route answer 404 and hydration falls back to the 1.x parallel fan-out; `bootstrap: false` pins the legacy mode); repositories read synchronously via `getDb()` or `store.read(fn)`; writes go through `store.apiWrite(path, init, keys)` / `store.http.write` which refresh only the touched collections on success and leave the cache untouched on failure; per-collection pub/sub (plus the `__refetch_all__` wildcard) drives the hooks; `view(keys, selector)` gives change-detected derived reads.
|
|
157
157
|
|
|
158
158
|
**7. Lifecycle scripts** (`scripts/`) — keep only your `TABLE_SPECS` registry and thin wrappers:
|
|
159
159
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-hono",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.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/activity.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getTableColumns } from 'drizzle-orm';
|
|
1
|
+
import { eq, getTableColumns } from 'drizzle-orm';
|
|
2
2
|
import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
|
|
3
3
|
import { uid } from './lib';
|
|
4
4
|
import type { CrudDb } from './crud';
|
|
@@ -18,7 +18,7 @@ export interface AuditWrite {
|
|
|
18
18
|
|
|
19
19
|
export interface NotificationWrite {
|
|
20
20
|
type?: string;
|
|
21
|
-
severity
|
|
21
|
+
severity?: string;
|
|
22
22
|
title: string;
|
|
23
23
|
body: string;
|
|
24
24
|
entityType?: string;
|
|
@@ -26,14 +26,26 @@ export interface NotificationWrite {
|
|
|
26
26
|
[extra: string]: unknown;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
export interface NotificationOpts {
|
|
30
|
+
prefix?: string;
|
|
31
|
+
dedupe?: { column: PgColumn; value: unknown };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type ColumnMeta = { columnType?: string };
|
|
35
|
+
type Columns = Record<string, ColumnMeta>;
|
|
30
36
|
|
|
31
37
|
/** Stamps the first present time column — the fleet's `at` plain tables and
|
|
32
38
|
* the trio-convention (`createdAt`) tables are both served; tables with
|
|
33
|
-
* neither rely on their column defaults.
|
|
34
|
-
|
|
39
|
+
* neither rely on their column defaults. Text time columns receive the ISO
|
|
40
|
+
* string form, timestamp columns the Date object. */
|
|
41
|
+
function timeStamp(table: ActivityTable, candidates: string[]): Record<string, Date | string> {
|
|
35
42
|
const columns = getTableColumns(table) as unknown as Columns;
|
|
36
|
-
for (const name of candidates)
|
|
43
|
+
for (const name of candidates) {
|
|
44
|
+
const meta = columns[name];
|
|
45
|
+
if (!meta) continue;
|
|
46
|
+
const kind = meta.columnType ?? '';
|
|
47
|
+
return { [name]: kind.includes('Text') || kind.includes('Varchar') ? new Date().toISOString() : new Date() };
|
|
48
|
+
}
|
|
37
49
|
return {};
|
|
38
50
|
}
|
|
39
51
|
|
|
@@ -50,7 +62,13 @@ export async function writeNotification(
|
|
|
50
62
|
db: CrudDb,
|
|
51
63
|
table: ActivityTable,
|
|
52
64
|
n: NotificationWrite,
|
|
53
|
-
|
|
54
|
-
): Promise<
|
|
55
|
-
|
|
65
|
+
opts: string | NotificationOpts = {},
|
|
66
|
+
): Promise<boolean> {
|
|
67
|
+
const o = typeof opts === 'string' ? { prefix: opts } : opts;
|
|
68
|
+
if (o.dedupe) {
|
|
69
|
+
const [dupe] = await db.select({ id: table.id }).from(table).where(eq(o.dedupe.column, o.dedupe.value)).limit(1);
|
|
70
|
+
if (dupe) return false;
|
|
71
|
+
}
|
|
72
|
+
await db.insert(table).values({ id: uid(o.prefix ?? 'ntf'), ...timeStamp(table, ['at', 'createdAt']), ...boolStamp(table, 'read', false), ...n } as never);
|
|
73
|
+
return true;
|
|
56
74
|
}
|
package/src/api.ts
CHANGED
|
@@ -34,6 +34,11 @@ export interface ApiConfig<E extends ApiEnv = ApiEnv> {
|
|
|
34
34
|
middleware?: ReadonlyArray<MiddlewareHandler<{ Bindings: E }>>;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/** Cap on replayed paths per bootstrap call — keeps one Worker request
|
|
38
|
+
* inside the free-tier subrequest budget even when a replayed route runs
|
|
39
|
+
* a couple of queries of its own. */
|
|
40
|
+
const BOOTSTRAP_MAX_PATHS = 40;
|
|
41
|
+
|
|
37
42
|
export function createApi<E extends ApiEnv = ApiEnv>(config: ApiConfig<E>): Hono<{ Bindings: E }> {
|
|
38
43
|
const api = new Hono<{ Bindings: E }>();
|
|
39
44
|
|
|
@@ -46,6 +51,31 @@ export function createApi<E extends ApiEnv = ApiEnv>(config: ApiConfig<E>): Hono
|
|
|
46
51
|
// Widening ApiEnv→E is safe at runtime (c.env: E ⊇ ApiEnv); hono's Context
|
|
47
52
|
// invariance just refuses the direct cast.
|
|
48
53
|
app.onError(apiOnError as unknown as ErrorHandler<{ Bindings: E }>);
|
|
54
|
+
|
|
55
|
+
// GET /api/bootstrap?paths=/api/a,/api/b — replays the app's own list
|
|
56
|
+
// routes in-process (no network) and bundles their JSON bodies under one
|
|
57
|
+
// response, so a hydrating client pays one round trip per chunk instead
|
|
58
|
+
// of one per collection. Only /api paths are replayed; anything else the
|
|
59
|
+
// router would have answered stays answerable only the normal way.
|
|
60
|
+
app.get('/api/bootstrap', async (c) => {
|
|
61
|
+
const raw = c.req.query('paths') ?? '';
|
|
62
|
+
const paths = [...new Set(raw.split(',').map((p) => p.trim()).filter((p) => p.startsWith('/api/') && p !== '/api/bootstrap'))]
|
|
63
|
+
.slice(0, BOOTSTRAP_MAX_PATHS);
|
|
64
|
+
const results: Record<string, { status: number; body?: unknown }> = {};
|
|
65
|
+
await Promise.all(
|
|
66
|
+
paths.map(async (p) => {
|
|
67
|
+
const res = await app.request(p, { headers: c.req.raw.headers }, c.env);
|
|
68
|
+
if (res.status !== 200) {
|
|
69
|
+
results[p] = { status: res.status };
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const body = await res.json().catch(() => undefined);
|
|
73
|
+
results[p] = body === undefined ? { status: res.status } : { status: res.status, body };
|
|
74
|
+
}),
|
|
75
|
+
);
|
|
76
|
+
return c.json({ results });
|
|
77
|
+
});
|
|
78
|
+
|
|
49
79
|
app.all('/api/*', apiNotFound);
|
|
50
80
|
app.get('*', spaFallback);
|
|
51
81
|
return app;
|
package/src/client.ts
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
export class ApiClientError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
readonly body: unknown;
|
|
4
|
+
readonly details?: unknown;
|
|
5
|
+
readonly conflicts?: unknown;
|
|
6
|
+
|
|
7
|
+
constructor(message: string, status: number, body: unknown) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'ApiClientError';
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.body = body;
|
|
12
|
+
if (body && typeof body === 'object') {
|
|
13
|
+
const rec = body as Record<string, unknown>;
|
|
14
|
+
if ('details' in rec) this.details = rec.details;
|
|
15
|
+
if ('conflicts' in rec) this.conflicts = rec.conflicts;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
4
19
|
|
|
5
20
|
export async function apiFetch<T>(path: string, init: { method?: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; json?: unknown } = {}): Promise<T> {
|
|
6
21
|
const res = await fetch(path, {
|
|
@@ -10,7 +25,7 @@ export async function apiFetch<T>(path: string, init: { method?: 'POST' | 'PATCH
|
|
|
10
25
|
});
|
|
11
26
|
if (!res.ok) {
|
|
12
27
|
const body = (await res.json().catch(() => null)) as { error?: string } | null;
|
|
13
|
-
throw new
|
|
28
|
+
throw new ApiClientError(body?.error ?? `API ${path} responded ${res.status}`, res.status, body);
|
|
14
29
|
}
|
|
15
30
|
// Void endpoints (204 / empty body) resolve to undefined — res.json()
|
|
16
31
|
// would throw a SyntaxError on the empty stream.
|
package/src/docstore.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
-
import { and, eq, isNull, sql } from 'drizzle-orm';
|
|
2
|
+
import { and, eq, getTableColumns, isNull, sql } from 'drizzle-orm';
|
|
3
3
|
import { drizzle } from 'drizzle-orm/neon-http';
|
|
4
4
|
import { neon } from '@neondatabase/serverless';
|
|
5
5
|
import { validator } from 'hono/validator';
|
|
@@ -27,9 +27,15 @@ import type { ApiEnv } from './env';
|
|
|
27
27
|
type RequestContext = Context<{ Bindings: ApiEnv }>;
|
|
28
28
|
|
|
29
29
|
export type Doc = Record<string, unknown> & { id: string };
|
|
30
|
+
export type DocInput = Record<string, unknown>;
|
|
30
31
|
|
|
31
32
|
export type DocTable = PgTable & { id: PgColumn; data: PgColumn; deletedAt: PgColumn };
|
|
32
33
|
|
|
34
|
+
export interface DocScopeSpec {
|
|
35
|
+
column: PgColumn;
|
|
36
|
+
field: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
33
39
|
/**
|
|
34
40
|
* Cross-cutting write guard: runs inside putDoc before the write, covering
|
|
35
41
|
* every path that funnels through it (PUT, PATCH-merged, batch puts,
|
|
@@ -38,14 +44,16 @@ export type DocTable = PgTable & { id: PgColumn; data: PgColumn; deletedAt: PgCo
|
|
|
38
44
|
* (booking-conflict style rules). Throw WorkflowError (or ApiError) to
|
|
39
45
|
* reject the write.
|
|
40
46
|
*/
|
|
41
|
-
export type DocValidateFn = (args: { db: CrudDb; doc:
|
|
47
|
+
export type DocValidateFn = (args: { db: CrudDb; doc: DocInput; existing?: DocInput }) => void | Promise<void>;
|
|
48
|
+
|
|
49
|
+
export type DocAfterWriteFn = (args: { db: CrudDb; key: string; id: string; doc: Doc; op: 'put' | 'delete' }) => void | Promise<void>;
|
|
42
50
|
|
|
43
51
|
export interface DocCollectionSpec {
|
|
44
52
|
/** Wire collection name — the URL segment and the batch op key. */
|
|
45
53
|
key: string;
|
|
46
54
|
table: DocTable;
|
|
47
55
|
/** Extra typed columns derived from the doc (users: email/name/flags). */
|
|
48
|
-
columns?: (doc:
|
|
56
|
+
columns?: (doc: DocInput) => Record<string, unknown>;
|
|
49
57
|
/** Collections that must always write the one fixed id. */
|
|
50
58
|
singletonId?: string;
|
|
51
59
|
/** Status state machine: allowed targets per current status. */
|
|
@@ -54,6 +62,9 @@ export interface DocCollectionSpec {
|
|
|
54
62
|
statusKey?: string;
|
|
55
63
|
/** Write guard — see DocValidateFn. */
|
|
56
64
|
validate?: DocValidateFn;
|
|
65
|
+
idField?: string;
|
|
66
|
+
scope?: DocScopeSpec;
|
|
67
|
+
afterWrite?: DocAfterWriteFn;
|
|
57
68
|
}
|
|
58
69
|
|
|
59
70
|
export interface DocStoreSpec {
|
|
@@ -96,9 +107,47 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
96
107
|
return col;
|
|
97
108
|
}
|
|
98
109
|
|
|
99
|
-
function
|
|
100
|
-
|
|
101
|
-
|
|
110
|
+
function idFieldOf(col: DocCollectionSpec): string {
|
|
111
|
+
return col.idField ?? 'id';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function docIdOf(col: DocCollectionSpec, doc: DocInput): string {
|
|
115
|
+
const value = doc[idFieldOf(col)];
|
|
116
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
117
|
+
throw new WorkflowError(`Document must carry a non-empty '${idFieldOf(col)}'`);
|
|
118
|
+
}
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function scopePropOf(col: DocCollectionSpec): string {
|
|
123
|
+
if (!col.scope) throw new WorkflowError('Collection is not scoped');
|
|
124
|
+
const columns = getTableColumns(col.table) as unknown as Record<string, PgColumn>;
|
|
125
|
+
const prop = Object.keys(columns).find((k) => columns[k] === col.scope!.column);
|
|
126
|
+
if (!prop) throw new UnknownCollectionError('Scope column not found on the collection table');
|
|
127
|
+
return prop;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function scopeValueOf(col: DocCollectionSpec, doc: DocInput): string {
|
|
131
|
+
const value = col.scope ? doc[col.scope.field] : undefined;
|
|
132
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
133
|
+
throw new WorkflowError(`Document must carry a non-empty '${col.scope?.field}'`);
|
|
134
|
+
}
|
|
135
|
+
return value;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function idConds(col: DocCollectionSpec, id: string, scope: string | undefined, live: boolean) {
|
|
139
|
+
const conds = [eq(col.table.id, id)];
|
|
140
|
+
if (col.scope) {
|
|
141
|
+
if (!scope) throw new WorkflowError(`Scoped collection '${col.key}' requires a scope value`);
|
|
142
|
+
conds.push(eq(col.scope.column, scope));
|
|
143
|
+
}
|
|
144
|
+
if (live) conds.push(isNull(col.table.deletedAt));
|
|
145
|
+
return and(...conds);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function rowValues(col: DocCollectionSpec, doc: DocInput, nowMs: number): Record<string, unknown> {
|
|
149
|
+
const id = docIdOf(col, doc);
|
|
150
|
+
const values: Record<string, unknown> = {
|
|
102
151
|
id,
|
|
103
152
|
createdAt: epoch(doc.createdAt) || nowMs,
|
|
104
153
|
updatedAt: epoch(doc.updatedAt) || nowMs,
|
|
@@ -106,11 +155,14 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
106
155
|
data: doc,
|
|
107
156
|
...col.columns?.(doc),
|
|
108
157
|
};
|
|
158
|
+
if (col.scope) values[scopePropOf(col)] = scopeValueOf(col, doc);
|
|
159
|
+
return values;
|
|
109
160
|
}
|
|
110
161
|
|
|
111
|
-
async function putDoc(db: CrudDb, key: string, doc:
|
|
162
|
+
async function putDoc(db: CrudDb, key: string, doc: DocInput): Promise<void> {
|
|
112
163
|
const col = requireSpec(key);
|
|
113
|
-
|
|
164
|
+
const id = docIdOf(col, doc);
|
|
165
|
+
if (col.singletonId && id !== col.singletonId) {
|
|
114
166
|
throw new WorkflowError(`Singleton collection '${key}' must use id '${col.singletonId}'`);
|
|
115
167
|
}
|
|
116
168
|
const guard = col.transitions;
|
|
@@ -118,9 +170,9 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
118
170
|
const [existingRow] = await db
|
|
119
171
|
.select({ data: col.table.data })
|
|
120
172
|
.from(col.table)
|
|
121
|
-
.where(
|
|
173
|
+
.where(idConds(col, id, col.scope ? scopeValueOf(col, doc) : undefined, true))
|
|
122
174
|
.limit(1);
|
|
123
|
-
const existing = existingRow?.data as
|
|
175
|
+
const existing = existingRow?.data as DocInput | undefined;
|
|
124
176
|
if (guard) {
|
|
125
177
|
const statusKey = col.statusKey ?? 'status';
|
|
126
178
|
if (existing) {
|
|
@@ -138,15 +190,16 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
138
190
|
.insert(col.table)
|
|
139
191
|
.values(values as never)
|
|
140
192
|
.onConflictDoUpdate({
|
|
141
|
-
target: [col.table.id],
|
|
193
|
+
target: col.scope ? [col.scope.column, col.table.id] : [col.table.id],
|
|
142
194
|
set: { updatedAt: values.updatedAt, deletedAt: null, data: values.data } as never,
|
|
143
195
|
});
|
|
196
|
+
if (col.afterWrite) await col.afterWrite({ db, key, id, doc: doc as Doc, op: 'put' });
|
|
144
197
|
}
|
|
145
198
|
|
|
146
199
|
/** Trusted bulk load for seed scripts: chunked multi-row upsert with the
|
|
147
200
|
* same revive semantics as putDoc, without per-row workflow/singleton
|
|
148
201
|
* guards (seeds write fresh, consistent datasets by construction). */
|
|
149
|
-
async function putDocs(db: CrudDb, key: string, docs: readonly
|
|
202
|
+
async function putDocs(db: CrudDb, key: string, docs: readonly DocInput[], chunkSize = 200): Promise<number> {
|
|
150
203
|
const col = requireSpec(key);
|
|
151
204
|
let count = 0;
|
|
152
205
|
for (let i = 0; i < docs.length; i += chunkSize) {
|
|
@@ -155,7 +208,7 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
155
208
|
.insert(col.table)
|
|
156
209
|
.values(chunk as never)
|
|
157
210
|
.onConflictDoUpdate({
|
|
158
|
-
target: [col.table.id],
|
|
211
|
+
target: col.scope ? [col.scope.column, col.table.id] : [col.table.id],
|
|
159
212
|
set: { updatedAt: sql`excluded.updated_at`, deletedAt: null, data: sql`excluded.data` } as never,
|
|
160
213
|
});
|
|
161
214
|
count += chunk.length;
|
|
@@ -163,64 +216,86 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
163
216
|
return count;
|
|
164
217
|
}
|
|
165
218
|
|
|
166
|
-
async function patchDoc(db: CrudDb, key: string, id: string, patch:
|
|
167
|
-
requireSpec(key);
|
|
168
|
-
const col = byKey.get(key)!;
|
|
219
|
+
async function patchDoc(db: CrudDb, key: string, id: string, patch: DocInput, scope?: string): Promise<Doc | undefined> {
|
|
220
|
+
const col = requireSpec(key);
|
|
169
221
|
const [row] = await db
|
|
170
222
|
.select()
|
|
171
223
|
.from(col.table)
|
|
172
|
-
.where(
|
|
224
|
+
.where(idConds(col, id, scope, true))
|
|
173
225
|
.limit(1);
|
|
174
|
-
const
|
|
226
|
+
const fld = idFieldOf(col);
|
|
227
|
+
const merged: DocInput = row ? { ...(row.data as DocInput), ...patch, [fld]: id } : { ...patch, [fld]: id };
|
|
228
|
+
if (col.scope && scope) merged[col.scope.field] = scope;
|
|
175
229
|
merged.updatedAt = new Date().toISOString();
|
|
176
230
|
await putDoc(db, key, merged);
|
|
177
|
-
return merged;
|
|
231
|
+
return merged as Doc;
|
|
178
232
|
}
|
|
179
233
|
|
|
180
|
-
async function softDeleteDoc(db: CrudDb, key: string, id: string): Promise<boolean> {
|
|
234
|
+
async function softDeleteDoc(db: CrudDb, key: string, id: string, scope?: string): Promise<boolean> {
|
|
181
235
|
const col = requireSpec(key);
|
|
236
|
+
let before: DocInput | undefined;
|
|
237
|
+
if (col.afterWrite) {
|
|
238
|
+
const [row] = await db
|
|
239
|
+
.select({ data: col.table.data })
|
|
240
|
+
.from(col.table)
|
|
241
|
+
.where(idConds(col, id, scope, true))
|
|
242
|
+
.limit(1);
|
|
243
|
+
before = row?.data as DocInput | undefined;
|
|
244
|
+
}
|
|
182
245
|
const res = await db
|
|
183
246
|
.update(col.table)
|
|
184
247
|
.set({ deletedAt: Date.now() } as never)
|
|
185
|
-
.where(
|
|
248
|
+
.where(idConds(col, id, scope, false))
|
|
186
249
|
.returning({ id: col.table.id });
|
|
250
|
+
if (res.length > 0 && col.afterWrite && before) {
|
|
251
|
+
await col.afterWrite({ db, key, id, doc: before as Doc, op: 'delete' });
|
|
252
|
+
}
|
|
187
253
|
return res.length > 0;
|
|
188
254
|
}
|
|
189
255
|
|
|
190
|
-
async function listDocs(db: CrudDb, key: string): Promise<Doc[]> {
|
|
256
|
+
async function listDocs(db: CrudDb, key: string, scope?: string): Promise<Doc[]> {
|
|
191
257
|
const col = requireSpec(key);
|
|
258
|
+
const conds = [isNull(col.table.deletedAt)];
|
|
259
|
+
if (col.scope && scope !== undefined) conds.push(eq(col.scope.column, scope));
|
|
192
260
|
const rows = await db
|
|
193
261
|
.select({ data: col.table.data })
|
|
194
262
|
.from(col.table)
|
|
195
|
-
.where(
|
|
263
|
+
.where(and(...conds))
|
|
196
264
|
.orderBy(col.table.id);
|
|
197
265
|
return rows.map((r) => r.data as Doc);
|
|
198
266
|
}
|
|
199
267
|
|
|
200
|
-
async function getDoc(db: CrudDb, key: string, id: string): Promise<Doc | undefined> {
|
|
268
|
+
async function getDoc(db: CrudDb, key: string, id: string, scope?: string): Promise<Doc | undefined> {
|
|
201
269
|
const col = requireSpec(key);
|
|
202
270
|
const [row] = await db
|
|
203
271
|
.select({ data: col.table.data })
|
|
204
272
|
.from(col.table)
|
|
205
|
-
.where(
|
|
273
|
+
.where(idConds(col, id, scope, true))
|
|
206
274
|
.limit(1);
|
|
207
275
|
return row?.data as Doc | undefined;
|
|
208
276
|
}
|
|
209
277
|
|
|
210
|
-
const docSchema = z.
|
|
278
|
+
const docSchema = z.record(z.string(), z.unknown());
|
|
211
279
|
const patchSchema = z.record(z.string(), z.unknown()).refine((r) => Object.keys(r).length > 0, 'Empty patch');
|
|
212
280
|
const batchSchema = z.object({
|
|
213
281
|
ops: z
|
|
214
282
|
.array(
|
|
215
283
|
z.discriminatedUnion('op', [
|
|
216
284
|
z.object({ op: z.literal('put'), collection: z.string(), doc: docSchema }),
|
|
217
|
-
z.object({ op: z.literal('del'), collection: z.string(), id: z.string().min(1) }),
|
|
285
|
+
z.object({ op: z.literal('del'), collection: z.string(), id: z.string().min(1), scope: z.string().min(1).optional() }),
|
|
218
286
|
]),
|
|
219
287
|
)
|
|
220
288
|
.min(1)
|
|
221
289
|
.max(maxBatch),
|
|
222
290
|
}).strict();
|
|
223
291
|
|
|
292
|
+
function requireScopeQuery(c: RequestContext, col: DocCollectionSpec): string | undefined {
|
|
293
|
+
if (!col.scope) return undefined;
|
|
294
|
+
const q = c.req.query('scope');
|
|
295
|
+
if (!q) throw new WorkflowError(`Scoped collection '${col.key}' requires a scope query`);
|
|
296
|
+
return q;
|
|
297
|
+
}
|
|
298
|
+
|
|
224
299
|
const router = new Hono<{ Bindings: ApiEnv }>();
|
|
225
300
|
|
|
226
301
|
router.get('/:collection', async (c) => {
|
|
@@ -229,30 +304,48 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
229
304
|
} catch {
|
|
230
305
|
return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
|
|
231
306
|
}
|
|
232
|
-
return c.json(await listDocs(getDb(c), c.req.param('collection')));
|
|
307
|
+
return c.json(await listDocs(getDb(c), c.req.param('collection'), c.req.query('scope')));
|
|
233
308
|
});
|
|
234
309
|
|
|
235
310
|
router.get('/:collection/:id', async (c) => {
|
|
311
|
+
let col: DocCollectionSpec;
|
|
236
312
|
try {
|
|
237
|
-
requireSpec(c.req.param('collection'));
|
|
313
|
+
col = requireSpec(c.req.param('collection'));
|
|
238
314
|
} catch {
|
|
239
315
|
return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
|
|
240
316
|
}
|
|
241
|
-
|
|
317
|
+
let scope: string | undefined;
|
|
318
|
+
try {
|
|
319
|
+
scope = requireScopeQuery(c, col);
|
|
320
|
+
} catch (err) {
|
|
321
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
|
|
322
|
+
throw err;
|
|
323
|
+
}
|
|
324
|
+
const doc = await getDoc(getDb(c), col.key, c.req.param('id'), scope);
|
|
242
325
|
return doc ? c.json(doc) : c.json({ error: 'Document not found' }, 404);
|
|
243
326
|
});
|
|
244
327
|
|
|
245
328
|
router.put('/:collection/:id', validator('json', validateJson(docSchema, 'Invalid document payload')), async (c) => {
|
|
246
329
|
const key = c.req.param('collection');
|
|
330
|
+
let col: DocCollectionSpec;
|
|
247
331
|
try {
|
|
248
|
-
requireSpec(key);
|
|
332
|
+
col = requireSpec(key);
|
|
249
333
|
} catch {
|
|
250
334
|
return c.json({ error: 'Unknown collection', collection: key }, 404);
|
|
251
335
|
}
|
|
252
|
-
const doc = c.req.valid('json') as unknown as
|
|
253
|
-
|
|
336
|
+
const doc = c.req.valid('json') as unknown as DocInput;
|
|
337
|
+
const fld = idFieldOf(col);
|
|
338
|
+
if (typeof doc[fld] !== 'string' || (doc[fld] as string).length === 0) {
|
|
339
|
+
return c.json({ error: 'Invalid document payload', details: { [fld]: ['Required'] } }, 400);
|
|
340
|
+
}
|
|
341
|
+
if (doc[fld] !== c.req.param('id')) {
|
|
254
342
|
return c.json({ error: 'Body id does not match the URL' }, 400);
|
|
255
343
|
}
|
|
344
|
+
if (col.scope && typeof doc[col.scope.field] !== 'string') {
|
|
345
|
+
const q = c.req.query('scope');
|
|
346
|
+
if (!q) return c.json({ error: `Scoped collection '${key}' requires a scope query` }, 400);
|
|
347
|
+
doc[col.scope.field] = q;
|
|
348
|
+
}
|
|
256
349
|
try {
|
|
257
350
|
await putDoc(getDb(c), key, doc);
|
|
258
351
|
} catch (err) {
|
|
@@ -264,13 +357,21 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
264
357
|
|
|
265
358
|
router.patch('/:collection/:id', validator('json', validateJson(patchSchema, 'Invalid patch payload')), async (c) => {
|
|
266
359
|
const key = c.req.param('collection');
|
|
360
|
+
let col: DocCollectionSpec;
|
|
267
361
|
try {
|
|
268
|
-
requireSpec(key);
|
|
362
|
+
col = requireSpec(key);
|
|
269
363
|
} catch {
|
|
270
364
|
return c.json({ error: 'Unknown collection', collection: key }, 404);
|
|
271
365
|
}
|
|
366
|
+
let scope: string | undefined;
|
|
367
|
+
try {
|
|
368
|
+
scope = requireScopeQuery(c, col);
|
|
369
|
+
} catch (err) {
|
|
370
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
|
|
371
|
+
throw err;
|
|
372
|
+
}
|
|
272
373
|
try {
|
|
273
|
-
const merged = await patchDoc(getDb(c), key, c.req.param('id'), c.req.valid('json') as unknown as
|
|
374
|
+
const merged = await patchDoc(getDb(c), key, c.req.param('id'), c.req.valid('json') as unknown as DocInput, scope);
|
|
274
375
|
return c.json(merged ?? {});
|
|
275
376
|
} catch (err) {
|
|
276
377
|
if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
|
|
@@ -279,13 +380,26 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
279
380
|
});
|
|
280
381
|
|
|
281
382
|
router.delete('/:collection/:id', async (c) => {
|
|
383
|
+
let col: DocCollectionSpec;
|
|
282
384
|
try {
|
|
283
|
-
requireSpec(c.req.param('collection'));
|
|
385
|
+
col = requireSpec(c.req.param('collection'));
|
|
284
386
|
} catch {
|
|
285
387
|
return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
|
|
286
388
|
}
|
|
287
|
-
|
|
288
|
-
|
|
389
|
+
let scope: string | undefined;
|
|
390
|
+
try {
|
|
391
|
+
scope = requireScopeQuery(c, col);
|
|
392
|
+
} catch (err) {
|
|
393
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
|
|
394
|
+
throw err;
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
const gone = await softDeleteDoc(getDb(c), col.key, c.req.param('id'), scope);
|
|
398
|
+
return gone ? c.json({ ok: true }) : c.json({ error: 'Document not found' }, 404);
|
|
399
|
+
} catch (err) {
|
|
400
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
|
|
401
|
+
throw err;
|
|
402
|
+
}
|
|
289
403
|
});
|
|
290
404
|
|
|
291
405
|
router.post('/batch', validator('json', validateJson(batchSchema, 'Invalid batch payload')), async (c) => {
|
|
@@ -294,10 +408,10 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
294
408
|
for (const op of c.req.valid('json').ops) {
|
|
295
409
|
requireSpec(op.collection);
|
|
296
410
|
if (op.op === 'put') {
|
|
297
|
-
await putDoc(getDb(c), op.collection, op.doc as
|
|
298
|
-
applied.push({ collection: op.collection, id:
|
|
411
|
+
await putDoc(getDb(c), op.collection, op.doc as DocInput);
|
|
412
|
+
applied.push({ collection: op.collection, id: docIdOf(requireSpec(op.collection), op.doc as DocInput) });
|
|
299
413
|
} else {
|
|
300
|
-
await softDeleteDoc(getDb(c), op.collection, op.id);
|
|
414
|
+
await softDeleteDoc(getDb(c), op.collection, op.id, op.scope);
|
|
301
415
|
applied.push({ collection: op.collection, id: op.id });
|
|
302
416
|
}
|
|
303
417
|
}
|
package/src/index.ts
CHANGED
|
@@ -27,7 +27,7 @@ export { ApiError, apiOnError, isUniqueViolation } from './errors';
|
|
|
27
27
|
export { crudRoutes, listRoutes } from './crud';
|
|
28
28
|
export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec } from './crud';
|
|
29
29
|
export { docStore, canTransition, epoch, WorkflowError, UnknownCollectionError } from './docstore';
|
|
30
|
-
export type { Doc, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn } from './docstore';
|
|
30
|
+
export type { Doc, DocInput, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn, DocAfterWriteFn, DocScopeSpec } from './docstore';
|
|
31
31
|
export { getDb } from './db';
|
|
32
32
|
export { uid, pickPatch, patchTypeErrors, normalizeRow, stampUpdate, trio, actor } from './lib';
|
|
33
33
|
export { isoNow, isoAt, todayISO, addDaysISO } from './dates';
|
|
@@ -35,7 +35,7 @@ export type { IsoPrecision } from './dates';
|
|
|
35
35
|
export { resolveOrg, orgHasMode, nextNumber } from './org';
|
|
36
36
|
export type { UsersLike, OrgsLike, NumberedTable } from './org';
|
|
37
37
|
export { writeAudit, writeNotification } from './activity';
|
|
38
|
-
export type { ActivityTable, AuditWrite, NotificationWrite } from './activity';
|
|
38
|
+
export type { ActivityTable, AuditWrite, NotificationWrite, NotificationOpts } from './activity';
|
|
39
39
|
export { findRow, softDelete } from './rows';
|
|
40
40
|
export type { AliveTable } from './rows';
|
|
41
41
|
export { apiNotFound, spaFallback } from './handlers';
|
package/src/store.ts
CHANGED
|
Binary file
|
package/src/validator.ts
CHANGED
|
@@ -26,6 +26,8 @@ export function validateJson<S extends z.ZodType>(schema: S, message = 'Invalid
|
|
|
26
26
|
|
|
27
27
|
export const dateOnly = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'expected YYYY-MM-DD');
|
|
28
28
|
|
|
29
|
+
export const dateOnlyCoerce = z.string().min(10).transform((v) => v.slice(0, 10)).pipe(dateOnly);
|
|
30
|
+
|
|
29
31
|
export const hhmm = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'expected HH:MM');
|
|
30
32
|
|
|
31
33
|
export const datetimeLocal = z.string().regex(/^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d$/, 'expected YYYY-MM-DDTHH:MM');
|