@umituz/web-hono 1.19.3 → 1.20.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.19.3",
3
+ "version": "1.20.1",
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), doc-sync diff/snapshot/push machine (snapshotDocs/diffOps/pushOps), better-auth server integration (tables/getter/mount/session helpers), weak-compare If-None-Match matcher (matchesEtag), cookie channels + request scope/ETag/R2-stream server helpers, TTL resource cache, and db lifecycle scripts (reset / snapshot / seed)",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
package/src/crud.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { Hono } from 'hono';
2
- import { and, asc, desc, eq, getTableColumns, isNull } from 'drizzle-orm';
2
+ import { and, asc, desc, eq, getTableColumns, inArray, isNull } from 'drizzle-orm';
3
3
  import { drizzle } from 'drizzle-orm/neon-http';
4
4
  import type { NeonHttpDatabase } from 'drizzle-orm/neon-http';
5
5
  import { neon } from '@neondatabase/serverless';
6
6
  import type { Context } from 'hono';
7
+ import type { SQL } from 'drizzle-orm';
7
8
  import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
8
9
  import { z } from 'zod';
9
10
  import { normalizeRow, patchTypeErrors, pickPatch, stampUpdate, uid } from './lib';
@@ -14,7 +15,6 @@ function defaultDb(c: RequestContext) {
14
15
  return drizzle(neon(c.env.DATABASE_URL));
15
16
  }
16
17
  export type CrudDb = Pick<NeonHttpDatabase<Record<string, never>>, 'select' | 'insert' | 'update'> & {
17
- /** Present on neon-http (production Workers); absent on some local drivers (pglite). */
18
18
  batch?: NeonHttpDatabase<Record<string, never>>['batch'];
19
19
  };
20
20
  export type CrudDbFactory = (c: RequestContext) => CrudDb;
@@ -27,6 +27,14 @@ export interface CreateSpec {
27
27
  schema: z.ZodType;
28
28
  prefix: string;
29
29
  defaults?: (c: RequestContext) => Record<string, unknown>;
30
+ pre?: (c: RequestContext, body: Record<string, unknown>) => Promise<Response | void>;
31
+ }
32
+
33
+ export interface OrgScopeSpec {
34
+ column?: PgColumn;
35
+ farmColumn?: PgColumn;
36
+ farms?: PgTable & { id: PgColumn; orgId: PgColumn };
37
+ resolve: (c: RequestContext) => Promise<string | null | undefined>;
30
38
  }
31
39
 
