@geektr.cloud/acrux-server 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +14 -2
- package/package.json +40 -3
- package/src/crud.ts +183 -0
- package/src/http-errors.ts +29 -0
- package/src/index.ts +6 -0
- package/src/list.ts +77 -0
- package/src/pagination.ts +162 -0
- package/src/validator.ts +6 -0
- package/src/zod.ts +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 geektr
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @geektr.cloud/acrux-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Acrux 的 Hono + Drizzle 服务端抽象:CRUD、offset/cursor 分页、校验与 HTTP 工具。
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm add @geektr.cloud/acrux-server
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
这是 **source-only** 包:入口直接指向 TypeScript 源码,消费者需要能够编译 TypeScript 的 bundler。Hono、Drizzle ORM 与 Zod 等通过 peer dependencies 提供。
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createCrudRoutes, createCursorRoutes, createPaginatedRoutes, HttpErr } from "@geektr.cloud/acrux-server";
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
完整说明见 [Acrux 文档](https://acrux.geektr.cloud/packages/server)与[仓库](https://github.com/geektr-cloud/acrux)。
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geektr.cloud/acrux-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Hono + Drizzle (D1) 服务端抽象:createCrudRoutes、HTTP 错误、zod 校验件。",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/geektr-cloud/acrux.git",
|
|
10
|
+
"directory": "packages/acrux-server"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://acrux.geektr.cloud/packages/server",
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"!**/*.test.ts",
|
|
16
|
+
"!**/__fixtures__/",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public",
|
|
22
|
+
"registry": "https://registry.npmjs.org"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./src/index.ts"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@hono/zod-validator": "^0.9.1",
|
|
29
|
+
"drizzle-orm": "1.0.0-rc.6",
|
|
30
|
+
"hono": "^4.13.23",
|
|
31
|
+
"typescript": "~5.9.3",
|
|
32
|
+
"zod": "^4.6.7"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@hono/zod-validator": "^0.9.0",
|
|
36
|
+
"drizzle-orm": "1.0.0-rc.6",
|
|
37
|
+
"hono": "^4.0.0",
|
|
38
|
+
"zod": "^4.0.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"type-check": "tsc --noEmit -p tsconfig.json"
|
|
42
|
+
}
|
|
6
43
|
}
|
package/src/crud.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { eq, desc, type SQL, type InferSelectModel } from "drizzle-orm";
|
|
3
|
+
import type { SQLiteColumn, SQLiteTable } from "drizzle-orm/sqlite-core";
|
|
4
|
+
import { zValidator } from "@hono/zod-validator";
|
|
5
|
+
import type { ZodType } from "zod";
|
|
6
|
+
import { HttpErr } from "./http-errors";
|
|
7
|
+
import { paramId } from "./validator";
|
|
8
|
+
import type { Db } from "./list";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* CRUD 工厂可作用的表:必须带 `id` 主键列。
|
|
12
|
+
*/
|
|
13
|
+
export type CrudTable = SQLiteTable & { id: SQLiteColumn };
|
|
14
|
+
|
|
15
|
+
/** 工厂内部统一窄化的表类型——精确表泛型会让 query builder 报错,落到 Row 边界再还原。 */
|
|
16
|
+
type AnyTable = SQLiteTable & { id: SQLiteColumn };
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 三个工厂(createCrudRoutes / createPaginatedRoutes / createCursorRoutes)共享的基础配置。
|
|
20
|
+
* 三者仅 `GET /` 列表端点不同;其余 5 个写/读端点完全一致,由 `crudBase` 生成。
|
|
21
|
+
* - `create` / `upsert` 为 zod body 校验器,来源于 `core/<entity>/schema.ts`。
|
|
22
|
+
* - `db` 由调用方注入,工厂本身不 import `@server/db`,便于独立打包。
|
|
23
|
+
*/
|
|
24
|
+
export interface CrudBaseOptions<TTable extends CrudTable, TCreate extends object, TUpsert extends { id?: string }> {
|
|
25
|
+
db: Db;
|
|
26
|
+
table: TTable;
|
|
27
|
+
create: ZodType<TCreate>;
|
|
28
|
+
upsert: ZodType<TUpsert>;
|
|
29
|
+
/** 404 文案,默认 "Not found"。 */
|
|
30
|
+
notFound?: string;
|
|
31
|
+
/**
|
|
32
|
+
* 创建前钩子(POST / 与 PUT / 无 id 分支)。抛错即中止。
|
|
33
|
+
* 返回 Partial<TCreate> 则浅合并入写库数据(如注入 token、tenantId);返回 void 则不变。
|
|
34
|
+
*/
|
|
35
|
+
beforeCreate?: (data: TCreate, db: Db) => Promise<Partial<TCreate> | void> | Partial<TCreate> | void;
|
|
36
|
+
/** 创建后钩子。row 为刚写入的完整行。 */
|
|
37
|
+
afterCreate?: (row: InferSelectModel<TTable>, db: Db) => Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* 更新前钩子(PUT /:id 与 PUT / 带 id 分支)。抛错即中止。
|
|
40
|
+
* 返回 Partial<TCreate> 则浅合并入写库数据;返回 void 则不变。
|
|
41
|
+
*/
|
|
42
|
+
beforeUpdate?: (
|
|
43
|
+
id: string,
|
|
44
|
+
data: Partial<TCreate>,
|
|
45
|
+
db: Db,
|
|
46
|
+
) => Promise<Partial<TCreate> | void> | Partial<TCreate> | void;
|
|
47
|
+
/** 更新后钩子。row 为更新后的完整行。 */
|
|
48
|
+
afterUpdate?: (row: InferSelectModel<TTable>, db: Db) => Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* 删除前钩子:在删除目标行之前调用(行确认存在后),用于清理关联行 / 悬挂引用。
|
|
51
|
+
* 抛错则中止删除。db 已注入,外键不强制时由此做应用层级联。
|
|
52
|
+
*/
|
|
53
|
+
beforeDelete?: (id: string, db: Db) => Promise<void>;
|
|
54
|
+
/** 删除后钩子。row 为被删除的完整行(DB returning 出来的)。 */
|
|
55
|
+
afterDelete?: (row: InferSelectModel<TTable>, db: Db) => Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 生成除 `GET /` 之外的 5 个共享端点,返回 Hono 链以便各列表工厂续接 `.get("/", …)`。
|
|
60
|
+
*
|
|
61
|
+
* `GET /:id` · `POST /` (create) · `PUT /` (upsert) · `PUT /:id` (update) · `DELETE /:id`
|
|
62
|
+
*
|
|
63
|
+
* 注意:保持链式调用(不要拆成多条 `app.get(...)`),否则 Hono 的 RPC 类型推断会丢失,
|
|
64
|
+
* 前端 `hc<AppType>` 拿不到精确的端点类型。
|
|
65
|
+
*/
|
|
66
|
+
export const crudBase = <TTable extends CrudTable, TCreate extends object, TUpsert extends { id?: string }>(
|
|
67
|
+
opts: CrudBaseOptions<TTable, TCreate, TUpsert>,
|
|
68
|
+
) => {
|
|
69
|
+
type Row = InferSelectModel<TTable>;
|
|
70
|
+
|
|
71
|
+
const { db, create, upsert } = opts;
|
|
72
|
+
const table = opts.table as AnyTable;
|
|
73
|
+
const notFound = opts.notFound ?? "Not found";
|
|
74
|
+
const { beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete, afterDelete } = opts;
|
|
75
|
+
|
|
76
|
+
const findById = async (id: string): Promise<Row | undefined> => {
|
|
77
|
+
const [row] = await db.select().from(table).where(eq(table.id, id));
|
|
78
|
+
return row as Row | undefined;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
return new Hono()
|
|
82
|
+
.get("/:id", paramId, async (c) => {
|
|
83
|
+
const row = await findById(c.req.valid("param").id);
|
|
84
|
+
if (!row) throw HttpErr(404, notFound);
|
|
85
|
+
return c.json(row);
|
|
86
|
+
})
|
|
87
|
+
.post("/", zValidator("json", create), async (c) => {
|
|
88
|
+
const data = c.req.valid("json");
|
|
89
|
+
const patch = beforeCreate ? await beforeCreate(data, db) : undefined;
|
|
90
|
+
const merged = patch ? { ...data, ...patch } : data;
|
|
91
|
+
const [row] = await db.insert(table).values(merged).returning();
|
|
92
|
+
if (afterCreate) await afterCreate(row as Row, db);
|
|
93
|
+
return c.json(row as Row);
|
|
94
|
+
})
|
|
95
|
+
.put("/", zValidator("json", upsert), async (c) => {
|
|
96
|
+
const { id, ...data } = c.req.valid("json");
|
|
97
|
+
if (id) {
|
|
98
|
+
if (!(await findById(id))) throw HttpErr(404, notFound);
|
|
99
|
+
const patch = beforeUpdate ? await beforeUpdate(id, data as unknown as Partial<TCreate>, db) : undefined;
|
|
100
|
+
const merged = patch ? { ...data, ...patch } : data;
|
|
101
|
+
const [row] = await db.update(table).set(merged).where(eq(table.id, id)).returning();
|
|
102
|
+
if (afterUpdate) await afterUpdate(row as Row, db);
|
|
103
|
+
return c.json(row as Row);
|
|
104
|
+
}
|
|
105
|
+
const patch = beforeCreate ? await beforeCreate(data as unknown as TCreate, db) : undefined;
|
|
106
|
+
const merged = patch ? { ...data, ...patch } : data;
|
|
107
|
+
const [row] = await db.insert(table).values(merged).returning();
|
|
108
|
+
if (afterCreate) await afterCreate(row as Row, db);
|
|
109
|
+
return c.json(row as Row);
|
|
110
|
+
})
|
|
111
|
+
.put("/:id", paramId, zValidator("json", create), async (c) => {
|
|
112
|
+
const { id } = c.req.valid("param");
|
|
113
|
+
if (!(await findById(id))) throw HttpErr(404, notFound);
|
|
114
|
+
const data = c.req.valid("json");
|
|
115
|
+
const patch = beforeUpdate ? await beforeUpdate(id, data, db) : undefined;
|
|
116
|
+
const merged = patch ? { ...data, ...patch } : data;
|
|
117
|
+
const [row] = await db.update(table).set(merged).where(eq(table.id, id)).returning();
|
|
118
|
+
if (afterUpdate) await afterUpdate(row as Row, db);
|
|
119
|
+
return c.json(row as Row);
|
|
120
|
+
})
|
|
121
|
+
.delete("/:id", paramId, async (c) => {
|
|
122
|
+
const { id } = c.req.valid("param");
|
|
123
|
+
if (!(await findById(id))) throw HttpErr(404, notFound);
|
|
124
|
+
if (beforeDelete) await beforeDelete(id, db);
|
|
125
|
+
const [row] = (await db.delete(table).where(eq(table.id, id)).returning()) as Row[];
|
|
126
|
+
if (afterDelete) await afterDelete(row as Row, db);
|
|
127
|
+
return c.json(row as Row);
|
|
128
|
+
});
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* createCrudRoutes 的配置项。在 base 之上加 `orderBy`(列表排序)。
|
|
133
|
+
*/
|
|
134
|
+
export interface CrudOptions<
|
|
135
|
+
TTable extends CrudTable,
|
|
136
|
+
TCreate extends object,
|
|
137
|
+
TUpsert extends { id?: string },
|
|
138
|
+
TOut extends object = InferSelectModel<TTable>,
|
|
139
|
+
> extends CrudBaseOptions<TTable, TCreate, TUpsert> {
|
|
140
|
+
/** 列表排序,默认 `desc(id)`(≈ UUIDv7 创建顺序倒序)。返回单个或多个 SQL 排序表达式。 */
|
|
141
|
+
orderBy?: (table: TTable) => SQL | SQL[];
|
|
142
|
+
/**
|
|
143
|
+
* 列表行后处理:批量接收 Row[],返回富化 / 裁剪后的 Out[]。
|
|
144
|
+
* 批量签名避免 N+1(如 memos 的 attachments join 必须 inArray 批量查)。
|
|
145
|
+
* 默认 `(rows) => rows`。TOut 缺省 = Row;传 serialize 时 TypeScript 从回调推断 TOut。
|
|
146
|
+
*/
|
|
147
|
+
serialize?: (rows: InferSelectModel<TTable>[]) => TOut[] | Promise<TOut[]>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 生成标准 6-endpoint CRUD 路由,前端 `useCachedCollection` 的服务端镜像。
|
|
152
|
+
*
|
|
153
|
+
* `GET /` · `GET /:id` · `POST /` (create) · `PUT /` (upsert) · `PUT /:id` (update) · `DELETE /:id`
|
|
154
|
+
*
|
|
155
|
+
* `GET /` 一次性返回全部行(内存集合场景)。需要分页时改用 `createPaginatedRoutes` / `createCursorRoutes`。
|
|
156
|
+
*/
|
|
157
|
+
export const createCrudRoutes = <
|
|
158
|
+
TTable extends CrudTable,
|
|
159
|
+
TCreate extends object,
|
|
160
|
+
TUpsert extends { id?: string },
|
|
161
|
+
TOut extends object = InferSelectModel<TTable>,
|
|
162
|
+
>(
|
|
163
|
+
opts: CrudOptions<TTable, TCreate, TUpsert, TOut>,
|
|
164
|
+
) => {
|
|
165
|
+
type Row = InferSelectModel<TTable>;
|
|
166
|
+
|
|
167
|
+
const { db } = opts;
|
|
168
|
+
const table = opts.table as AnyTable;
|
|
169
|
+
const serialize = (opts.serialize ?? ((rows) => rows)) as (rows: Row[]) => TOut[] | Promise<TOut[]>;
|
|
170
|
+
const orderBy = (opts.orderBy ?? ((t) => desc(t.id))) as (t: AnyTable) => SQL | SQL[];
|
|
171
|
+
const toOrderBy = (): SQL[] => {
|
|
172
|
+
const r = orderBy(table);
|
|
173
|
+
return Array.isArray(r) ? r : [r];
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
return crudBase(opts).get("/", async (c) => {
|
|
177
|
+
const rows = await db
|
|
178
|
+
.select()
|
|
179
|
+
.from(table)
|
|
180
|
+
.orderBy(...toOrderBy());
|
|
181
|
+
return c.json(await serialize(rows as Row[]));
|
|
182
|
+
});
|
|
183
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Context } from "hono";
|
|
2
|
+
import type { ContentfulStatusCode } from "hono/utils/http-status";
|
|
3
|
+
|
|
4
|
+
class HttpError extends Error {
|
|
5
|
+
constructor(
|
|
6
|
+
readonly status: ContentfulStatusCode,
|
|
7
|
+
message: string,
|
|
8
|
+
) {
|
|
9
|
+
super(message);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const ErrorHandler = (_err: Error, c: Context) => {
|
|
14
|
+
if (!(_err instanceof HttpError)) {
|
|
15
|
+
console.error(_err);
|
|
16
|
+
_err = HttpErr(500, "Internal server error");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const err = _err as HttpError;
|
|
20
|
+
return c.json(
|
|
21
|
+
{
|
|
22
|
+
status: err.status,
|
|
23
|
+
error: err.message,
|
|
24
|
+
},
|
|
25
|
+
err.status,
|
|
26
|
+
);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const HttpErr = (status: ContentfulStatusCode, message: string) => new HttpError(status, message);
|
package/src/index.ts
ADDED
package/src/list.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { and, asc, count, desc, gt, lt, type SQL } from "drizzle-orm";
|
|
2
|
+
import type { SQLiteColumn, SQLiteTable } from "drizzle-orm/sqlite-core";
|
|
3
|
+
import type { DrizzleD1Database } from "drizzle-orm/d1";
|
|
4
|
+
|
|
5
|
+
export type Db = DrizzleD1Database;
|
|
6
|
+
|
|
7
|
+
/** query builder 在精确表泛型上会报错,统一窄化到这个基底,调用方在边界还原 Row。 */
|
|
8
|
+
type AnyTable = SQLiteTable & { id: SQLiteColumn };
|
|
9
|
+
|
|
10
|
+
const mergeWhere = (conds: (SQL | undefined)[]): SQL | undefined => {
|
|
11
|
+
const list = conds.filter(Boolean) as SQL[];
|
|
12
|
+
return list.length ? and(...list) : undefined;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// ── offset 分页查询 ─────────────────────────────────────────────────────────────
|
|
16
|
+
// 工厂与手写路由共用:一次查当前页 + 一次 count(同 where)。
|
|
17
|
+
|
|
18
|
+
export interface PaginatedListParams {
|
|
19
|
+
page: number;
|
|
20
|
+
limit: number;
|
|
21
|
+
/** 已翻译好的 WHERE,同时作用于列表与 count。 */
|
|
22
|
+
where?: SQL;
|
|
23
|
+
/** 排序表达式,默认 desc(id)。 */
|
|
24
|
+
orderBy?: SQL[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const paginatedList = async <Row>(
|
|
28
|
+
db: Db,
|
|
29
|
+
table: AnyTable,
|
|
30
|
+
{ page, limit, where, orderBy }: PaginatedListParams,
|
|
31
|
+
): Promise<{ items: Row[]; total: number }> => {
|
|
32
|
+
const order = orderBy?.length ? orderBy : [desc(table.id)];
|
|
33
|
+
const rows = await db
|
|
34
|
+
.select()
|
|
35
|
+
.from(table)
|
|
36
|
+
.where(where)
|
|
37
|
+
.orderBy(...order)
|
|
38
|
+
.limit(limit)
|
|
39
|
+
.offset((page - 1) * limit);
|
|
40
|
+
|
|
41
|
+
const [agg] = await db.select({ value: count() }).from(table).where(where);
|
|
42
|
+
return { items: rows as Row[], total: agg?.value ?? 0 };
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// ── cursor 分页查询 ─────────────────────────────────────────────────────────────
|
|
46
|
+
// 游标恒为 id 列:多取 1 行探测下一页,溢出则 nextCursor = 本页末行 id。
|
|
47
|
+
|
|
48
|
+
export interface CursorListParams {
|
|
49
|
+
cursor?: string;
|
|
50
|
+
limit: number;
|
|
51
|
+
/** desc(默认,id 倒序、游标 `id < cursor`)或 asc(`id > cursor`)。 */
|
|
52
|
+
direction?: "asc" | "desc";
|
|
53
|
+
/** 额外的过滤条件(与游标条件 AND)。 */
|
|
54
|
+
where?: SQL;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const cursorList = async <Row>(
|
|
58
|
+
db: Db,
|
|
59
|
+
table: AnyTable,
|
|
60
|
+
{ cursor, limit, direction = "desc", where }: CursorListParams,
|
|
61
|
+
): Promise<{ items: Row[]; nextCursor: string | null }> => {
|
|
62
|
+
// 方向同时驱动排序与游标比较,二者必须一致。
|
|
63
|
+
const orderExpr = direction === "desc" ? desc(table.id) : asc(table.id);
|
|
64
|
+
const cursorCond = cursor ? (direction === "desc" ? lt(table.id, cursor) : gt(table.id, cursor)) : undefined;
|
|
65
|
+
|
|
66
|
+
const rows = (await db
|
|
67
|
+
.select()
|
|
68
|
+
.from(table)
|
|
69
|
+
.where(mergeWhere([where, cursorCond]))
|
|
70
|
+
.orderBy(orderExpr)
|
|
71
|
+
.limit(limit + 1)) as Row[];
|
|
72
|
+
|
|
73
|
+
const hasMore = rows.length > limit;
|
|
74
|
+
const items = hasMore ? rows.slice(0, limit) : rows;
|
|
75
|
+
const last = items.at(-1) as (Row & { id: string }) | undefined;
|
|
76
|
+
return { items, nextCursor: hasMore && last ? last.id : null };
|
|
77
|
+
};
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { desc, type SQL, type InferSelectModel } from "drizzle-orm";
|
|
2
|
+
import type { SQLiteColumn, SQLiteTable } from "drizzle-orm/sqlite-core";
|
|
3
|
+
import { zValidator } from "@hono/zod-validator";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { crudBase, type CrudBaseOptions, type CrudTable } from "./crud";
|
|
6
|
+
import { cursorList, paginatedList } from "./list";
|
|
7
|
+
|
|
8
|
+
/** 工厂内部统一窄化的表类型——与 crud.ts 一致,落到 Row 边界再还原。 */
|
|
9
|
+
type AnyTable = SQLiteTable & { id: SQLiteColumn };
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* filter 翻译器:把前端传来的不透明 filter 字符串翻译成 drizzle WHERE 表达式。
|
|
13
|
+
* 返回 undefined 表示不过滤。offset 工厂会同时应用到列表查询与 count。
|
|
14
|
+
*/
|
|
15
|
+
export type FilterWhere = (filter: string) => SQL | undefined;
|
|
16
|
+
|
|
17
|
+
// limit 校验:非数字/缺省 → defaultLimit;超过 maxLimit → 钳制到 maxLimit(而非回退默认)。
|
|
18
|
+
// 注意 .max().catch() 会把越界值「重置」为默认,所以这里用 .transform 做钳制。
|
|
19
|
+
export const clampLimit = (defaultLimit: number, maxLimit: number) =>
|
|
20
|
+
z.coerce
|
|
21
|
+
.number()
|
|
22
|
+
.int()
|
|
23
|
+
.min(1)
|
|
24
|
+
.catch(defaultLimit)
|
|
25
|
+
.transform((n) => Math.min(n, maxLimit));
|
|
26
|
+
|
|
27
|
+
// ── offset 分页 ────────────────────────────────────────────────────────────────
|
|
28
|
+
// 前端 usePaginatedCollection 的服务端镜像。
|
|
29
|
+
// GET /?page&limit&filter → { items: Row[], total: number };offset = (page-1)*limit。
|
|
30
|
+
|
|
31
|
+
export interface PaginatedOptions<
|
|
32
|
+
TTable extends CrudTable,
|
|
33
|
+
TCreate extends object,
|
|
34
|
+
TUpsert extends { id?: string },
|
|
35
|
+
TOut extends object = InferSelectModel<TTable>,
|
|
36
|
+
> extends CrudBaseOptions<TTable, TCreate, TUpsert> {
|
|
37
|
+
/** 列表排序,默认 `desc(id)`(≈ UUIDv7 创建顺序倒序)。 */
|
|
38
|
+
orderBy?: (table: TTable) => SQL | SQL[];
|
|
39
|
+
/** filter 字符串 → WHERE。不传则忽略 filter。 */
|
|
40
|
+
filterWhere?: FilterWhere;
|
|
41
|
+
/** 默认每页条数,limit 缺省/越界时回退到它。默认 20。 */
|
|
42
|
+
defaultLimit?: number;
|
|
43
|
+
/** 每页条数上限,超出则钳制。默认 100。 */
|
|
44
|
+
maxLimit?: number;
|
|
45
|
+
/**
|
|
46
|
+
* 列表行后处理:批量接收 Row[],返回富化 / 裁剪后的 Out[]。
|
|
47
|
+
* 批量签名避免 N+1(如 memos 的 attachments join 必须 inArray 批量查)。
|
|
48
|
+
* 默认 `(rows) => rows`。TOut 缺省 = Row;传 serialize 时 TypeScript 从回调推断 TOut。
|
|
49
|
+
*/
|
|
50
|
+
serialize?: (rows: InferSelectModel<TTable>[]) => TOut[] | Promise<TOut[]>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 生成 offset 分页的 6-endpoint 路由,前端 `usePaginatedCollection` 的服务端镜像。
|
|
55
|
+
*
|
|
56
|
+
* `GET /?page&limit&filter` → `{ items, total }`,其余 5 端点同 `createCrudRoutes`。
|
|
57
|
+
*/
|
|
58
|
+
export const createPaginatedRoutes = <
|
|
59
|
+
TTable extends CrudTable,
|
|
60
|
+
TCreate extends object,
|
|
61
|
+
TUpsert extends { id?: string },
|
|
62
|
+
TOut extends object = InferSelectModel<TTable>,
|
|
63
|
+
>(
|
|
64
|
+
opts: PaginatedOptions<TTable, TCreate, TUpsert, TOut>,
|
|
65
|
+
) => {
|
|
66
|
+
type Row = InferSelectModel<TTable>;
|
|
67
|
+
|
|
68
|
+
const { db, filterWhere } = opts;
|
|
69
|
+
const table = opts.table as AnyTable;
|
|
70
|
+
const serialize = (opts.serialize ?? ((rows) => rows)) as (rows: Row[]) => TOut[] | Promise<TOut[]>;
|
|
71
|
+
const defaultLimit = opts.defaultLimit ?? 20;
|
|
72
|
+
const maxLimit = opts.maxLimit ?? 100;
|
|
73
|
+
const orderBy = (opts.orderBy ?? ((t) => desc(t.id))) as (t: AnyTable) => SQL | SQL[];
|
|
74
|
+
const toOrderBy = (): SQL[] => {
|
|
75
|
+
const r = orderBy(table);
|
|
76
|
+
return Array.isArray(r) ? r : [r];
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const query = z.object({
|
|
80
|
+
page: z.coerce.number().int().min(1).catch(1),
|
|
81
|
+
limit: clampLimit(defaultLimit, maxLimit),
|
|
82
|
+
filter: z.string().catch(""),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
return crudBase(opts).get("/", zValidator("query", query), async (c) => {
|
|
86
|
+
const { page, limit, filter } = c.req.valid("query");
|
|
87
|
+
const { items, total } = await paginatedList<Row>(db, table, {
|
|
88
|
+
page,
|
|
89
|
+
limit,
|
|
90
|
+
where: filterWhere?.(filter),
|
|
91
|
+
orderBy: toOrderBy(),
|
|
92
|
+
});
|
|
93
|
+
return c.json({ items: await serialize(items), total });
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
// ── cursor 分页 ────────────────────────────────────────────────────────────────
|
|
98
|
+
// 前端 useCursorCollection 的服务端镜像。游标恒为 `id` 列(UUIDv7 单调,序 ≈ 创建序)。
|
|
99
|
+
// GET /?cursor&limit&filter → { items: Row[], nextCursor: string | null }。
|
|
100
|
+
|
|
101
|
+
export interface CursorOptions<
|
|
102
|
+
TTable extends CrudTable,
|
|
103
|
+
TCreate extends object,
|
|
104
|
+
TUpsert extends { id?: string },
|
|
105
|
+
TOut extends object = InferSelectModel<TTable>,
|
|
106
|
+
> extends CrudBaseOptions<TTable, TCreate, TUpsert> {
|
|
107
|
+
/** 翻页方向:`desc`(默认,id 倒序、游标取 `id < cursor`)或 `asc`(`id > cursor`)。 */
|
|
108
|
+
direction?: "asc" | "desc";
|
|
109
|
+
/** filter 字符串 → WHERE。不传则忽略 filter。 */
|
|
110
|
+
filterWhere?: FilterWhere;
|
|
111
|
+
/** 默认每次拉取条数。默认 20。 */
|
|
112
|
+
defaultLimit?: number;
|
|
113
|
+
/** 每次拉取条数上限。默认 100。 */
|
|
114
|
+
maxLimit?: number;
|
|
115
|
+
/**
|
|
116
|
+
* 列表行后处理:批量接收 Row[],返回富化 / 裁剪后的 Out[]。
|
|
117
|
+
* 批量签名避免 N+1(如 memos 的 attachments join 必须 inArray 批量查)。
|
|
118
|
+
* 默认 `(rows) => rows`。TOut 缺省 = Row;传 serialize 时 TypeScript 从回调推断 TOut。
|
|
119
|
+
*/
|
|
120
|
+
serialize?: (rows: InferSelectModel<TTable>[]) => TOut[] | Promise<TOut[]>;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 生成 cursor 分页的 6-endpoint 路由,前端 `useCursorCollection` 的服务端镜像。
|
|
125
|
+
*
|
|
126
|
+
* `GET /?cursor&limit&filter` → `{ items, nextCursor }`,其余 5 端点同 `createCrudRoutes`。
|
|
127
|
+
* 多取 1 行判断是否还有下一页:溢出则 `nextCursor` = 本页末行 id,否则 null。
|
|
128
|
+
*/
|
|
129
|
+
export const createCursorRoutes = <
|
|
130
|
+
TTable extends CrudTable,
|
|
131
|
+
TCreate extends object,
|
|
132
|
+
TUpsert extends { id?: string },
|
|
133
|
+
TOut extends object = InferSelectModel<TTable>,
|
|
134
|
+
>(
|
|
135
|
+
opts: CursorOptions<TTable, TCreate, TUpsert, TOut>,
|
|
136
|
+
) => {
|
|
137
|
+
type Row = InferSelectModel<TTable>;
|
|
138
|
+
|
|
139
|
+
const { db, filterWhere } = opts;
|
|
140
|
+
const table = opts.table as AnyTable;
|
|
141
|
+
const serialize = (opts.serialize ?? ((rows) => rows)) as (rows: Row[]) => TOut[] | Promise<TOut[]>;
|
|
142
|
+
const direction = opts.direction ?? "desc";
|
|
143
|
+
const defaultLimit = opts.defaultLimit ?? 20;
|
|
144
|
+
const maxLimit = opts.maxLimit ?? 100;
|
|
145
|
+
|
|
146
|
+
const query = z.object({
|
|
147
|
+
cursor: z.string().optional(),
|
|
148
|
+
limit: clampLimit(defaultLimit, maxLimit),
|
|
149
|
+
filter: z.string().catch(""),
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
return crudBase(opts).get("/", zValidator("query", query), async (c) => {
|
|
153
|
+
const { cursor, limit, filter } = c.req.valid("query");
|
|
154
|
+
const { items, nextCursor } = await cursorList<Row>(db, table, {
|
|
155
|
+
cursor,
|
|
156
|
+
limit,
|
|
157
|
+
direction,
|
|
158
|
+
where: filterWhere?.(filter),
|
|
159
|
+
});
|
|
160
|
+
return c.json({ items: await serialize(items), nextCursor });
|
|
161
|
+
});
|
|
162
|
+
};
|
package/src/validator.ts
ADDED
package/src/zod.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
/** Validates that a string is parseable as JSON. Use for textarea-bound form fields. */
|
|
4
|
+
export const validJson = (message = "JSON 格式无效") =>
|
|
5
|
+
z.string().refine(
|
|
6
|
+
(s) => {
|
|
7
|
+
try {
|
|
8
|
+
JSON.parse(s);
|
|
9
|
+
return true;
|
|
10
|
+
} catch {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
{ message },
|
|
15
|
+
);
|