@wordrhyme/auto-crud-server 2.3.0 → 2.5.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 +43 -2
- package/dist/index.cjs +70 -22
- package/dist/index.d.cts +47 -23
- package/dist/index.d.ts +47 -23
- package/dist/index.js +70 -22
- package/package.json +2 -2
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
|
|
@@ -1360,3 +1365,39 @@ createCrudRouter({
|
|
|
1360
1365
|
```
|
|
1361
1366
|
|
|
1362
1367
|
`orderBy` 提供时替换默认排序;权限和作用域不会被覆盖。SQL 表达式必须通过当前数据库 capability 的治理机制构造,不能把其他租户或无权读取的数据带入派生条件。本扩展只作用于列表及导出;批量 counts 仍使用其原有输入契约。
|
|
1368
|
+
|
|
1369
|
+
### 服务端列表字段投影
|
|
1370
|
+
|
|
1371
|
+
`query.select` 可以在保留 list 权限、过滤和分页链路的情况下减少 SQL 查询列。
|
|
1372
|
+
至少选择一个本表列,键名沿用表字段名,并同时声明 `listSelectSchema`。投影列表只用
|
|
1373
|
+
`listSelectSchema` 校验,并跳过扩展字段补充。普通列表、get 和 export 沿用完整行和扩展字段。
|
|
1374
|
+
|
|
1375
|
+
```typescript
|
|
1376
|
+
const listSelectSchema = orderSelectSchema.pick({ id: true, lineItems: true }).strict();
|
|
1377
|
+
|
|
1378
|
+
createCrudRouter({
|
|
1379
|
+
table: orders,
|
|
1380
|
+
selectSchema: orderSelectSchema,
|
|
1381
|
+
listSelectSchema,
|
|
1382
|
+
listInputSchema: baseListInputSchema.extend({ snapshotOnly: z.boolean().optional() }),
|
|
1383
|
+
query: ({ input, operation }) =>
|
|
1384
|
+
operation === 'list' && 'snapshotOnly' in input && input.snapshotOnly
|
|
1385
|
+
? { select: { id: orders.id, lineItems: orders.lineItems } }
|
|
1386
|
+
: {},
|
|
1387
|
+
middleware: {
|
|
1388
|
+
list: async ({ next }) => {
|
|
1389
|
+
const result = await next();
|
|
1390
|
+
if (result.projected) {
|
|
1391
|
+
// 此分支只有 listSelectSchema 声明的字段,不能当作完整订单处理。
|
|
1392
|
+
return result;
|
|
1393
|
+
}
|
|
1394
|
+
// 此分支保留完整实体类型,可执行原有完整行后处理。
|
|
1395
|
+
return result;
|
|
1396
|
+
},
|
|
1397
|
+
},
|
|
1398
|
+
});
|
|
1399
|
+
```
|
|
1400
|
+
|
|
1401
|
+
`projected: true` 仅供服务端中间件区分结果类型,输出校验后会移除,不返回客户端。
|
|
1402
|
+
修改分页结果时保留该标记(例如返回 `{ ...result, data: nextRows }`),避免将投影行
|
|
1403
|
+
误当成完整行。未配置投影的 CRUD 继续使用原有完整行类型与响应格式。
|
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,13 +1297,21 @@ function createCrudRouter(config) {
|
|
|
1277
1297
|
};
|
|
1278
1298
|
const { selectSchema, schema, upsertSchema, importSchema, updateSchema } = resolveSchemas(config, idField);
|
|
1279
1299
|
const entityOutputSchema = withCrudExtensionInput(selectSchema, config);
|
|
1280
|
-
const
|
|
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;
|
|
1304
|
+
const fullListOutputSchema = 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()
|
|
1286
1310
|
});
|
|
1311
|
+
const listOutputSchema = config.listSelectSchema ? zod.z.discriminatedUnion("projected", [fullListOutputSchema.extend({ projected: zod.z.literal(false).optional() }), fullListOutputSchema.extend({
|
|
1312
|
+
data: zod.z.array(config.listSelectSchema),
|
|
1313
|
+
projected: zod.z.literal(true)
|
|
1314
|
+
})]).transform(({ projected: _projected,...page }) => page) : fullListOutputSchema;
|
|
1287
1315
|
const metadataOutputSchema = zod.z.object({
|
|
1288
1316
|
schema: zod.z.unknown().optional(),
|
|
1289
1317
|
fields: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
|
|
@@ -1348,7 +1376,6 @@ function createCrudRouter(config) {
|
|
|
1348
1376
|
__crudOperation: "list"
|
|
1349
1377
|
});
|
|
1350
1378
|
const softDelete = resolveSoftDelete(softDeleteOption);
|
|
1351
|
-
const resolvedListInputSchema = config.listInputSchema ?? baseListInputSchema;
|
|
1352
1379
|
const resolvedGetInputSchema = config.getInputSchema ? zod.z.union([zod.z.string(), config.getInputSchema]) : defaultGetInputSchema;
|
|
1353
1380
|
const resolvedExportInputSchema = config.exportInputSchema ?? baseExportInputSchema;
|
|
1354
1381
|
const m = middleware;
|
|
@@ -1488,41 +1515,62 @@ function createCrudRouter(config) {
|
|
|
1488
1515
|
}) } : {},
|
|
1489
1516
|
list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
|
|
1490
1517
|
await withGuard(ctx, "list");
|
|
1491
|
-
const
|
|
1518
|
+
const skipTotal = input[skipListTotal] === true;
|
|
1519
|
+
if (skipTotal) delete input[skipListTotal];
|
|
1520
|
+
const doList = async (listInput) => {
|
|
1492
1521
|
const extra = await config.query?.({
|
|
1493
1522
|
ctx,
|
|
1494
|
-
input: listInput
|
|
1523
|
+
input: listInput,
|
|
1495
1524
|
operation: "list"
|
|
1496
1525
|
});
|
|
1497
|
-
const
|
|
1526
|
+
const select = extra?.select;
|
|
1527
|
+
if (select) {
|
|
1528
|
+
if (!config.listSelectSchema) throw new __trpc_server.TRPCError({
|
|
1529
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
1530
|
+
message: "List projections require listSelectSchema"
|
|
1531
|
+
});
|
|
1532
|
+
const fields = Object.entries(select);
|
|
1533
|
+
const columns = (0, drizzle_orm.getTableColumns)(table);
|
|
1534
|
+
if (fields.length === 0 || fields.some(([key, column]) => !Object.hasOwn(columns, key) || columns[key] !== column)) throw new __trpc_server.TRPCError({
|
|
1535
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
1536
|
+
message: "List projections require table columns under their original field names"
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput);
|
|
1498
1540
|
const where = combineConditions(baseWhere, extra?.where);
|
|
1499
1541
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1500
|
-
let query = ctx.db.select().from(table).$dynamic();
|
|
1542
|
+
let query = (select ? ctx.db.select(select) : ctx.db.select()).from(table).$dynamic();
|
|
1501
1543
|
if (where) query = query.where(where);
|
|
1502
1544
|
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
|
|
1503
1545
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1546
|
+
const data = Promise.resolve(query.limit(effectiveInput.perPage).offset(offset)).then((rows$1) => select ? rows$1 : enrichCrudRows(ctx, config, idField, rows$1));
|
|
1547
|
+
const count = async () => {
|
|
1548
|
+
if (skipTotal) return void 0;
|
|
1549
|
+
let countQuery = ctx.db.select({ count: drizzle_orm.sql`count(*)::int` }).from(table).$dynamic();
|
|
1550
|
+
if (where) countQuery = countQuery.where(where);
|
|
1551
|
+
return (await countQuery)[0]?.count ?? 0;
|
|
1552
|
+
};
|
|
1553
|
+
const [rows, total] = await Promise.all([data, count()]);
|
|
1511
1554
|
return {
|
|
1512
|
-
data:
|
|
1513
|
-
|
|
1555
|
+
data: rows,
|
|
1556
|
+
...select ? { projected: true } : {},
|
|
1557
|
+
...total === void 0 ? {} : { total },
|
|
1514
1558
|
page: effectiveInput.page,
|
|
1515
1559
|
perPage: effectiveInput.perPage,
|
|
1516
|
-
pageCount: Math.ceil(
|
|
1560
|
+
pageCount: total === void 0 ? -1 : Math.ceil(total / effectiveInput.perPage)
|
|
1517
1561
|
};
|
|
1518
1562
|
};
|
|
1519
|
-
|
|
1520
|
-
|
|
1563
|
+
if (!m.list) return doList(input);
|
|
1564
|
+
const result = await m.list({
|
|
1521
1565
|
ctx,
|
|
1522
|
-
input
|
|
1523
|
-
next:
|
|
1566
|
+
input,
|
|
1567
|
+
next: (modifiedInput) => doList(modifiedInput ?? input)
|
|
1568
|
+
});
|
|
1569
|
+
if (optionalTotal && (skipTotal ? result.total !== void 0 || result.pageCount !== -1 : result.total === void 0 || result.pageCount === -1)) throw new __trpc_server.TRPCError({
|
|
1570
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
1571
|
+
message: "List middleware returned pagination inconsistent with the requested total"
|
|
1524
1572
|
});
|
|
1525
|
-
return
|
|
1573
|
+
return result;
|
|
1526
1574
|
}),
|
|
1527
1575
|
get: resolved.procedureFactory("get").input(resolvedGetInputSchema).output(entityOutputSchema.nullable()).query(async ({ ctx, input }) => {
|
|
1528
1576
|
await withGuard(ctx, "get");
|
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,21 @@ 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 ListPagination<TInput extends ListInput> = false extends DeclaredListTotal<TInput> ? Omit<ListResult<never>, 'data' | 'total'> & {
|
|
176
|
+
total?: number;
|
|
177
|
+
} : Omit<ListResult<never>, 'data'>;
|
|
178
|
+
/** `projected` is server-only: preserve it when transforming middleware results. */
|
|
179
|
+
type ListPageResult<TSelect, TInput extends ListInput, TListSelect = never> = ListPagination<TInput> & ({
|
|
180
|
+
data: TSelect[];
|
|
181
|
+
projected?: false;
|
|
182
|
+
} | ([TListSelect] extends [never] ? never : {
|
|
183
|
+
data: TListSelect[];
|
|
184
|
+
projected: true;
|
|
185
|
+
}));
|
|
171
186
|
/**
|
|
172
187
|
* 单条查询输入类型
|
|
173
188
|
* - string: 兼容旧的 get(id) 调用
|
|
@@ -347,10 +362,10 @@ interface ImportInput {
|
|
|
347
362
|
*/
|
|
348
363
|
onConflict?: 'skip' | 'upsert' | 'error';
|
|
349
364
|
}
|
|
350
|
-
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput> {
|
|
365
|
+
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput, TListSelect = never> {
|
|
351
366
|
ctx: TContext;
|
|
352
367
|
input: TListInput;
|
|
353
|
-
next: (input?: TListInput) => Promise<
|
|
368
|
+
next: (input?: TListInput) => Promise<ListPageResult<TSelect, TListInput, TListSelect>>;
|
|
354
369
|
}
|
|
355
370
|
interface GetMiddlewareParams<TContext, TSelect, TGetInput extends GetInput = GetInput> {
|
|
356
371
|
ctx: TContext;
|
|
@@ -443,11 +458,11 @@ interface CreateManyMiddlewareParams<TContext, TSelect, TInsert> {
|
|
|
443
458
|
* },
|
|
444
459
|
* }
|
|
445
460
|
*/
|
|
446
|
-
interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput> {
|
|
461
|
+
interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput, TListSelect = never> {
|
|
447
462
|
/**
|
|
448
463
|
* 列表查询包装器
|
|
449
464
|
*/
|
|
450
|
-
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput
|
|
465
|
+
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput, NoInfer<TListSelect>>) => Promise<ListPageResult<TSelect, TListInput, NoInfer<TListSelect>>>;
|
|
451
466
|
/** Batch counts use list authorization, but do not run row enrichment. */
|
|
452
467
|
counts?: (params: {
|
|
453
468
|
ctx: TContext;
|
|
@@ -562,6 +577,11 @@ type ProcedureFactory = (operation: CrudOperation) => AnyProcedure;
|
|
|
562
577
|
* }
|
|
563
578
|
*/
|
|
564
579
|
type ProcedureConfig = AnyProcedure | ProcedureMap | ProcedureFactory;
|
|
580
|
+
type CrudQueryOptions<TTable extends PgTable> = {
|
|
581
|
+
where?: SQL;
|
|
582
|
+
orderBy?: SQL[];
|
|
583
|
+
select?: Partial<TTable['_']['columns']>;
|
|
584
|
+
};
|
|
565
585
|
/**
|
|
566
586
|
* CRUD Router 配置
|
|
567
587
|
*
|
|
@@ -593,7 +613,7 @@ type ProcedureConfig = AnyProcedure | ProcedureMap | ProcedureFactory;
|
|
|
593
613
|
* authorize: (ctx, resource) => resource.ownerId === ctx.user.id,
|
|
594
614
|
* })
|
|
595
615
|
*/
|
|
596
|
-
interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput> {
|
|
616
|
+
interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput, TListSelect = never> {
|
|
597
617
|
/** Drizzle 表定义 */
|
|
598
618
|
table: TTable;
|
|
599
619
|
/**
|
|
@@ -646,18 +666,26 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
646
666
|
updateSchema?: z.ZodType<TUpdate>;
|
|
647
667
|
/** 查询返回 Schema */
|
|
648
668
|
selectSchema?: z.ZodType<TSelect>;
|
|
669
|
+
/** Row schema used only when query.select projects a list request.
|
|
670
|
+
* Other requests use selectSchema. In middleware, check result.projected before
|
|
671
|
+
* reading fields that may be absent from the projected row shape.
|
|
672
|
+
*/
|
|
673
|
+
listSelectSchema?: z.ZodType<TListSelect>;
|
|
649
674
|
/**
|
|
650
675
|
* 列表查询输入 Schema(可选)
|
|
651
676
|
* - 默认使用内置基础列表输入:page、perPage、sort、filters、joinOperator
|
|
652
677
|
* - 业务侧可以基于 baseListInputSchema.extend(...) 增加自定义参数
|
|
653
|
-
* -
|
|
678
|
+
* - 声明 total: z.boolean().optional() 后,list({ total: false }) 会跳过计数
|
|
679
|
+
* - 自定义字段会保留给 middleware.list 使用
|
|
654
680
|
*
|
|
655
681
|
* @example
|
|
656
682
|
* listInputSchema: baseListInputSchema.extend({
|
|
657
683
|
* include: z.object({ skus: z.boolean().optional() }).optional(),
|
|
658
684
|
* })
|
|
659
685
|
*/
|
|
660
|
-
listInputSchema?: z.ZodType<TListInput
|
|
686
|
+
listInputSchema?: z.ZodType<TListInput & {
|
|
687
|
+
total?: DeclaredListTotal<NoInfer<TListInput>>;
|
|
688
|
+
}>;
|
|
661
689
|
/**
|
|
662
690
|
* 单条查询输入 Schema(可选)
|
|
663
691
|
* - 默认兼容 get(id) 和 get({ id })
|
|
@@ -677,18 +705,14 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
677
705
|
exportInputSchema?: z.ZodType<TExportInput>;
|
|
678
706
|
/** Additional request conditions, ANDed before count/pagination/export limits.
|
|
679
707
|
* orderBy, when provided, replaces the normal ordering. Scope and guards still apply.
|
|
708
|
+
* For list only, select reads a nonempty subset of the table's columns under their
|
|
709
|
+
* original field names. It requires listSelectSchema and skips extension enrichment.
|
|
680
710
|
*/
|
|
681
711
|
query?: (params: {
|
|
682
712
|
ctx: TContext;
|
|
683
713
|
input: TListInput | TExportInput;
|
|
684
714
|
operation: 'list' | 'export';
|
|
685
|
-
}) =>
|
|
686
|
-
where?: SQL;
|
|
687
|
-
orderBy?: SQL[];
|
|
688
|
-
} | Promise<{
|
|
689
|
-
where?: SQL;
|
|
690
|
-
orderBy?: SQL[];
|
|
691
|
-
}>;
|
|
715
|
+
}) => CrudQueryOptions<TTable> | Promise<CrudQueryOptions<TTable>>;
|
|
692
716
|
/**
|
|
693
717
|
* Procedure 配置(统一字段)
|
|
694
718
|
*
|
|
@@ -852,7 +876,7 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
852
876
|
* }),
|
|
853
877
|
* }
|
|
854
878
|
*/
|
|
855
|
-
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput
|
|
879
|
+
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput, NoInfer<TListSelect>>;
|
|
856
880
|
}
|
|
857
881
|
interface CrudProcedures {
|
|
858
882
|
counts?: AnyProcedure;
|
|
@@ -1068,7 +1092,7 @@ declare const baseCountsInputSchema: z.ZodObject<{
|
|
|
1068
1092
|
* @typeParam TInsert - 创建输入类型
|
|
1069
1093
|
* @typeParam TUpdate - 更新输入类型
|
|
1070
1094
|
*/
|
|
1071
|
-
declare function createCrudRouter<TTable extends PgTable = PgTable, TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput>(config: CrudRouterConfig<TTable, TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput>): CrudRouterReturn;
|
|
1095
|
+
declare function createCrudRouter<TTable extends PgTable = PgTable, TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput, TListSelect = never>(config: CrudRouterConfig<TTable, TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput, TListSelect>): CrudRouterReturn;
|
|
1072
1096
|
//#endregion
|
|
1073
1097
|
//#region src/lib/middleware-helpers.d.ts
|
|
1074
1098
|
/**
|
|
@@ -1161,12 +1185,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
|
|
|
1161
1185
|
} } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
|
|
1162
1186
|
//#endregion
|
|
1163
1187
|
//#region src/routers/index.d.ts
|
|
1164
|
-
declare const appRouter:
|
|
1188
|
+
declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
|
|
1165
1189
|
ctx: Context;
|
|
1166
1190
|
meta: object;
|
|
1167
|
-
errorShape:
|
|
1191
|
+
errorShape: _trpc_server0.TRPCDefaultErrorShape;
|
|
1168
1192
|
transformer: true;
|
|
1169
|
-
},
|
|
1193
|
+
}, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
|
|
1170
1194
|
type AppRouter = typeof appRouter;
|
|
1171
1195
|
//#endregion
|
|
1172
1196
|
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_server0 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_server0.TRPCRouterBuilder<{
|
|
45
45
|
ctx: Context;
|
|
46
46
|
meta: object;
|
|
47
|
-
errorShape:
|
|
47
|
+
errorShape: _trpc_server0.TRPCDefaultErrorShape;
|
|
48
48
|
transformer: true;
|
|
49
49
|
}>;
|
|
50
|
-
declare const publicProcedure:
|
|
50
|
+
declare const publicProcedure: _trpc_server0.TRPCProcedureBuilder<Context, object, object, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.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,21 @@ 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 ListPagination<TInput extends ListInput> = false extends DeclaredListTotal<TInput> ? Omit<ListResult<never>, 'data' | 'total'> & {
|
|
177
|
+
total?: number;
|
|
178
|
+
} : Omit<ListResult<never>, 'data'>;
|
|
179
|
+
/** `projected` is server-only: preserve it when transforming middleware results. */
|
|
180
|
+
type ListPageResult<TSelect, TInput extends ListInput, TListSelect = never> = ListPagination<TInput> & ({
|
|
181
|
+
data: TSelect[];
|
|
182
|
+
projected?: false;
|
|
183
|
+
} | ([TListSelect] extends [never] ? never : {
|
|
184
|
+
data: TListSelect[];
|
|
185
|
+
projected: true;
|
|
186
|
+
}));
|
|
172
187
|
/**
|
|
173
188
|
* 单条查询输入类型
|
|
174
189
|
* - string: 兼容旧的 get(id) 调用
|
|
@@ -348,10 +363,10 @@ interface ImportInput {
|
|
|
348
363
|
*/
|
|
349
364
|
onConflict?: 'skip' | 'upsert' | 'error';
|
|
350
365
|
}
|
|
351
|
-
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput> {
|
|
366
|
+
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput, TListSelect = never> {
|
|
352
367
|
ctx: TContext;
|
|
353
368
|
input: TListInput;
|
|
354
|
-
next: (input?: TListInput) => Promise<
|
|
369
|
+
next: (input?: TListInput) => Promise<ListPageResult<TSelect, TListInput, TListSelect>>;
|
|
355
370
|
}
|
|
356
371
|
interface GetMiddlewareParams<TContext, TSelect, TGetInput extends GetInput = GetInput> {
|
|
357
372
|
ctx: TContext;
|
|
@@ -444,11 +459,11 @@ interface CreateManyMiddlewareParams<TContext, TSelect, TInsert> {
|
|
|
444
459
|
* },
|
|
445
460
|
* }
|
|
446
461
|
*/
|
|
447
|
-
interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput> {
|
|
462
|
+
interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput, TListSelect = never> {
|
|
448
463
|
/**
|
|
449
464
|
* 列表查询包装器
|
|
450
465
|
*/
|
|
451
|
-
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput
|
|
466
|
+
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput, NoInfer<TListSelect>>) => Promise<ListPageResult<TSelect, TListInput, NoInfer<TListSelect>>>;
|
|
452
467
|
/** Batch counts use list authorization, but do not run row enrichment. */
|
|
453
468
|
counts?: (params: {
|
|
454
469
|
ctx: TContext;
|
|
@@ -563,6 +578,11 @@ type ProcedureFactory = (operation: CrudOperation) => AnyProcedure;
|
|
|
563
578
|
* }
|
|
564
579
|
*/
|
|
565
580
|
type ProcedureConfig = AnyProcedure | ProcedureMap | ProcedureFactory;
|
|
581
|
+
type CrudQueryOptions<TTable extends PgTable> = {
|
|
582
|
+
where?: SQL;
|
|
583
|
+
orderBy?: SQL[];
|
|
584
|
+
select?: Partial<TTable['_']['columns']>;
|
|
585
|
+
};
|
|
566
586
|
/**
|
|
567
587
|
* CRUD Router 配置
|
|
568
588
|
*
|
|
@@ -594,7 +614,7 @@ type ProcedureConfig = AnyProcedure | ProcedureMap | ProcedureFactory;
|
|
|
594
614
|
* authorize: (ctx, resource) => resource.ownerId === ctx.user.id,
|
|
595
615
|
* })
|
|
596
616
|
*/
|
|
597
|
-
interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput> {
|
|
617
|
+
interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput, TListSelect = never> {
|
|
598
618
|
/** Drizzle 表定义 */
|
|
599
619
|
table: TTable;
|
|
600
620
|
/**
|
|
@@ -647,18 +667,26 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
647
667
|
updateSchema?: z.ZodType<TUpdate>;
|
|
648
668
|
/** 查询返回 Schema */
|
|
649
669
|
selectSchema?: z.ZodType<TSelect>;
|
|
670
|
+
/** Row schema used only when query.select projects a list request.
|
|
671
|
+
* Other requests use selectSchema. In middleware, check result.projected before
|
|
672
|
+
* reading fields that may be absent from the projected row shape.
|
|
673
|
+
*/
|
|
674
|
+
listSelectSchema?: z.ZodType<TListSelect>;
|
|
650
675
|
/**
|
|
651
676
|
* 列表查询输入 Schema(可选)
|
|
652
677
|
* - 默认使用内置基础列表输入:page、perPage、sort、filters、joinOperator
|
|
653
678
|
* - 业务侧可以基于 baseListInputSchema.extend(...) 增加自定义参数
|
|
654
|
-
* -
|
|
679
|
+
* - 声明 total: z.boolean().optional() 后,list({ total: false }) 会跳过计数
|
|
680
|
+
* - 自定义字段会保留给 middleware.list 使用
|
|
655
681
|
*
|
|
656
682
|
* @example
|
|
657
683
|
* listInputSchema: baseListInputSchema.extend({
|
|
658
684
|
* include: z.object({ skus: z.boolean().optional() }).optional(),
|
|
659
685
|
* })
|
|
660
686
|
*/
|
|
661
|
-
listInputSchema?: z.ZodType<TListInput
|
|
687
|
+
listInputSchema?: z.ZodType<TListInput & {
|
|
688
|
+
total?: DeclaredListTotal<NoInfer<TListInput>>;
|
|
689
|
+
}>;
|
|
662
690
|
/**
|
|
663
691
|
* 单条查询输入 Schema(可选)
|
|
664
692
|
* - 默认兼容 get(id) 和 get({ id })
|
|
@@ -678,18 +706,14 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
678
706
|
exportInputSchema?: z.ZodType<TExportInput>;
|
|
679
707
|
/** Additional request conditions, ANDed before count/pagination/export limits.
|
|
680
708
|
* orderBy, when provided, replaces the normal ordering. Scope and guards still apply.
|
|
709
|
+
* For list only, select reads a nonempty subset of the table's columns under their
|
|
710
|
+
* original field names. It requires listSelectSchema and skips extension enrichment.
|
|
681
711
|
*/
|
|
682
712
|
query?: (params: {
|
|
683
713
|
ctx: TContext;
|
|
684
714
|
input: TListInput | TExportInput;
|
|
685
715
|
operation: 'list' | 'export';
|
|
686
|
-
}) =>
|
|
687
|
-
where?: SQL;
|
|
688
|
-
orderBy?: SQL[];
|
|
689
|
-
} | Promise<{
|
|
690
|
-
where?: SQL;
|
|
691
|
-
orderBy?: SQL[];
|
|
692
|
-
}>;
|
|
716
|
+
}) => CrudQueryOptions<TTable> | Promise<CrudQueryOptions<TTable>>;
|
|
693
717
|
/**
|
|
694
718
|
* Procedure 配置(统一字段)
|
|
695
719
|
*
|
|
@@ -853,7 +877,7 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
853
877
|
* }),
|
|
854
878
|
* }
|
|
855
879
|
*/
|
|
856
|
-
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput
|
|
880
|
+
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput, NoInfer<TListSelect>>;
|
|
857
881
|
}
|
|
858
882
|
interface CrudProcedures {
|
|
859
883
|
counts?: AnyProcedure;
|
|
@@ -1069,7 +1093,7 @@ declare const baseCountsInputSchema: z.ZodObject<{
|
|
|
1069
1093
|
* @typeParam TInsert - 创建输入类型
|
|
1070
1094
|
* @typeParam TUpdate - 更新输入类型
|
|
1071
1095
|
*/
|
|
1072
|
-
declare function createCrudRouter<TTable extends PgTable = PgTable, TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput>(config: CrudRouterConfig<TTable, TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput>): CrudRouterReturn;
|
|
1096
|
+
declare function createCrudRouter<TTable extends PgTable = PgTable, TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown, TListInput extends ListInput = ListInput, TGetInput extends GetInput = GetInput, TExportInput extends ExportInput = ExportInput, TListSelect = never>(config: CrudRouterConfig<TTable, TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput, TListSelect>): CrudRouterReturn;
|
|
1073
1097
|
//#endregion
|
|
1074
1098
|
//#region src/lib/middleware-helpers.d.ts
|
|
1075
1099
|
/**
|
|
@@ -1162,12 +1186,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
|
|
|
1162
1186
|
} } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
|
|
1163
1187
|
//#endregion
|
|
1164
1188
|
//#region src/routers/index.d.ts
|
|
1165
|
-
declare const appRouter:
|
|
1189
|
+
declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
|
|
1166
1190
|
ctx: Context;
|
|
1167
1191
|
meta: object;
|
|
1168
|
-
errorShape:
|
|
1192
|
+
errorShape: _trpc_server0.TRPCDefaultErrorShape;
|
|
1169
1193
|
transformer: true;
|
|
1170
|
-
},
|
|
1194
|
+
}, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
|
|
1171
1195
|
type AppRouter = typeof appRouter;
|
|
1172
1196
|
//#endregion
|
|
1173
1197
|
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,13 +1266,21 @@ function createCrudRouter(config) {
|
|
|
1246
1266
|
};
|
|
1247
1267
|
const { selectSchema, schema, upsertSchema, importSchema, updateSchema } = resolveSchemas(config, idField);
|
|
1248
1268
|
const entityOutputSchema = withCrudExtensionInput(selectSchema, config);
|
|
1249
|
-
const
|
|
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;
|
|
1273
|
+
const fullListOutputSchema = 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()
|
|
1255
1279
|
});
|
|
1280
|
+
const listOutputSchema = config.listSelectSchema ? z.discriminatedUnion("projected", [fullListOutputSchema.extend({ projected: z.literal(false).optional() }), fullListOutputSchema.extend({
|
|
1281
|
+
data: z.array(config.listSelectSchema),
|
|
1282
|
+
projected: z.literal(true)
|
|
1283
|
+
})]).transform(({ projected: _projected,...page }) => page) : fullListOutputSchema;
|
|
1256
1284
|
const metadataOutputSchema = z.object({
|
|
1257
1285
|
schema: z.unknown().optional(),
|
|
1258
1286
|
fields: z.record(z.string(), z.unknown()).optional(),
|
|
@@ -1317,7 +1345,6 @@ function createCrudRouter(config) {
|
|
|
1317
1345
|
__crudOperation: "list"
|
|
1318
1346
|
});
|
|
1319
1347
|
const softDelete = resolveSoftDelete(softDeleteOption);
|
|
1320
|
-
const resolvedListInputSchema = config.listInputSchema ?? baseListInputSchema;
|
|
1321
1348
|
const resolvedGetInputSchema = config.getInputSchema ? z.union([z.string(), config.getInputSchema]) : defaultGetInputSchema;
|
|
1322
1349
|
const resolvedExportInputSchema = config.exportInputSchema ?? baseExportInputSchema;
|
|
1323
1350
|
const m = middleware;
|
|
@@ -1457,41 +1484,62 @@ function createCrudRouter(config) {
|
|
|
1457
1484
|
}) } : {},
|
|
1458
1485
|
list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
|
|
1459
1486
|
await withGuard(ctx, "list");
|
|
1460
|
-
const
|
|
1487
|
+
const skipTotal = input[skipListTotal] === true;
|
|
1488
|
+
if (skipTotal) delete input[skipListTotal];
|
|
1489
|
+
const doList = async (listInput) => {
|
|
1461
1490
|
const extra = await config.query?.({
|
|
1462
1491
|
ctx,
|
|
1463
|
-
input: listInput
|
|
1492
|
+
input: listInput,
|
|
1464
1493
|
operation: "list"
|
|
1465
1494
|
});
|
|
1466
|
-
const
|
|
1495
|
+
const select = extra?.select;
|
|
1496
|
+
if (select) {
|
|
1497
|
+
if (!config.listSelectSchema) throw new TRPCError({
|
|
1498
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
1499
|
+
message: "List projections require listSelectSchema"
|
|
1500
|
+
});
|
|
1501
|
+
const fields = Object.entries(select);
|
|
1502
|
+
const columns = getTableColumns(table);
|
|
1503
|
+
if (fields.length === 0 || fields.some(([key, column]) => !Object.hasOwn(columns, key) || columns[key] !== column)) throw new TRPCError({
|
|
1504
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
1505
|
+
message: "List projections require table columns under their original field names"
|
|
1506
|
+
});
|
|
1507
|
+
}
|
|
1508
|
+
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput);
|
|
1467
1509
|
const where = combineConditions(baseWhere, extra?.where);
|
|
1468
1510
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1469
|
-
let query = ctx.db.select().from(table).$dynamic();
|
|
1511
|
+
let query = (select ? ctx.db.select(select) : ctx.db.select()).from(table).$dynamic();
|
|
1470
1512
|
if (where) query = query.where(where);
|
|
1471
1513
|
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
|
|
1472
1514
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1515
|
+
const data = Promise.resolve(query.limit(effectiveInput.perPage).offset(offset)).then((rows$1) => select ? rows$1 : enrichCrudRows(ctx, config, idField, rows$1));
|
|
1516
|
+
const count = async () => {
|
|
1517
|
+
if (skipTotal) return void 0;
|
|
1518
|
+
let countQuery = ctx.db.select({ count: sql`count(*)::int` }).from(table).$dynamic();
|
|
1519
|
+
if (where) countQuery = countQuery.where(where);
|
|
1520
|
+
return (await countQuery)[0]?.count ?? 0;
|
|
1521
|
+
};
|
|
1522
|
+
const [rows, total] = await Promise.all([data, count()]);
|
|
1480
1523
|
return {
|
|
1481
|
-
data:
|
|
1482
|
-
|
|
1524
|
+
data: rows,
|
|
1525
|
+
...select ? { projected: true } : {},
|
|
1526
|
+
...total === void 0 ? {} : { total },
|
|
1483
1527
|
page: effectiveInput.page,
|
|
1484
1528
|
perPage: effectiveInput.perPage,
|
|
1485
|
-
pageCount: Math.ceil(
|
|
1529
|
+
pageCount: total === void 0 ? -1 : Math.ceil(total / effectiveInput.perPage)
|
|
1486
1530
|
};
|
|
1487
1531
|
};
|
|
1488
|
-
|
|
1489
|
-
|
|
1532
|
+
if (!m.list) return doList(input);
|
|
1533
|
+
const result = await m.list({
|
|
1490
1534
|
ctx,
|
|
1491
|
-
input
|
|
1492
|
-
next:
|
|
1535
|
+
input,
|
|
1536
|
+
next: (modifiedInput) => doList(modifiedInput ?? input)
|
|
1537
|
+
});
|
|
1538
|
+
if (optionalTotal && (skipTotal ? result.total !== void 0 || result.pageCount !== -1 : result.total === void 0 || result.pageCount === -1)) throw new TRPCError({
|
|
1539
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
1540
|
+
message: "List middleware returned pagination inconsistent with the requested total"
|
|
1493
1541
|
});
|
|
1494
|
-
return
|
|
1542
|
+
return result;
|
|
1495
1543
|
}),
|
|
1496
1544
|
get: resolved.procedureFactory("get").input(resolvedGetInputSchema).output(entityOutputSchema.nullable()).query(async ({ ctx, input }) => {
|
|
1497
1545
|
await withGuard(ctx, "get");
|
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.5.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,8 +48,8 @@
|
|
|
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/prettier-config": "0.0.1",
|
|
52
|
+
"@internal/eslint-config": "0.3.0",
|
|
53
53
|
"@internal/tsconfig": "0.1.0",
|
|
54
54
|
"@internal/tsdown-config": "0.1.0",
|
|
55
55
|
"@internal/vitest-config": "0.1.0"
|