@umituz/web-hono 1.19.2 → 1.20.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.19.2",
3
+ "version": "1.20.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), 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;
@@ -29,11 +29,19 @@ export interface CreateSpec {
29
29
  defaults?: (c: RequestContext) => Record<string, unknown>;
30
30
  }
31
31
 
32
+ export interface OrgScopeSpec {
33
+ column?: PgColumn;
34
+ farmColumn?: PgColumn;
35
+ farms?: PgTable & { id: PgColumn; orgId: PgColumn };
36
+ resolve: (c: RequestContext) => Promise<string | null | undefined>;
37
+ }
38
+
32
39
  export interface ListSpec {
33
40
  path: string;
34
41
  table: PgTable & { deletedAt: PgColumn };
35
42
  orderBy?: OrderSpec | ReadonlyArray<OrderSpec>;
36
43
  db?: CrudDbFactory;
44
+ orgScope?: OrgScopeSpec;
37
45
  }
38
46
 
39
47
  export interface CrudSpec extends ListSpec {
@@ -45,6 +53,28 @@ export interface CrudSpec extends ListSpec {
45
53
 
46
54
  const MAX_LIST_LIMIT = 500;
47
55
 
56
+ function assertOrgScope(scope: OrgScopeSpec): void {
57
+ if (scope.column && scope.farmColumn) throw new Error('orgScope: pass either column or farmColumn, not both');
58
+ if (!scope.column && !scope.farmColumn) throw new Error('orgScope: column or farmColumn is required');
59
+ if (scope.farmColumn && !scope.farms) throw new Error('orgScope: farms table is required with farmColumn');
60
+ }
61
+
62
+ function orgScopeCondition(scope: OrgScopeSpec, db: CrudDb, orgId: string): SQL {
63
+ if (scope.column) return eq(scope.column, orgId) as SQL;
64
+ const farms = scope.farms!;
65
+ return inArray(scope.farmColumn!, db.select({ id: farms.id }).from(farms).where(eq(farms.orgId, orgId))) as SQL;
66
+ }
67
+
68
+ async function resolveScopedOrg(spec: ListSpec, c: RequestContext): Promise<string | null | undefined> {
69
+ if (spec.orgScope) assertOrgScope(spec.orgScope);
70
+ return spec.orgScope?.resolve(c);
71
+ }
72
+
73
+ function orgColumnKey(spec: ListSpec, column: PgColumn): string | undefined {
74
+ const cols = getTableColumns(spec.table) as unknown as Record<string, PgColumn>;
75
+ return Object.keys(cols).find((k) => cols[k] === column);
76
+ }
77
+
48
78
  export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
49
79
  const { path, table, orderBy } = spec;
50
80
  const getDb = spec.db ?? defaultDb;
@@ -52,7 +82,13 @@ export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
52
82
 
53
83
  router.get(path, async (c) => {
54
84
  const db = getDb(c);
55
- const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
85
+ const conds: SQL[] = [isNull(table.deletedAt) as SQL];
86
+ if (spec.orgScope) {
87
+ const orgId = await resolveScopedOrg(spec, c);
88
+ if (!orgId) return c.json({ error: 'Sign in to an organization to list this resource' }, 401);
89
+ conds.push(orgScopeCondition(spec.orgScope, db, orgId));
90
+ }
91
+ const q = db.select().from(table).where(conds.length === 1 ? conds[0] : and(...conds)).$dynamic();
56
92
  const orders = orderBy === undefined ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];
57
93
  if (orders.length > 0) q.orderBy(...orders.map((o) => (o.dir === 'desc' ? desc(o.col) : asc(o.col))));
58
94
  return c.json(await q);
@@ -68,7 +104,13 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
68
104
 
69
105
  router.get(path, async (c) => {
70
106
  const db = getDb(c);
71
- const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
107
+ const conds: SQL[] = [isNull(table.deletedAt) as SQL];
108
+ if (spec.orgScope) {
109
+ const orgId = await resolveScopedOrg(spec, c);
110
+ if (!orgId) return c.json({ error: 'Sign in to an organization to list this resource' }, 401);
111
+ conds.push(orgScopeCondition(spec.orgScope, db, orgId));
112
+ }
113
+ const q = db.select().from(table).where(conds.length === 1 ? conds[0] : and(...conds)).$dynamic();
72
114
 
73
115
  const orderParam = c.req.query('order');
74
116
  if (orderParam !== undefined) {
@@ -106,10 +148,16 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
106
148
  const typeDetails = patchTypeErrors(table, patch);
107
149
  if (typeDetails) return c.json({ error: 'Invalid field types', details: typeDetails }, 400);
108
150
  const db = getDb(c);
151
+ const conds: SQL[] = [eq(table.id, c.req.param('id')), isNull(table.deletedAt) as SQL];
152
+ if (spec.orgScope) {
153
+ const orgId = await resolveScopedOrg(spec, c);
154
+ if (!orgId) return c.json({ error: 'Sign in to an organization to update this resource' }, 401);
155
+ conds.push(orgScopeCondition(spec.orgScope, db, orgId));
156
+ }
109
157
  const [row] = await db
110
158
  .update(table)
111
159
  .set({ ...patch, ...stampUpdate(table) } as never)
112
- .where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
160
+ .where(conds.length === 1 ? conds[0] : and(...conds))
113
161
  .returning();
114
162
  return row ? c.json(row) : c.json({ error: `${label} not found` }, 404);
115
163
  });
@@ -127,9 +175,31 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
127
175
  }
128
176
  const body = normalizeRow(table, parsed.data as Record<string, unknown>);
129
177
  const db = getDb(c);
178
+ const stamped: Record<string, unknown> = {};
179
+ if (spec.orgScope) {
180
+ const orgId = await resolveScopedOrg(spec, c);
181
+ if (!orgId) return c.json({ error: 'Sign in to an organization to create this resource' }, 401);
182
+ const scope = spec.orgScope;
183
+ if (scope.column) {
184
+ const key = orgColumnKey(spec, scope.column);
185
+ if (key) stamped[key] = orgId;
186
+ } else {
187
+ const key = orgColumnKey(spec, scope.farmColumn!);
188
+ const farmId = key ? (body[key] as string | undefined) : undefined;
189
+ if (farmId) {
190
+ const farms = scope.farms!;
191
+ const [farm] = await db
192
+ .select({ id: farms.id })
193
+ .from(farms)
194
+ .where(and(eq(farms.id, farmId), eq(farms.orgId, orgId)))
195
+ .limit(1);
196
+ if (!farm) return c.json({ error: 'Farm is not in your organization' }, 400);
197
+ }
198
+ }
199
+ }
130
200
  const [row] = await db
131
201
  .insert(table)
132
- .values({ ...defaults?.(c), ...body, id: uid(prefix) } as never)
202
+ .values({ ...defaults?.(c), ...body, ...stamped, id: uid(prefix) } as never)
133
203
  .returning();
134
204
  return c.json(row, 201);
135
205
  });
@@ -138,10 +208,16 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
138
208
  if (spec.remove) {
139
209
  router.delete(`${path}/:id`, async (c) => {
140
210
  const db = getDb(c);
211
+ const conds: SQL[] = [eq(table.id, c.req.param('id')), isNull(table.deletedAt) as SQL];
212
+ if (spec.orgScope) {
213
+ const orgId = await resolveScopedOrg(spec, c);
214
+ if (!orgId) return c.json({ error: 'Sign in to an organization to delete this resource' }, 401);
215
+ conds.push(orgScopeCondition(spec.orgScope, db, orgId));
216
+ }
141
217
  const [row] = await db
142
218
  .update(table)
143
219
  .set({ deletedAt: new Date(), ...stampUpdate(table) } as never)
144
- .where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
220
+ .where(conds.length === 1 ? conds[0] : and(...conds))
145
221
  .returning({ id: table.id });
146
222
  return row ? c.json({ ok: true }) : c.json({ error: `${label} not found` }, 404);
147
223
  });
package/src/docstore.ts CHANGED
@@ -284,8 +284,10 @@ export function docStore<E extends ApiEnv = ApiEnv>(spec: DocStoreSpec<E>) {
284
284
  });
285
285
  return out;
286
286
  }
287
- for (let i = 0; i < cols.length; i += 1) {
288
- out[cols[i].key] = (await queries[i]).map((r) => r.data as Doc);
287
+ for (const [i, col] of cols.entries()) {
288
+ const query = queries[i];
289
+ if (!query) continue;
290
+ out[col.key] = (await query).map((r) => r.data as Doc);
289
291
  }
290
292
  return out;
291
293
  }
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';