@umituz/web-hono 1.4.0 → 1.6.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/crud.ts +10 -10
- package/src/errors.ts +8 -0
- package/src/index.ts +7 -5
- package/src/lib.ts +5 -0
- package/src/rows.ts +28 -0
- package/src/validator.ts +6 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-hono",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.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/crud.ts
CHANGED
|
@@ -40,6 +40,8 @@ export type CrudDbFactory = (c: RequestContext) => CrudDb;
|
|
|
40
40
|
|
|
41
41
|
export type CrudTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
|
|
42
42
|
|
|
43
|
+
export type OrderSpec = { col: PgColumn; dir?: 'asc' | 'desc' };
|
|
44
|
+
|
|
43
45
|
/** Opt-in POST create: zod-validated body, server-generated uid, optional
|
|
44
46
|
* request-scoped stamps (organizationId, createdBy…). */
|
|
45
47
|
export interface CreateSpec {
|
|
@@ -55,8 +57,9 @@ export interface ListSpec {
|
|
|
55
57
|
/** Path under /api, e.g. '/activities'. */
|
|
56
58
|
path: string;
|
|
57
59
|
table: PgTable & { deletedAt: PgColumn };
|
|
58
|
-
/** List order; defaults to insertion order.
|
|
59
|
-
|
|
60
|
+
/** List order; defaults to insertion order. Array = multi-key
|
|
61
|
+
* (primary first, ties broken by the next key). */
|
|
62
|
+
orderBy?: OrderSpec | ReadonlyArray<OrderSpec>;
|
|
60
63
|
/** Injectable db factory (tests, Hyperdrive). Default: per-request
|
|
61
64
|
* drizzle(neon(c.env.DATABASE_URL)) — the 1.x behavior. */
|
|
62
65
|
db?: CrudDbFactory;
|
|
@@ -85,7 +88,8 @@ export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
|
|
|
85
88
|
router.get(path, async (c) => {
|
|
86
89
|
const db = getDb(c);
|
|
87
90
|
const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
|
|
88
|
-
|
|
91
|
+
const orders = orderBy === undefined ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
92
|
+
if (orders.length > 0) q.orderBy(...orders.map((o) => (o.dir === 'desc' ? desc(o.col) : asc(o.col))));
|
|
89
93
|
return c.json(await q);
|
|
90
94
|
});
|
|
91
95
|
|
|
@@ -104,20 +108,16 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
|
104
108
|
// ?order=col | -col (leading '-' = desc) — whitelisted against the
|
|
105
109
|
// table's own property columns; an explicit order overrides spec.orderBy.
|
|
106
110
|
const orderParam = c.req.query('order');
|
|
107
|
-
let orderCol: PgColumn | undefined;
|
|
108
|
-
let dir: 'asc' | 'desc' = 'asc';
|
|
109
111
|
if (orderParam !== undefined) {
|
|
110
112
|
const wantDesc = orderParam.startsWith('-');
|
|
111
113
|
const name = orderParam.slice(wantDesc ? 1 : 0);
|
|
112
114
|
const found = (getTableColumns(table) as unknown as Record<string, PgColumn>)[name];
|
|
113
115
|
if (!found) return c.json({ error: 'Invalid order column' }, 400);
|
|
114
|
-
|
|
115
|
-
dir = wantDesc ? 'desc' : 'asc';
|
|
116
|
+
q.orderBy(wantDesc ? desc(found) : asc(found));
|
|
116
117
|
} else if (orderBy) {
|
|
117
|
-
|
|
118
|
-
|
|
118
|
+
const orders = Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
119
|
+
q.orderBy(...orders.map((o) => (o.dir === 'desc' ? desc(o.col) : asc(o.col))));
|
|
119
120
|
}
|
|
120
|
-
if (orderCol) q.orderBy(dir === 'desc' ? desc(orderCol) : asc(orderCol));
|
|
121
121
|
|
|
122
122
|
// ?limit/&offset= — absent params add no clauses: the 1.x query exactly.
|
|
123
123
|
// offset without order follows the spec/default insertion order (the
|
package/src/errors.ts
CHANGED
|
@@ -32,6 +32,14 @@ export class ApiError extends Error {
|
|
|
32
32
|
static badRequest(message: string, details?: unknown): ApiError {
|
|
33
33
|
return new ApiError(400, message, details);
|
|
34
34
|
}
|
|
35
|
+
|
|
36
|
+
static forbidden(message: string): ApiError {
|
|
37
|
+
return new ApiError(403, message);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static conflict(message: string): ApiError {
|
|
41
|
+
return new ApiError(409, message);
|
|
42
|
+
}
|
|
35
43
|
}
|
|
36
44
|
|
|
37
45
|
/**
|
package/src/index.ts
CHANGED
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
* Apps keep their schema (with TABLE_PREFIX), domain routers, zod schemas,
|
|
6
6
|
* and business rules — this package owns the cross-cutting skeleton:
|
|
7
7
|
* the createApi app factory, the error envelope layer, the full-CRUD
|
|
8
|
-
* resource factory, getDb, the uid/pickPatch/stampUpdate/trio
|
|
9
|
-
* the org-scoped lookups (resolveOrg/orgHasMode/nextNumber),
|
|
10
|
-
* and notification writes, the JSON-404
|
|
11
|
-
* the ApiEnv binding types.
|
|
8
|
+
* resource factory, getDb, the uid/pickPatch/stampUpdate/trio/actor
|
|
9
|
+
* helpers, the org-scoped lookups (resolveOrg/orgHasMode/nextNumber),
|
|
10
|
+
* the audit and notification writes, findRow/softDelete, the JSON-404
|
|
11
|
+
* and SPA-fallback handlers, and the ApiEnv binding types.
|
|
12
12
|
*
|
|
13
13
|
* Entry points:
|
|
14
14
|
* `.` server core (this file)
|
|
@@ -26,10 +26,12 @@ 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
28
|
export { getDb } from './db';
|
|
29
|
-
export { uid, pickPatch, stampUpdate, trio } from './lib';
|
|
29
|
+
export { uid, pickPatch, stampUpdate, trio, actor } from './lib';
|
|
30
30
|
export { resolveOrg, orgHasMode, nextNumber } from './org';
|
|
31
31
|
export type { UsersLike, OrgsLike, NumberedTable } from './org';
|
|
32
32
|
export { writeAudit, writeNotification } from './activity';
|
|
33
33
|
export type { ActivityTable, AuditWrite, NotificationWrite } from './activity';
|
|
34
|
+
export { findRow, softDelete } from './rows';
|
|
35
|
+
export type { AliveTable } from './rows';
|
|
34
36
|
export { apiNotFound, spaFallback } from './handlers';
|
|
35
37
|
export type { ApiEnv } from './env';
|
package/src/lib.ts
CHANGED
|
@@ -9,6 +9,11 @@ export function uid(prefix: string): string {
|
|
|
9
9
|
return `${prefix}_${Date.now().toString(36)}${idCounter.toString(36)}`;
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
/** Write-schema actor pair with the fleet defaults. */
|
|
13
|
+
export function actor(input: { actorId?: string; actorName?: string }, name = 'Back office'): { actorId: string; actorName: string } {
|
|
14
|
+
return { actorId: input.actorId ?? 'api', actorName: input.actorName ?? name };
|
|
15
|
+
}
|
|
16
|
+
|
|
12
17
|
/**
|
|
13
18
|
* Fleet time-trio columns for timestamptz tables — spread into a pgTable
|
|
14
19
|
* definition: `{ id: text('id').primaryKey(), name: text('name'), ...trio() }`.
|
package/src/rows.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { and, eq, isNull } from 'drizzle-orm';
|
|
2
|
+
import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
|
|
3
|
+
import { ApiError } from './errors';
|
|
4
|
+
import { stampUpdate } from './lib';
|
|
5
|
+
import type { CrudDb, CrudTable } from './crud';
|
|
6
|
+
|
|
7
|
+
export type AliveTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
|
|
8
|
+
type RowOf<T> = T extends { $inferSelect: infer R } ? R : never;
|
|
9
|
+
|
|
10
|
+
/** Live row by id — a miss throws ApiError.notFound (the envelope's 404). */
|
|
11
|
+
export async function findRow<T extends AliveTable>(db: CrudDb, table: T, id: string, label: string): Promise<RowOf<T>> {
|
|
12
|
+
const rows = (await db.select().from(table as CrudTable).where(and(eq(table.id, id), isNull(table.deletedAt)))) as RowOf<T>[];
|
|
13
|
+
const row = rows[0];
|
|
14
|
+
if (!row) throw ApiError.notFound(label);
|
|
15
|
+
return row;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Soft delete (deletedAt + updatedAt stamps) — a miss throws notFound. */
|
|
19
|
+
export async function softDelete<T extends AliveTable>(db: CrudDb, table: T, id: string, label: string): Promise<RowOf<T>> {
|
|
20
|
+
const rows = (await db
|
|
21
|
+
.update(table as CrudTable)
|
|
22
|
+
.set({ deletedAt: new Date(), ...stampUpdate(table) } as never)
|
|
23
|
+
.where(and(eq(table.id, id), isNull(table.deletedAt)))
|
|
24
|
+
.returning()) as RowOf<T>[];
|
|
25
|
+
const row = rows[0];
|
|
26
|
+
if (!row) throw ApiError.notFound(label);
|
|
27
|
+
return row;
|
|
28
|
+
}
|
package/src/validator.ts
CHANGED
|
@@ -23,3 +23,9 @@ export function validateJson<S extends z.ZodType>(schema: S, message = 'Invalid
|
|
|
23
23
|
return parsed.data as z.output<S>;
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
|
+
|
|
27
|
+
export const dateOnly = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'expected YYYY-MM-DD');
|
|
28
|
+
|
|
29
|
+
export const hhmm = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'expected HH:MM');
|
|
30
|
+
|
|
31
|
+
export const actorFields = { actorId: z.string().optional(), actorName: z.string().optional() } as const;
|