@umituz/web-hono 1.7.5 → 1.7.7

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,7 +1,7 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.7.5",
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\u2192client type bridge (ClientRow), apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), and db lifecycle scripts (reset / snapshot / seed)",
3
+ "version": "1.7.7",
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",
7
7
  "types": "./src/index.ts",
package/src/crud.ts CHANGED
@@ -6,7 +6,7 @@ import { neon } from '@neondatabase/serverless';
6
6
  import type { Context } from 'hono';
7
7
  import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
8
8
  import { z } from 'zod';
9
- import { normalizeRow, pickPatch, stampUpdate, uid } from './lib';
9
+ import { normalizeRow, patchTypeErrors, pickPatch, stampUpdate, uid } from './lib';
10
10
  import type { ApiEnv } from './env';
11
11
 
12
12
  /**
@@ -139,8 +139,12 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
139
139
  });
140
140
 
141
141
  router.patch(`${path}/:id`, async (c) => {
142
- const patch = pickPatch(table, await c.req.json().catch(() => null));
142
+ const raw = await c.req.json().catch(() => undefined);
143
+ if (raw === undefined) return c.json({ error: 'Malformed JSON in request body' }, 400);
144
+ const patch = pickPatch(table, raw);
143
145
  if (!patch) return c.json({ error: 'No updatable fields' }, 400);
146
+ const typeDetails = patchTypeErrors(table, patch);
147
+ if (typeDetails) return c.json({ error: 'Invalid field types', details: typeDetails }, 400);
144
148
  const db = getDb(c);
145
149
  const [row] = await db
146
150
  .update(table)
@@ -156,7 +160,11 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
156
160
  if (spec.create) {
157
161
  const { schema, prefix, defaults } = spec.create;
158
162
  router.post(path, async (c) => {
159
- const parsed = schema.safeParse(await c.req.json().catch(() => null));
163
+ const raw = await c.req.json().catch(() => undefined);
164
+ if (raw === undefined || typeof raw !== 'object' || raw === null) {
165
+ return c.json({ error: 'Malformed JSON in request body' }, 400);
166
+ }
167
+ const parsed = schema.safeParse(raw);
160
168
  if (!parsed.success) {
161
169
  return c.json({ error: 'Invalid request body', details: parsed.error.flatten().fieldErrors }, 400);
162
170
  }
package/src/index.ts CHANGED
@@ -26,7 +26,7 @@ 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, normalizeRow, stampUpdate, trio, actor } from './lib';
29
+ export { uid, pickPatch, patchTypeErrors, normalizeRow, 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';
package/src/lib.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { getTableColumns } from 'drizzle-orm';
2
2
  import { timestamp } from 'drizzle-orm/pg-core';
3
- import type { PgTable } from 'drizzle-orm/pg-core';
3
+ import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
4
4
 
5
5
  /** Server-side id generation: `${prefix}_${base36 timestamp}${base36 counter}`. */
6
6
  let idCounter = 0;
@@ -80,6 +80,40 @@ export function pickPatch(table: PgTable, body: unknown): Record<string, unknown
80
80
  return Object.keys(out).length > 0 ? out : null;
81
81
  }
82
82
 