32
40
  export interface ListSpec {
@@ -34,6 +42,7 @@ export interface ListSpec {
34
42
  table: PgTable & { deletedAt: PgColumn };
35
43
  orderBy?: OrderSpec | ReadonlyArray<OrderSpec>;
36
44
  db?: CrudDbFactory;
45
+ orgScope?: OrgScopeSpec;
37
46
  }
38
47
 
39
48
  export interface CrudSpec extends ListSpec {
@@ -45,6 +54,28 @@ export interface CrudSpec extends ListSpec {
45
54
 
46
55
  const MAX_LIST_LIMIT = 500;
47
56
 
57
+ function assertOrgScope(scope: OrgScopeSpec): void {
58
+ if (scope.column && scope.farmColumn) throw new Error('orgScope: pass either column or farmColumn, not both');
59
+ if (!scope.column && !scope.farmColumn) throw new Error('orgScope: column or farmColumn is required');
60
+ if (scope.farmColumn && !scope.farms) throw new Error('orgScope: farms table is required with farmColumn');
61
+ }
62
+
63
+ function orgScopeCondition(scope: OrgScopeSpec, db: CrudDb, orgId: string): SQL {
64
+ if (scope.column) return eq(scope.column, orgId) as SQL;
65
+ const farms = scope.farms!;
66
+ return inArray(scope.farmColumn!, db.select({ id: farms.id }).from(farms).where(eq(farms.orgId, orgId))) as SQL;
67
+ }
68
+
69
+ async function resolveScopedOrg(spec: ListSpec, c: RequestContext): Promise<string | null | undefined> {
70
+ if (spec.orgScope) assertOrgScope(spec.orgScope);
71
+ return spec.orgScope?.resolve(c);
72
+ }
73
+
74
+ function orgColumnKey(spec: ListSpec, column: PgColumn): string | undefined {
75
+ const cols = getTableColumns(spec.table) as unknown as Record<string, PgColumn>;
76
+ return Object.keys(cols).find((k) => cols[k] === column);
77
+ }
78
+
48
79
  export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
49
80
  const { path, table, orderBy } = spec;
50
81
  const getDb = spec.db ?? defaultDb;
@@ -52,7 +83,13 @@ export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
52
83
 
53
84
  router.get(path, async (c) => {
54
85
  const db = getDb(c);
55
- const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
86
+ const conds: SQL[] = [isNull(table.deletedAt) as SQL];
87
+ if (spec.orgScope) {
88
+ const orgId = await resolveScopedOrg(spec, c);
89
+ if (!orgId) return c.json({ error: 'Sign in to an organization to list this resource' }, 401);
90
+ conds.push(orgScopeCondition(spec.orgScope, db, orgId));
91
+ }
92
+ const q = db.select().from(table).where(conds.length === 1 ? conds[0] : and(...conds)).$dynamic();
56
93
  const orders = orderBy === undefined ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];
57
94
  if (orders.length > 0) q.orderBy(...orders.map((o) => (o.dir === 'desc' ? desc(o.col) : asc(o.col))));
58
95
  return c.json(await q);
@@ -68,7 +105,13 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
68
105
 
69
106
  router.get(path, async (c) => {
70
107
  const db = getDb(c);
71
- const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
108
+ const conds: SQL[] = [isNull(table.deletedAt) as SQL];
109
+ if (spec.orgScope) {
110
+ const orgId = await resolveScopedOrg(spec, c);
111
+ if (!orgId) return c.json({ error: 'Sign in to an organization to list this resource' }, 401);
112
+ conds.push(orgScopeCondition(spec.orgScope, db, orgId));
113
+ }
114
+ const q = db.select().from(table).where(conds.length === 1 ? conds[0] : and(...conds)).$dynamic();
72
115
 
73
116
  const orderParam = c.req.query('order');
74
117
  if (orderParam !== undefined) {
@@ -106,16 +149,22 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
106
149
  const typeDetails = patchTypeErrors(table, patch);
107
150
  if (typeDetails) return c.json({ error: 'Invalid field types', details: typeDetails }, 400);
108
151
  const db = getDb(c);
152
+ const conds: SQL[] = [eq(table.id, c.req.param('id')), isNull(table.deletedAt) as SQL];
153
+ if (spec.orgScope) {
154
+ const orgId = await resolveScopedOrg(spec, c);
155
+ if (!orgId) return c.json({ error: 'Sign in to an organization to update this resource' }, 401);
156
+ conds.push(orgScopeCondition(spec.orgScope, db, orgId));
157
+ }
109
158
  const [row] = await db
110
159
  .update(table)
111
160
  .set({ ...patch, ...stampUpdate(table) } as never)
112
- .where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
161
+ .where(conds.length === 1 ? conds[0] : and(...conds))
113
162
  .returning();
114
163
  return row ? c.json(row) : c.json({ error: `${label} not found` }, 404);
115
164
  });
116
165
 
117
166
  if (spec.create) {
118
- const { schema, prefix, defaults } = spec.create;
167
+ const { schema, prefix, defaults, pre } = spec.create;
119
168
  router.post(path, async (c) => {
120
169
  const raw = await c.req.json().catch(() => undefined);
121
170
  if (raw === undefined || typeof raw !== 'object' || raw === null) {
@@ -126,10 +175,36 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
126
175
  return c.json({ error: 'Invalid request body', details: parsed.error.flatten().fieldErrors }, 400);
127
176
  }
128
177
  const body = normalizeRow(table, parsed.data as Record<string, unknown>);
178
+ if (pre) {
179
+ const gate = await pre(c, body);
180
+ if (gate) return gate;
181
+ }
129
182
  const db = getDb(c);
183
+ const stamped: Record<string, unknown> = {};
184
+ if (spec.orgScope) {
185
+ const orgId = await resolveScopedOrg(spec, c);
186
+ if (!orgId) return c.json({ error: 'Sign in to an organization to create this resource' }, 401);
187
+ const scope = spec.orgScope;
188
+ if (scope.column) {
189
+ const key = orgColumnKey(spec, scope.column);
190
+ if (key) stamped[key] = orgId;
191
+ } else {
192
+ const key = orgColumnKey(spec, scope.farmColumn!);
193
+ const farmId = key ? (body[key] as string | undefined) : undefined;
194
+ if (farmId) {
195
+ const farms = scope.farms!;
196
+ const [farm] = await db
197
+ .select({ id: farms.id })
198
+ .from(farms)
199
+ .where(and(eq(farms.id, farmId), eq(farms.orgId, orgId)))
200
+ .limit(1);
201
+ if (!farm) return c.json({ error: 'Farm is not in your organization' }, 400);
202
+ }
203
+ }
204
+ }
130
205
  const [row] = await db
131
206
  .insert(table)
132
- .values({ ...defaults?.(c), ...body, id: uid(prefix) } as never)
207
+ .values({ ...defaults?.(c), ...body, ...stamped, id: uid(prefix) } as never)
133
208
  .returning();
134
209
  return c.json(row, 201);
135
210
  });
@@ -138,10 +213,16 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
138
213
  if (spec.remove) {
139
214
  router.delete(`${path}/:id`, async (c) => {
140
215
  const db = getDb(c);
216
+ const conds: SQL[] = [eq(table.id, c.req.param('id')), isNull(table.deletedAt) as SQL];
217
+ if (spec.orgScope) {
218
+ const orgId = await resolveScopedOrg(spec, c);
219
+ if (!orgId) return c.json({ error: 'Sign in to an organization to delete this resource' }, 401);
220
+ conds.push(orgScopeCondition(spec.orgScope, db, orgId));
221
+ }
141
222
  const [row] = await db
142
223
  .update(table)
143
224
  .set({ deletedAt: new Date(), ...stampUpdate(table) } as never)
144
- .where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
225
+ .where(conds.length === 1 ? conds[0] : and(...conds))
145
226
  .returning({ id: table.id });
146
227
  return row ? c.json({ ok: true }) : c.json({ error: `${label} not found` }, 404);
147
228
  });
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ export type { ApiConfig } from './api';
3
3
  export { healthRouter } from './health';
4
4
  export { ApiError, apiOnError, isUniqueViolation } from './errors';
5
5
  export { crudRoutes, listRoutes } from './crud';
6
- export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec } from './crud';
6
+ export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec, OrgScopeSpec } from './crud';
7
7
  export { docStore, canTransition, epoch, WorkflowError, UnknownCollectionError } from './docstore';
8
8
  export type { Doc, DocInput, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn, DocAfterWriteFn, DocScopeSpec, DocWriteHookArgs, DocPatchHookArgs } from './docstore';
9
9
  export { getDb } from './db';