@wordrhyme/auto-crud-server 2.2.0 → 2.4.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/README.md +29 -2
- package/dist/index.cjs +63 -22
- package/dist/index.d.cts +35 -11
- package/dist/index.d.ts +35 -11
- package/dist/index.js +63 -22
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -551,8 +551,7 @@ const ordersRouter = createCrudRouter({
|
|
|
551
551
|
```
|
|
552
552
|
|
|
553
553
|
业务侧可以用 `baseListInputSchema.extend(...)` 增加自定义参数,不需要覆盖
|
|
554
|
-
`list` procedure
|
|
555
|
-
额外字段会保留在 `middleware.list` 的 `input` 中。
|
|
554
|
+
`list` procedure。自定义字段会保留在 `middleware.list` 的 `input` 中。
|
|
556
555
|
|
|
557
556
|
```typescript
|
|
558
557
|
import { baseListInputSchema, createCrudRouter } from '@wordrhyme/auto-crud-server';
|
|
@@ -564,6 +563,7 @@ const productsRouter = createCrudRouter({
|
|
|
564
563
|
schema: createProductSchema,
|
|
565
564
|
updateSchema: updateProductSchema,
|
|
566
565
|
listInputSchema: baseListInputSchema.extend({
|
|
566
|
+
total: z.boolean().optional(),
|
|
567
567
|
include: z
|
|
568
568
|
.object({
|
|
569
569
|
skus: z.boolean().optional(),
|
|
@@ -587,6 +587,11 @@ await trpc.products.list.query({
|
|
|
587
587
|
});
|
|
588
588
|
```
|
|
589
589
|
|
|
590
|
+
列表默认查询总数,响应的 `total` 是符合筛选条件的总条数。按上例在列表输入中声明
|
|
591
|
+
`total` 后,调用 `list.query({ total: false })` 会跳过计数,响应省略 `total`,
|
|
592
|
+
并以 `pageCount: -1` 表示总页数未知。省略参数或传入 `total: true` 时仍返回精确总数。
|
|
593
|
+
如果使用联合输入,只有命中的对象分支显式声明了 `total` 才支持跳过计数。
|
|
594
|
+
|
|
590
595
|
`get` 也可以扩展。默认仍兼容 `get("spu_1")`,业务侧如需详情页按需挂载关联数据,可以改成对象输入:
|
|
591
596
|
|
|
592
597
|
```typescript
|
|
@@ -1338,3 +1343,25 @@ The database provider must implement governed `$counts(table, predicates)`, appl
|
|
|
1338
1343
|
为 CRUD extension provider 实现 `buildConditions({ id, entityId, filters, joinOperator, search })`,返回 `{ filter?: SQL, search?: SQL }`。这属于可信进程内接口,客户端不能提供 SQL。使用 `entityId` 与标签关联表构造相关 `EXISTS` 查询,列表、总数和导出会在原有数据权限条件内组合这些谓词,无须先取一批实体 ID。
|
|
1339
1344
|
|
|
1340
1345
|
扩展筛选统一通过既有 `buildConditions` 接口生成 SQL。标签字段不直接映射为基础表列,应由扩展 provider 提供条件和读取投影;赋值服务负责校验租户、字段及记录更新权限。
|
|
1346
|
+
|
|
1347
|
+
## 按请求补充查询条件
|
|
1348
|
+
|
|
1349
|
+
`query({ ctx, input, operation })` 在守卫之后执行,`operation` 为 `list` 或 `export`,`input` 来自对应输入 schema 和 middleware。返回的 `where` 始终与普通筛选、搜索、scope 求交集,先于列表与导出总数、分页及导出限制执行。未配置时保持原行为。
|
|
1350
|
+
|
|
1351
|
+
```ts
|
|
1352
|
+
createCrudRouter({
|
|
1353
|
+
table: products,
|
|
1354
|
+
listInputSchema,
|
|
1355
|
+
exportInputSchema,
|
|
1356
|
+
query: async ({ ctx, input }) => {
|
|
1357
|
+
if (!input.image) return {};
|
|
1358
|
+
const distance = await imageDistance(ctx, input.image);
|
|
1359
|
+
return {
|
|
1360
|
+
where: sql`${distance} <= ${0.65}`,
|
|
1361
|
+
...(!input.sort?.length ? { orderBy: [asc(distance), asc(products.id)] } : {}),
|
|
1362
|
+
};
|
|
1363
|
+
},
|
|
1364
|
+
});
|
|
1365
|
+
```
|
|
1366
|
+
|
|
1367
|
+
`orderBy` 提供时替换默认排序;权限和作用域不会被覆盖。SQL 表达式必须通过当前数据库 capability 的治理机制构造,不能把其他租户或无权读取的数据带入派生条件。本扩展只作用于列表及导出;批量 counts 仍使用其原有输入契约。
|
package/dist/index.cjs
CHANGED
|
@@ -694,6 +694,26 @@ const baseListInputSchema = zod.z.object({
|
|
|
694
694
|
filters: zod.z.array(filterItemSchema).optional(),
|
|
695
695
|
joinOperator: zod.z.enum(["and", "or"]).default("and")
|
|
696
696
|
});
|
|
697
|
+
const skipListTotal = Symbol("skipListTotal");
|
|
698
|
+
function listSchemaWithOptionalTotal(schema) {
|
|
699
|
+
if (isZodObject(schema)) return Object.hasOwn(schema.shape, "total") ? schema.transform((input) => input.total === false ? {
|
|
700
|
+
...input,
|
|
701
|
+
[skipListTotal]: true
|
|
702
|
+
} : input) : schema;
|
|
703
|
+
if (!("options" in schema) || !Array.isArray(schema.options)) return schema;
|
|
704
|
+
const options = schema.options;
|
|
705
|
+
if (!options.every((option) => typeof option?.parseAsync === "function")) return schema;
|
|
706
|
+
const marked = options.map(listSchemaWithOptionalTotal);
|
|
707
|
+
if (marked.every((option, index) => option === options[index])) return schema;
|
|
708
|
+
const def = {
|
|
709
|
+
...schema._def,
|
|
710
|
+
options: marked
|
|
711
|
+
};
|
|
712
|
+
if (typeof schema.clone === "function") return schema.clone(def);
|
|
713
|
+
if ("optionsMap" in schema && schema.optionsMap instanceof Map) Object.assign(def, { optionsMap: new Map(Array.from(schema.optionsMap, ([key, option]) => [key, marked[options.indexOf(option)]])) });
|
|
714
|
+
const Union = schema.constructor;
|
|
715
|
+
return new Union(def);
|
|
716
|
+
}
|
|
697
717
|
const baseGetInputSchema = zod.z.object({ id: zod.z.string() });
|
|
698
718
|
const defaultGetInputSchema = zod.z.union([zod.z.string(), baseGetInputSchema]);
|
|
699
719
|
const baseExportInputSchema = zod.z.object({
|
|
@@ -1277,9 +1297,13 @@ function createCrudRouter(config) {
|
|
|
1277
1297
|
};
|
|
1278
1298
|
const { selectSchema, schema, upsertSchema, importSchema, updateSchema } = resolveSchemas(config, idField);
|
|
1279
1299
|
const entityOutputSchema = withCrudExtensionInput(selectSchema, config);
|
|
1300
|
+
const listInputSchema = config.listInputSchema ?? baseListInputSchema;
|
|
1301
|
+
const rowsOnlySchema = listSchemaWithOptionalTotal(listInputSchema);
|
|
1302
|
+
const optionalTotal = rowsOnlySchema !== listInputSchema;
|
|
1303
|
+
const resolvedListInputSchema = optionalTotal ? (raw) => (raw && typeof raw === "object" && "total" in raw && raw.total === false ? rowsOnlySchema : listInputSchema).parseAsync(raw) : listInputSchema;
|
|
1280
1304
|
const listOutputSchema = zod.z.object({
|
|
1281
1305
|
data: zod.z.array(entityOutputSchema),
|
|
1282
|
-
total: zod.z.number(),
|
|
1306
|
+
total: optionalTotal ? zod.z.number().optional() : zod.z.number(),
|
|
1283
1307
|
page: zod.z.number(),
|
|
1284
1308
|
perPage: zod.z.number(),
|
|
1285
1309
|
pageCount: zod.z.number()
|
|
@@ -1348,7 +1372,6 @@ function createCrudRouter(config) {
|
|
|
1348
1372
|
__crudOperation: "list"
|
|
1349
1373
|
});
|
|
1350
1374
|
const softDelete = resolveSoftDelete(softDeleteOption);
|
|
1351
|
-
const resolvedListInputSchema = config.listInputSchema ?? baseListInputSchema;
|
|
1352
1375
|
const resolvedGetInputSchema = config.getInputSchema ? zod.z.union([zod.z.string(), config.getInputSchema]) : defaultGetInputSchema;
|
|
1353
1376
|
const resolvedExportInputSchema = config.exportInputSchema ?? baseExportInputSchema;
|
|
1354
1377
|
const m = middleware;
|
|
@@ -1488,35 +1511,48 @@ function createCrudRouter(config) {
|
|
|
1488
1511
|
}) } : {},
|
|
1489
1512
|
list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
|
|
1490
1513
|
await withGuard(ctx, "list");
|
|
1491
|
-
const
|
|
1492
|
-
|
|
1514
|
+
const skipTotal = input[skipListTotal] === true;
|
|
1515
|
+
if (skipTotal) delete input[skipListTotal];
|
|
1516
|
+
const doList = async (listInput) => {
|
|
1517
|
+
const extra = await config.query?.({
|
|
1518
|
+
ctx,
|
|
1519
|
+
input: listInput,
|
|
1520
|
+
operation: "list"
|
|
1521
|
+
});
|
|
1522
|
+
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput);
|
|
1523
|
+
const where = combineConditions(baseWhere, extra?.where);
|
|
1493
1524
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1494
1525
|
let query = ctx.db.select().from(table).$dynamic();
|
|
1495
1526
|
if (where) query = query.where(where);
|
|
1496
|
-
const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, true);
|
|
1527
|
+
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
|
|
1497
1528
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1529
|
+
const data = Promise.resolve(query.limit(effectiveInput.perPage).offset(offset)).then((rows$1) => enrichCrudRows(ctx, config, idField, rows$1));
|
|
1530
|
+
const count = async () => {
|
|
1531
|
+
if (skipTotal) return void 0;
|
|
1532
|
+
let countQuery = ctx.db.select({ count: drizzle_orm.sql`count(*)::int` }).from(table).$dynamic();
|
|
1533
|
+
if (where) countQuery = countQuery.where(where);
|
|
1534
|
+
return (await countQuery)[0]?.count ?? 0;
|
|
1535
|
+
};
|
|
1536
|
+
const [rows, total] = await Promise.all([data, count()]);
|
|
1505
1537
|
return {
|
|
1506
|
-
data:
|
|
1507
|
-
total:
|
|
1538
|
+
data: rows,
|
|
1539
|
+
...total === void 0 ? {} : { total },
|
|
1508
1540
|
page: effectiveInput.page,
|
|
1509
1541
|
perPage: effectiveInput.perPage,
|
|
1510
|
-
pageCount: Math.ceil(
|
|
1542
|
+
pageCount: total === void 0 ? -1 : Math.ceil(total / effectiveInput.perPage)
|
|
1511
1543
|
};
|
|
1512
1544
|
};
|
|
1513
|
-
|
|
1514
|
-
|
|
1545
|
+
if (!m.list) return doList(input);
|
|
1546
|
+
const result = await m.list({
|
|
1515
1547
|
ctx,
|
|
1516
|
-
input
|
|
1517
|
-
next:
|
|
1548
|
+
input,
|
|
1549
|
+
next: (modifiedInput) => doList(modifiedInput ?? input)
|
|
1550
|
+
});
|
|
1551
|
+
if (optionalTotal && (skipTotal ? result.total !== void 0 || result.pageCount !== -1 : result.total === void 0 || result.pageCount === -1)) throw new __trpc_server.TRPCError({
|
|
1552
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
1553
|
+
message: "List middleware returned pagination inconsistent with the requested total"
|
|
1518
1554
|
});
|
|
1519
|
-
return
|
|
1555
|
+
return result;
|
|
1520
1556
|
}),
|
|
1521
1557
|
get: resolved.procedureFactory("get").input(resolvedGetInputSchema).output(entityOutputSchema.nullable()).query(async ({ ctx, input }) => {
|
|
1522
1558
|
await withGuard(ctx, "get");
|
|
@@ -1778,6 +1814,11 @@ function createCrudRouter(config) {
|
|
|
1778
1814
|
export: resolved.procedureFactory("export").input(resolvedExportInputSchema).output(exportOutputSchema).query(async ({ ctx, input }) => {
|
|
1779
1815
|
await withGuard(ctx, "export");
|
|
1780
1816
|
const doExport = async (exportInput$1) => {
|
|
1817
|
+
const extra = await config.query?.({
|
|
1818
|
+
ctx,
|
|
1819
|
+
input: exportInput$1,
|
|
1820
|
+
operation: "export"
|
|
1821
|
+
});
|
|
1781
1822
|
const columns = await querySearch(ctx, exportInput$1.search);
|
|
1782
1823
|
const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, {
|
|
1783
1824
|
page: 1,
|
|
@@ -1803,10 +1844,10 @@ function createCrudRouter(config) {
|
|
|
1803
1844
|
resolveDateRange: ctx.resolveDateRange
|
|
1804
1845
|
}) : void 0;
|
|
1805
1846
|
const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
|
|
1806
|
-
const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
|
|
1847
|
+
const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition, extra?.where));
|
|
1807
1848
|
let query = ctx.db.select().from(table).$dynamic();
|
|
1808
1849
|
if (where) query = query.where(where);
|
|
1809
|
-
const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, false);
|
|
1850
|
+
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, false);
|
|
1810
1851
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1811
1852
|
let countQuery = ctx.db.select({ count: drizzle_orm.sql`count(*)::int` }).from(table).$dynamic();
|
|
1812
1853
|
if (where) countQuery = countQuery.where(where);
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AnyColumn, SQL, Table } from "drizzle-orm";
|
|
2
2
|
import { PgTable } from "drizzle-orm/pg-core";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
import * as
|
|
4
|
+
import * as _trpc_server0 from "@trpc/server";
|
|
5
5
|
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
6
6
|
|
|
7
7
|
//#region src/lib/filter-columns.d.ts
|
|
@@ -40,13 +40,13 @@ interface Context {
|
|
|
40
40
|
db: PostgresJsDatabase<Record<string, never>>;
|
|
41
41
|
resolveDateRange?: DateRangeResolver;
|
|
42
42
|
}
|
|
43
|
-
declare const router:
|
|
43
|
+
declare const router: _trpc_server0.TRPCRouterBuilder<{
|
|
44
44
|
ctx: Context;
|
|
45
45
|
meta: object;
|
|
46
|
-
errorShape:
|
|
46
|
+
errorShape: _trpc_server0.TRPCDefaultErrorShape;
|
|
47
47
|
transformer: true;
|
|
48
48
|
}>;
|
|
49
|
-
declare const publicProcedure:
|
|
49
|
+
declare const publicProcedure: _trpc_server0.TRPCProcedureBuilder<Context, object, object, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, false>;
|
|
50
50
|
//#endregion
|
|
51
51
|
//#region src/types/config.d.ts
|
|
52
52
|
type CrudOperation = 'list' | 'get' | 'create' | 'update' | 'delete' | 'deleteMany' | 'updateMany' | 'upsert' | 'export' | 'import' | 'createMany';
|
|
@@ -168,6 +168,13 @@ interface ListResult<TSelect> {
|
|
|
168
168
|
perPage: number;
|
|
169
169
|
pageCount: number;
|
|
170
170
|
}
|
|
171
|
+
/** A passthrough index signature alone does not declare a total field. */
|
|
172
|
+
type DeclaredListTotal<TInput> = Extract<Required<TInput>, {
|
|
173
|
+
total: unknown;
|
|
174
|
+
}>['total'];
|
|
175
|
+
type ListPageResult<TSelect, TInput extends ListInput> = false extends DeclaredListTotal<TInput> ? Omit<ListResult<TSelect>, 'total'> & {
|
|
176
|
+
total?: number;
|
|
177
|
+
} : ListResult<TSelect>;
|
|
171
178
|
/**
|
|
172
179
|
* 单条查询输入类型
|
|
173
180
|
* - string: 兼容旧的 get(id) 调用
|
|
@@ -350,7 +357,7 @@ interface ImportInput {
|
|
|
350
357
|
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput> {
|
|
351
358
|
ctx: TContext;
|
|
352
359
|
input: TListInput;
|
|
353
|
-
next: (input?: TListInput) => Promise<
|
|
360
|
+
next: (input?: TListInput) => Promise<ListPageResult<TSelect, TListInput>>;
|
|
354
361
|
}
|
|
355
362
|
interface GetMiddlewareParams<TContext, TSelect, TGetInput extends GetInput = GetInput> {
|
|
356
363
|
ctx: TContext;
|
|
@@ -447,7 +454,7 @@ interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknow
|
|
|
447
454
|
/**
|
|
448
455
|
* 列表查询包装器
|
|
449
456
|
*/
|
|
450
|
-
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput>) => Promise<
|
|
457
|
+
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput>) => Promise<ListPageResult<TSelect, TListInput>>;
|
|
451
458
|
/** Batch counts use list authorization, but do not run row enrichment. */
|
|
452
459
|
counts?: (params: {
|
|
453
460
|
ctx: TContext;
|
|
@@ -650,14 +657,17 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
650
657
|
* 列表查询输入 Schema(可选)
|
|
651
658
|
* - 默认使用内置基础列表输入:page、perPage、sort、filters、joinOperator
|
|
652
659
|
* - 业务侧可以基于 baseListInputSchema.extend(...) 增加自定义参数
|
|
653
|
-
* -
|
|
660
|
+
* - 声明 total: z.boolean().optional() 后,list({ total: false }) 会跳过计数
|
|
661
|
+
* - 自定义字段会保留给 middleware.list 使用
|
|
654
662
|
*
|
|
655
663
|
* @example
|
|
656
664
|
* listInputSchema: baseListInputSchema.extend({
|
|
657
665
|
* include: z.object({ skus: z.boolean().optional() }).optional(),
|
|
658
666
|
* })
|
|
659
667
|
*/
|
|
660
|
-
listInputSchema?: z.ZodType<TListInput
|
|
668
|
+
listInputSchema?: z.ZodType<TListInput & {
|
|
669
|
+
total?: DeclaredListTotal<NoInfer<TListInput>>;
|
|
670
|
+
}>;
|
|
661
671
|
/**
|
|
662
672
|
* 单条查询输入 Schema(可选)
|
|
663
673
|
* - 默认兼容 get(id) 和 get({ id })
|
|
@@ -675,6 +685,20 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
675
685
|
* - 默认查询逻辑只读取基础字段,额外字段会保留给 middleware.export 使用
|
|
676
686
|
*/
|
|
677
687
|
exportInputSchema?: z.ZodType<TExportInput>;
|
|
688
|
+
/** Additional request conditions, ANDed before count/pagination/export limits.
|
|
689
|
+
* orderBy, when provided, replaces the normal ordering. Scope and guards still apply.
|
|
690
|
+
*/
|
|
691
|
+
query?: (params: {
|
|
692
|
+
ctx: TContext;
|
|
693
|
+
input: TListInput | TExportInput;
|
|
694
|
+
operation: 'list' | 'export';
|
|
695
|
+
}) => {
|
|
696
|
+
where?: SQL;
|
|
697
|
+
orderBy?: SQL[];
|
|
698
|
+
} | Promise<{
|
|
699
|
+
where?: SQL;
|
|
700
|
+
orderBy?: SQL[];
|
|
701
|
+
}>;
|
|
678
702
|
/**
|
|
679
703
|
* Procedure 配置(统一字段)
|
|
680
704
|
*
|
|
@@ -1147,12 +1171,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
|
|
|
1147
1171
|
} } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
|
|
1148
1172
|
//#endregion
|
|
1149
1173
|
//#region src/routers/index.d.ts
|
|
1150
|
-
declare const appRouter:
|
|
1174
|
+
declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
|
|
1151
1175
|
ctx: Context;
|
|
1152
1176
|
meta: object;
|
|
1153
|
-
errorShape:
|
|
1177
|
+
errorShape: _trpc_server0.TRPCDefaultErrorShape;
|
|
1154
1178
|
transformer: true;
|
|
1155
|
-
},
|
|
1179
|
+
}, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
|
|
1156
1180
|
type AppRouter = typeof appRouter;
|
|
1157
1181
|
//#endregion
|
|
1158
1182
|
export { type AnyProcedure, type AppRouter, type CountQuery, type CountsInput, type CountsResult, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportIssue, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router, tagFilterValueSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as _trpc_server2 from "@trpc/server";
|
|
2
2
|
import { AnyColumn, SQL, Table } from "drizzle-orm";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import superjson from "superjson";
|
|
@@ -41,13 +41,13 @@ interface Context {
|
|
|
41
41
|
db: PostgresJsDatabase<Record<string, never>>;
|
|
42
42
|
resolveDateRange?: DateRangeResolver;
|
|
43
43
|
}
|
|
44
|
-
declare const router:
|
|
44
|
+
declare const router: _trpc_server2.TRPCRouterBuilder<{
|
|
45
45
|
ctx: Context;
|
|
46
46
|
meta: object;
|
|
47
|
-
errorShape:
|
|
47
|
+
errorShape: _trpc_server2.TRPCDefaultErrorShape;
|
|
48
48
|
transformer: true;
|
|
49
49
|
}>;
|
|
50
|
-
declare const publicProcedure:
|
|
50
|
+
declare const publicProcedure: _trpc_server2.TRPCProcedureBuilder<Context, object, object, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, false>;
|
|
51
51
|
//#endregion
|
|
52
52
|
//#region src/types/config.d.ts
|
|
53
53
|
type CrudOperation = 'list' | 'get' | 'create' | 'update' | 'delete' | 'deleteMany' | 'updateMany' | 'upsert' | 'export' | 'import' | 'createMany';
|
|
@@ -169,6 +169,13 @@ interface ListResult<TSelect> {
|
|
|
169
169
|
perPage: number;
|
|
170
170
|
pageCount: number;
|
|
171
171
|
}
|
|
172
|
+
/** A passthrough index signature alone does not declare a total field. */
|
|
173
|
+
type DeclaredListTotal<TInput> = Extract<Required<TInput>, {
|
|
174
|
+
total: unknown;
|
|
175
|
+
}>['total'];
|
|
176
|
+
type ListPageResult<TSelect, TInput extends ListInput> = false extends DeclaredListTotal<TInput> ? Omit<ListResult<TSelect>, 'total'> & {
|
|
177
|
+
total?: number;
|
|
178
|
+
} : ListResult<TSelect>;
|
|
172
179
|
/**
|
|
173
180
|
* 单条查询输入类型
|
|
174
181
|
* - string: 兼容旧的 get(id) 调用
|
|
@@ -351,7 +358,7 @@ interface ImportInput {
|
|
|
351
358
|
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput> {
|
|
352
359
|
ctx: TContext;
|
|
353
360
|
input: TListInput;
|
|
354
|
-
next: (input?: TListInput) => Promise<
|
|
361
|
+
next: (input?: TListInput) => Promise<ListPageResult<TSelect, TListInput>>;
|
|
355
362
|
}
|
|
356
363
|
interface GetMiddlewareParams<TContext, TSelect, TGetInput extends GetInput = GetInput> {
|
|
357
364
|
ctx: TContext;
|
|
@@ -448,7 +455,7 @@ interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknow
|
|
|
448
455
|
/**
|
|
449
456
|
* 列表查询包装器
|
|
450
457
|
*/
|
|
451
|
-
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput>) => Promise<
|
|
458
|
+
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput>) => Promise<ListPageResult<TSelect, TListInput>>;
|
|
452
459
|
/** Batch counts use list authorization, but do not run row enrichment. */
|
|
453
460
|
counts?: (params: {
|
|
454
461
|
ctx: TContext;
|
|
@@ -651,14 +658,17 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
651
658
|
* 列表查询输入 Schema(可选)
|
|
652
659
|
* - 默认使用内置基础列表输入:page、perPage、sort、filters、joinOperator
|
|
653
660
|
* - 业务侧可以基于 baseListInputSchema.extend(...) 增加自定义参数
|
|
654
|
-
* -
|
|
661
|
+
* - 声明 total: z.boolean().optional() 后,list({ total: false }) 会跳过计数
|
|
662
|
+
* - 自定义字段会保留给 middleware.list 使用
|
|
655
663
|
*
|
|
656
664
|
* @example
|
|
657
665
|
* listInputSchema: baseListInputSchema.extend({
|
|
658
666
|
* include: z.object({ skus: z.boolean().optional() }).optional(),
|
|
659
667
|
* })
|
|
660
668
|
*/
|
|
661
|
-
listInputSchema?: z.ZodType<TListInput
|
|
669
|
+
listInputSchema?: z.ZodType<TListInput & {
|
|
670
|
+
total?: DeclaredListTotal<NoInfer<TListInput>>;
|
|
671
|
+
}>;
|
|
662
672
|
/**
|
|
663
673
|
* 单条查询输入 Schema(可选)
|
|
664
674
|
* - 默认兼容 get(id) 和 get({ id })
|
|
@@ -676,6 +686,20 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
676
686
|
* - 默认查询逻辑只读取基础字段,额外字段会保留给 middleware.export 使用
|
|
677
687
|
*/
|
|
678
688
|
exportInputSchema?: z.ZodType<TExportInput>;
|
|
689
|
+
/** Additional request conditions, ANDed before count/pagination/export limits.
|
|
690
|
+
* orderBy, when provided, replaces the normal ordering. Scope and guards still apply.
|
|
691
|
+
*/
|
|
692
|
+
query?: (params: {
|
|
693
|
+
ctx: TContext;
|
|
694
|
+
input: TListInput | TExportInput;
|
|
695
|
+
operation: 'list' | 'export';
|
|
696
|
+
}) => {
|
|
697
|
+
where?: SQL;
|
|
698
|
+
orderBy?: SQL[];
|
|
699
|
+
} | Promise<{
|
|
700
|
+
where?: SQL;
|
|
701
|
+
orderBy?: SQL[];
|
|
702
|
+
}>;
|
|
679
703
|
/**
|
|
680
704
|
* Procedure 配置(统一字段)
|
|
681
705
|
*
|
|
@@ -1148,12 +1172,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
|
|
|
1148
1172
|
} } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
|
|
1149
1173
|
//#endregion
|
|
1150
1174
|
//#region src/routers/index.d.ts
|
|
1151
|
-
declare const appRouter:
|
|
1175
|
+
declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
|
|
1152
1176
|
ctx: Context;
|
|
1153
1177
|
meta: object;
|
|
1154
|
-
errorShape:
|
|
1178
|
+
errorShape: _trpc_server2.TRPCDefaultErrorShape;
|
|
1155
1179
|
transformer: true;
|
|
1156
|
-
},
|
|
1180
|
+
}, _trpc_server2.TRPCDecorateCreateRouterOptions<{}>>;
|
|
1157
1181
|
type AppRouter = typeof appRouter;
|
|
1158
1182
|
//#endregion
|
|
1159
1183
|
export { type AnyProcedure, type AppRouter, type CountQuery, type CountsInput, type CountsResult, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportIssue, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router, tagFilterValueSchema };
|
package/dist/index.js
CHANGED
|
@@ -663,6 +663,26 @@ const baseListInputSchema = z.object({
|
|
|
663
663
|
filters: z.array(filterItemSchema).optional(),
|
|
664
664
|
joinOperator: z.enum(["and", "or"]).default("and")
|
|
665
665
|
});
|
|
666
|
+
const skipListTotal = Symbol("skipListTotal");
|
|
667
|
+
function listSchemaWithOptionalTotal(schema) {
|
|
668
|
+
if (isZodObject(schema)) return Object.hasOwn(schema.shape, "total") ? schema.transform((input) => input.total === false ? {
|
|
669
|
+
...input,
|
|
670
|
+
[skipListTotal]: true
|
|
671
|
+
} : input) : schema;
|
|
672
|
+
if (!("options" in schema) || !Array.isArray(schema.options)) return schema;
|
|
673
|
+
const options = schema.options;
|
|
674
|
+
if (!options.every((option) => typeof option?.parseAsync === "function")) return schema;
|
|
675
|
+
const marked = options.map(listSchemaWithOptionalTotal);
|
|
676
|
+
if (marked.every((option, index) => option === options[index])) return schema;
|
|
677
|
+
const def = {
|
|
678
|
+
...schema._def,
|
|
679
|
+
options: marked
|
|
680
|
+
};
|
|
681
|
+
if (typeof schema.clone === "function") return schema.clone(def);
|
|
682
|
+
if ("optionsMap" in schema && schema.optionsMap instanceof Map) Object.assign(def, { optionsMap: new Map(Array.from(schema.optionsMap, ([key, option]) => [key, marked[options.indexOf(option)]])) });
|
|
683
|
+
const Union = schema.constructor;
|
|
684
|
+
return new Union(def);
|
|
685
|
+
}
|
|
666
686
|
const baseGetInputSchema = z.object({ id: z.string() });
|
|
667
687
|
const defaultGetInputSchema = z.union([z.string(), baseGetInputSchema]);
|
|
668
688
|
const baseExportInputSchema = z.object({
|
|
@@ -1246,9 +1266,13 @@ function createCrudRouter(config) {
|
|
|
1246
1266
|
};
|
|
1247
1267
|
const { selectSchema, schema, upsertSchema, importSchema, updateSchema } = resolveSchemas(config, idField);
|
|
1248
1268
|
const entityOutputSchema = withCrudExtensionInput(selectSchema, config);
|
|
1269
|
+
const listInputSchema = config.listInputSchema ?? baseListInputSchema;
|
|
1270
|
+
const rowsOnlySchema = listSchemaWithOptionalTotal(listInputSchema);
|
|
1271
|
+
const optionalTotal = rowsOnlySchema !== listInputSchema;
|
|
1272
|
+
const resolvedListInputSchema = optionalTotal ? (raw) => (raw && typeof raw === "object" && "total" in raw && raw.total === false ? rowsOnlySchema : listInputSchema).parseAsync(raw) : listInputSchema;
|
|
1249
1273
|
const listOutputSchema = z.object({
|
|
1250
1274
|
data: z.array(entityOutputSchema),
|
|
1251
|
-
total: z.number(),
|
|
1275
|
+
total: optionalTotal ? z.number().optional() : z.number(),
|
|
1252
1276
|
page: z.number(),
|
|
1253
1277
|
perPage: z.number(),
|
|
1254
1278
|
pageCount: z.number()
|
|
@@ -1317,7 +1341,6 @@ function createCrudRouter(config) {
|
|
|
1317
1341
|
__crudOperation: "list"
|
|
1318
1342
|
});
|
|
1319
1343
|
const softDelete = resolveSoftDelete(softDeleteOption);
|
|
1320
|
-
const resolvedListInputSchema = config.listInputSchema ?? baseListInputSchema;
|
|
1321
1344
|
const resolvedGetInputSchema = config.getInputSchema ? z.union([z.string(), config.getInputSchema]) : defaultGetInputSchema;
|
|
1322
1345
|
const resolvedExportInputSchema = config.exportInputSchema ?? baseExportInputSchema;
|
|
1323
1346
|
const m = middleware;
|
|
@@ -1457,35 +1480,48 @@ function createCrudRouter(config) {
|
|
|
1457
1480
|
}) } : {},
|
|
1458
1481
|
list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
|
|
1459
1482
|
await withGuard(ctx, "list");
|
|
1460
|
-
const
|
|
1461
|
-
|
|
1483
|
+
const skipTotal = input[skipListTotal] === true;
|
|
1484
|
+
if (skipTotal) delete input[skipListTotal];
|
|
1485
|
+
const doList = async (listInput) => {
|
|
1486
|
+
const extra = await config.query?.({
|
|
1487
|
+
ctx,
|
|
1488
|
+
input: listInput,
|
|
1489
|
+
operation: "list"
|
|
1490
|
+
});
|
|
1491
|
+
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput);
|
|
1492
|
+
const where = combineConditions(baseWhere, extra?.where);
|
|
1462
1493
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1463
1494
|
let query = ctx.db.select().from(table).$dynamic();
|
|
1464
1495
|
if (where) query = query.where(where);
|
|
1465
|
-
const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, true);
|
|
1496
|
+
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
|
|
1466
1497
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1498
|
+
const data = Promise.resolve(query.limit(effectiveInput.perPage).offset(offset)).then((rows$1) => enrichCrudRows(ctx, config, idField, rows$1));
|
|
1499
|
+
const count = async () => {
|
|
1500
|
+
if (skipTotal) return void 0;
|
|
1501
|
+
let countQuery = ctx.db.select({ count: sql`count(*)::int` }).from(table).$dynamic();
|
|
1502
|
+
if (where) countQuery = countQuery.where(where);
|
|
1503
|
+
return (await countQuery)[0]?.count ?? 0;
|
|
1504
|
+
};
|
|
1505
|
+
const [rows, total] = await Promise.all([data, count()]);
|
|
1474
1506
|
return {
|
|
1475
|
-
data:
|
|
1476
|
-
total:
|
|
1507
|
+
data: rows,
|
|
1508
|
+
...total === void 0 ? {} : { total },
|
|
1477
1509
|
page: effectiveInput.page,
|
|
1478
1510
|
perPage: effectiveInput.perPage,
|
|
1479
|
-
pageCount: Math.ceil(
|
|
1511
|
+
pageCount: total === void 0 ? -1 : Math.ceil(total / effectiveInput.perPage)
|
|
1480
1512
|
};
|
|
1481
1513
|
};
|
|
1482
|
-
|
|
1483
|
-
|
|
1514
|
+
if (!m.list) return doList(input);
|
|
1515
|
+
const result = await m.list({
|
|
1484
1516
|
ctx,
|
|
1485
|
-
input
|
|
1486
|
-
next:
|
|
1517
|
+
input,
|
|
1518
|
+
next: (modifiedInput) => doList(modifiedInput ?? input)
|
|
1519
|
+
});
|
|
1520
|
+
if (optionalTotal && (skipTotal ? result.total !== void 0 || result.pageCount !== -1 : result.total === void 0 || result.pageCount === -1)) throw new TRPCError({
|
|
1521
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
1522
|
+
message: "List middleware returned pagination inconsistent with the requested total"
|
|
1487
1523
|
});
|
|
1488
|
-
return
|
|
1524
|
+
return result;
|
|
1489
1525
|
}),
|
|
1490
1526
|
get: resolved.procedureFactory("get").input(resolvedGetInputSchema).output(entityOutputSchema.nullable()).query(async ({ ctx, input }) => {
|
|
1491
1527
|
await withGuard(ctx, "get");
|
|
@@ -1747,6 +1783,11 @@ function createCrudRouter(config) {
|
|
|
1747
1783
|
export: resolved.procedureFactory("export").input(resolvedExportInputSchema).output(exportOutputSchema).query(async ({ ctx, input }) => {
|
|
1748
1784
|
await withGuard(ctx, "export");
|
|
1749
1785
|
const doExport = async (exportInput$1) => {
|
|
1786
|
+
const extra = await config.query?.({
|
|
1787
|
+
ctx,
|
|
1788
|
+
input: exportInput$1,
|
|
1789
|
+
operation: "export"
|
|
1790
|
+
});
|
|
1750
1791
|
const columns = await querySearch(ctx, exportInput$1.search);
|
|
1751
1792
|
const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, {
|
|
1752
1793
|
page: 1,
|
|
@@ -1772,10 +1813,10 @@ function createCrudRouter(config) {
|
|
|
1772
1813
|
resolveDateRange: ctx.resolveDateRange
|
|
1773
1814
|
}) : void 0;
|
|
1774
1815
|
const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
|
|
1775
|
-
const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
|
|
1816
|
+
const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition, extra?.where));
|
|
1776
1817
|
let query = ctx.db.select().from(table).$dynamic();
|
|
1777
1818
|
if (where) query = query.where(where);
|
|
1778
|
-
const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, false);
|
|
1819
|
+
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, false);
|
|
1779
1820
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1780
1821
|
let countQuery = ctx.db.select({ count: sql`count(*)::int` }).from(table).$dynamic();
|
|
1781
1822
|
if (where) countQuery = countQuery.where(where);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wordrhyme/auto-crud-server",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.4.0",
|
|
5
5
|
"description": "tRPC server utilities for auto-crud - automatic CRUD routers for Drizzle ORM",
|
|
6
6
|
"author": "wordrhyme",
|
|
7
7
|
"license": "MIT",
|
|
@@ -48,11 +48,11 @@
|
|
|
48
48
|
"typescript": "^5.9.3",
|
|
49
49
|
"vitest": "^4.0.18",
|
|
50
50
|
"zod": "^4.3.6",
|
|
51
|
-
"@internal/eslint-config": "0.3.0",
|
|
52
51
|
"@internal/tsconfig": "0.1.0",
|
|
52
|
+
"@internal/prettier-config": "0.0.1",
|
|
53
|
+
"@internal/eslint-config": "0.3.0",
|
|
53
54
|
"@internal/tsdown-config": "0.1.0",
|
|
54
|
-
"@internal/vitest-config": "0.1.0"
|
|
55
|
-
"@internal/prettier-config": "0.0.1"
|
|
55
|
+
"@internal/vitest-config": "0.1.0"
|
|
56
56
|
},
|
|
57
57
|
"prettier": "@internal/prettier-config",
|
|
58
58
|
"scripts": {
|