83
+ /**
84
+ * Column-type check for schema-less patches (the crudRoutes PATCH path):
85
+ * a JSON value whose primitive type contradicts the column's drizzle
86
+ * dataType would otherwise surface as a driver 500. Returns the details
87
+ * object for the 400 envelope, or null when every value fits.
88
+ */
89
+ export function patchTypeErrors(table: PgTable, patch: Record<string, unknown>): Record<string, string[]> | null {
90
+ const columns = getTableColumns(table) as unknown as Record<string, PgColumn>;
91
+ const errors: Record<string, string[]> = {};
92
+ for (const [key, value] of Object.entries(patch)) {
93
+ const col = columns[key];
94
+ if (!col) continue;
95
+ let msg: string | null = null;
96
+ switch (col.dataType) {
97
+ case 'string':
98
+ msg = typeof value === 'string' ? null : 'expected string';
99
+ break;
100
+ case 'number':
101
+ msg = typeof value === 'number' && Number.isFinite(value) ? null : 'expected number';
102
+ break;
103
+ case 'boolean':
104
+ msg = typeof value === 'boolean' ? null : 'expected boolean';
105
+ break;
106
+ case 'date':
107
+ msg = typeof value === 'string' || value instanceof Date ? null : 'expected date string';
108
+ break;
109
+ default:
110
+ break;
111
+ }
112
+ if (msg) errors[key] = [msg];
113
+ }
114
+ return Object.keys(errors).length > 0 ? errors : null;
115
+ }
116
+
83
117
  /**
84
118
  * Normalizes a create payload against the table before insert: drops keys
85
119
  * that are not table columns, turns ISO-datetime strings destined for
package/src/org.ts CHANGED
@@ -31,12 +31,22 @@ export async function orgHasMode(db: CrudDb, orgs: OrgsLike, orgId: string, mode
31
31
 
32
32
  /** Next `PREFIX-n` (or `PREFIX-YYYY-NNNN` with year: true) document number:
33
33
  * max numeric suffix +1 among the current year's live rows. Not a
34
- * reservation — the partial-unique on number turns races into a 409. */
34
+ * reservation — the partial-unique on number turns races into a 409.
35
+ * digitsOnly: true serves prefix-less columns that store the bare integer
36
+ * ("101") — prefix is ignored, non-numeric rows don't count. */
35
37
  export async function nextNumber(
36
38
  db: CrudDb,
37
39
  table: NumberedTable,
38
40
  prefix: string,
39
- opts: { orgId?: string; base?: number; year?: boolean; pad?: number; column?: PgColumn } = {},
41
+ opts: {
42
+ orgId?: string;
43
+ base?: number;
44
+ year?: boolean;
45
+ pad?: number;
46
+ column?: PgColumn;
47
+ digitsOnly?: boolean;
48
+ separator?: string;
49
+ } = {},
40
50
  ): Promise<string> {
41
51
  const numberCol = opts.column ?? table.number;
42
52
  if (!numberCol) throw new Error('nextNumber: no number column (pass opts.column for orderNo-style tables)');
@@ -47,13 +57,16 @@ export async function nextNumber(
47
57
  .select({ number: numberCol })
48
58
  .from(table)
49
59
  .where(conds.length > 0 ? and(...conds) : undefined);
50
- const withYear = opts.year === true;
60
+ const bare = opts.digitsOnly === true;
61
+ const withYear = !bare && opts.year === true;
51
62
  const year = new Date().getFullYear();
52
- const pat = withYear ? new RegExp(`^${prefix}-${year}-(\\d+)$`) : new RegExp(`^${prefix}-(\\d+)$`);
63
+ const sep = bare ? '' : (opts.separator ?? '-').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
64
+ const pat = bare ? /^(\d+)$/ : withYear ? new RegExp(`^${prefix}-${year}-(\\d+)$`) : new RegExp(`^${prefix}${sep}(\\d+)$`);
53
65
  const max = rows.reduce((m, r) => {
54
66
  const n = pat.exec(String(r.number ?? ''))?.[1];
55
67
  return n ? Math.max(m, Number(n)) : m;
56
- }, opts.base ?? (withYear ? 0 : 2000));
68
+ }, opts.base ?? (bare ? 0 : withYear ? 0 : 2000));
57
69
  const n = max + 1;
58
- return withYear ? `${prefix}-${year}-${String(n).padStart(opts.pad ?? 4, '0')}` : `${prefix}-${n}`;
70
+ if (bare) return opts.pad ? String(n).padStart(opts.pad, '0') : String(n);
71
+ return withYear ? `${prefix}-${year}-${String(n).padStart(opts.pad ?? 4, '0')}` : `${prefix}${opts.separator ?? '-'}${n}`;
59
72
  }