@wordrhyme/auto-crud-server 2.4.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 +36 -0
- package/dist/index.cjs +21 -3
- package/dist/index.d.cts +30 -16
- package/dist/index.d.ts +37 -23
- package/dist/index.js +21 -3
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1365,3 +1365,39 @@ createCrudRouter({
|
|
|
1365
1365
|
```
|
|
1366
1366
|
|
|
1367
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
|
@@ -1301,13 +1301,17 @@ function createCrudRouter(config) {
|
|
|
1301
1301
|
const rowsOnlySchema = listSchemaWithOptionalTotal(listInputSchema);
|
|
1302
1302
|
const optionalTotal = rowsOnlySchema !== listInputSchema;
|
|
1303
1303
|
const resolvedListInputSchema = optionalTotal ? (raw) => (raw && typeof raw === "object" && "total" in raw && raw.total === false ? rowsOnlySchema : listInputSchema).parseAsync(raw) : listInputSchema;
|
|
1304
|
-
const
|
|
1304
|
+
const fullListOutputSchema = zod.z.object({
|
|
1305
1305
|
data: zod.z.array(entityOutputSchema),
|
|
1306
1306
|
total: optionalTotal ? zod.z.number().optional() : zod.z.number(),
|
|
1307
1307
|
page: zod.z.number(),
|
|
1308
1308
|
perPage: zod.z.number(),
|
|
1309
1309
|
pageCount: zod.z.number()
|
|
1310
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;
|
|
1311
1315
|
const metadataOutputSchema = zod.z.object({
|
|
1312
1316
|
schema: zod.z.unknown().optional(),
|
|
1313
1317
|
fields: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
|
|
@@ -1519,14 +1523,27 @@ function createCrudRouter(config) {
|
|
|
1519
1523
|
input: listInput,
|
|
1520
1524
|
operation: "list"
|
|
1521
1525
|
});
|
|
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
|
+
}
|
|
1522
1539
|
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput);
|
|
1523
1540
|
const where = combineConditions(baseWhere, extra?.where);
|
|
1524
1541
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1525
|
-
let query = ctx.db.select().from(table).$dynamic();
|
|
1542
|
+
let query = (select ? ctx.db.select(select) : ctx.db.select()).from(table).$dynamic();
|
|
1526
1543
|
if (where) query = query.where(where);
|
|
1527
1544
|
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
|
|
1528
1545
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1529
|
-
const data = Promise.resolve(query.limit(effectiveInput.perPage).offset(offset)).then((rows$1) => enrichCrudRows(ctx, config, idField, rows$1));
|
|
1546
|
+
const data = Promise.resolve(query.limit(effectiveInput.perPage).offset(offset)).then((rows$1) => select ? rows$1 : enrichCrudRows(ctx, config, idField, rows$1));
|
|
1530
1547
|
const count = async () => {
|
|
1531
1548
|
if (skipTotal) return void 0;
|
|
1532
1549
|
let countQuery = ctx.db.select({ count: drizzle_orm.sql`count(*)::int` }).from(table).$dynamic();
|
|
@@ -1536,6 +1553,7 @@ function createCrudRouter(config) {
|
|
|
1536
1553
|
const [rows, total] = await Promise.all([data, count()]);
|
|
1537
1554
|
return {
|
|
1538
1555
|
data: rows,
|
|
1556
|
+
...select ? { projected: true } : {},
|
|
1539
1557
|
...total === void 0 ? {} : { total },
|
|
1540
1558
|
page: effectiveInput.page,
|
|
1541
1559
|
perPage: effectiveInput.perPage,
|
package/dist/index.d.cts
CHANGED
|
@@ -172,9 +172,17 @@ interface ListResult<TSelect> {
|
|
|
172
172
|
type DeclaredListTotal<TInput> = Extract<Required<TInput>, {
|
|
173
173
|
total: unknown;
|
|
174
174
|
}>['total'];
|
|
175
|
-
type
|
|
175
|
+
type ListPagination<TInput extends ListInput> = false extends DeclaredListTotal<TInput> ? Omit<ListResult<never>, 'data' | 'total'> & {
|
|
176
176
|
total?: number;
|
|
177
|
-
} : ListResult<
|
|
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
|
+
}));
|
|
178
186
|
/**
|
|
179
187
|
* 单条查询输入类型
|
|
180
188
|
* - string: 兼容旧的 get(id) 调用
|
|
@@ -354,10 +362,10 @@ interface ImportInput {
|
|
|
354
362
|
*/
|
|
355
363
|
onConflict?: 'skip' | 'upsert' | 'error';
|
|
356
364
|
}
|
|
357
|
-
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput> {
|
|
365
|
+
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput, TListSelect = never> {
|
|
358
366
|
ctx: TContext;
|
|
359
367
|
input: TListInput;
|
|
360
|
-
next: (input?: TListInput) => Promise<ListPageResult<TSelect, TListInput>>;
|
|
368
|
+
next: (input?: TListInput) => Promise<ListPageResult<TSelect, TListInput, TListSelect>>;
|
|
361
369
|
}
|
|
362
370
|
interface GetMiddlewareParams<TContext, TSelect, TGetInput extends GetInput = GetInput> {
|
|
363
371
|
ctx: TContext;
|
|
@@ -450,11 +458,11 @@ interface CreateManyMiddlewareParams<TContext, TSelect, TInsert> {
|
|
|
450
458
|
* },
|
|
451
459
|
* }
|
|
452
460
|
*/
|
|
453
|
-
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> {
|
|
454
462
|
/**
|
|
455
463
|
* 列表查询包装器
|
|
456
464
|
*/
|
|
457
|
-
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput
|
|
465
|
+
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput, NoInfer<TListSelect>>) => Promise<ListPageResult<TSelect, TListInput, NoInfer<TListSelect>>>;
|
|
458
466
|
/** Batch counts use list authorization, but do not run row enrichment. */
|
|
459
467
|
counts?: (params: {
|
|
460
468
|
ctx: TContext;
|
|
@@ -569,6 +577,11 @@ type ProcedureFactory = (operation: CrudOperation) => AnyProcedure;
|
|
|
569
577
|
* }
|
|
570
578
|
*/
|
|
571
579
|
type ProcedureConfig = AnyProcedure | ProcedureMap | ProcedureFactory;
|
|
580
|
+
type CrudQueryOptions<TTable extends PgTable> = {
|
|
581
|
+
where?: SQL;
|
|
582
|
+
orderBy?: SQL[];
|
|
583
|
+
select?: Partial<TTable['_']['columns']>;
|
|
584
|
+
};
|
|
572
585
|
/**
|
|
573
586
|
* CRUD Router 配置
|
|
574
587
|
*
|
|
@@ -600,7 +613,7 @@ type ProcedureConfig = AnyProcedure | ProcedureMap | ProcedureFactory;
|
|
|
600
613
|
* authorize: (ctx, resource) => resource.ownerId === ctx.user.id,
|
|
601
614
|
* })
|
|
602
615
|
*/
|
|
603
|
-
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> {
|
|
604
617
|
/** Drizzle 表定义 */
|
|
605
618
|
table: TTable;
|
|
606
619
|
/**
|
|
@@ -653,6 +666,11 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
653
666
|
updateSchema?: z.ZodType<TUpdate>;
|
|
654
667
|
/** 查询返回 Schema */
|
|
655
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>;
|
|
656
674
|
/**
|
|
657
675
|
* 列表查询输入 Schema(可选)
|
|
658
676
|
* - 默认使用内置基础列表输入:page、perPage、sort、filters、joinOperator
|
|
@@ -687,18 +705,14 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
687
705
|
exportInputSchema?: z.ZodType<TExportInput>;
|
|
688
706
|
/** Additional request conditions, ANDed before count/pagination/export limits.
|
|
689
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.
|
|
690
710
|
*/
|
|
691
711
|
query?: (params: {
|
|
692
712
|
ctx: TContext;
|
|
693
713
|
input: TListInput | TExportInput;
|
|
694
714
|
operation: 'list' | 'export';
|
|
695
|
-
}) =>
|
|
696
|
-
where?: SQL;
|
|
697
|
-
orderBy?: SQL[];
|
|
698
|
-
} | Promise<{
|
|
699
|
-
where?: SQL;
|
|
700
|
-
orderBy?: SQL[];
|
|
701
|
-
}>;
|
|
715
|
+
}) => CrudQueryOptions<TTable> | Promise<CrudQueryOptions<TTable>>;
|
|
702
716
|
/**
|
|
703
717
|
* Procedure 配置(统一字段)
|
|
704
718
|
*
|
|
@@ -862,7 +876,7 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
862
876
|
* }),
|
|
863
877
|
* }
|
|
864
878
|
*/
|
|
865
|
-
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput
|
|
879
|
+
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput, NoInfer<TListSelect>>;
|
|
866
880
|
}
|
|
867
881
|
interface CrudProcedures {
|
|
868
882
|
counts?: AnyProcedure;
|
|
@@ -1078,7 +1092,7 @@ declare const baseCountsInputSchema: z.ZodObject<{
|
|
|
1078
1092
|
* @typeParam TInsert - 创建输入类型
|
|
1079
1093
|
* @typeParam TUpdate - 更新输入类型
|
|
1080
1094
|
*/
|
|
1081
|
-
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;
|
|
1082
1096
|
//#endregion
|
|
1083
1097
|
//#region src/lib/middleware-helpers.d.ts
|
|
1084
1098
|
/**
|
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';
|
|
@@ -173,9 +173,17 @@ interface ListResult<TSelect> {
|
|
|
173
173
|
type DeclaredListTotal<TInput> = Extract<Required<TInput>, {
|
|
174
174
|
total: unknown;
|
|
175
175
|
}>['total'];
|
|
176
|
-
type
|
|
176
|
+
type ListPagination<TInput extends ListInput> = false extends DeclaredListTotal<TInput> ? Omit<ListResult<never>, 'data' | 'total'> & {
|
|
177
177
|
total?: number;
|
|
178
|
-
} : ListResult<
|
|
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
|
+
}));
|
|
179
187
|
/**
|
|
180
188
|
* 单条查询输入类型
|
|
181
189
|
* - string: 兼容旧的 get(id) 调用
|
|
@@ -355,10 +363,10 @@ interface ImportInput {
|
|
|
355
363
|
*/
|
|
356
364
|
onConflict?: 'skip' | 'upsert' | 'error';
|
|
357
365
|
}
|
|
358
|
-
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput> {
|
|
366
|
+
interface ListMiddlewareParams<TContext, TSelect, TListInput extends ListInput = ListInput, TListSelect = never> {
|
|
359
367
|
ctx: TContext;
|
|
360
368
|
input: TListInput;
|
|
361
|
-
next: (input?: TListInput) => Promise<ListPageResult<TSelect, TListInput>>;
|
|
369
|
+
next: (input?: TListInput) => Promise<ListPageResult<TSelect, TListInput, TListSelect>>;
|
|
362
370
|
}
|
|
363
371
|
interface GetMiddlewareParams<TContext, TSelect, TGetInput extends GetInput = GetInput> {
|
|
364
372
|
ctx: TContext;
|
|
@@ -451,11 +459,11 @@ interface CreateManyMiddlewareParams<TContext, TSelect, TInsert> {
|
|
|
451
459
|
* },
|
|
452
460
|
* }
|
|
453
461
|
*/
|
|
454
|
-
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> {
|
|
455
463
|
/**
|
|
456
464
|
* 列表查询包装器
|
|
457
465
|
*/
|
|
458
|
-
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput
|
|
466
|
+
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput, NoInfer<TListSelect>>) => Promise<ListPageResult<TSelect, TListInput, NoInfer<TListSelect>>>;
|
|
459
467
|
/** Batch counts use list authorization, but do not run row enrichment. */
|
|
460
468
|
counts?: (params: {
|
|
461
469
|
ctx: TContext;
|
|
@@ -570,6 +578,11 @@ type ProcedureFactory = (operation: CrudOperation) => AnyProcedure;
|
|
|
570
578
|
* }
|
|
571
579
|
*/
|
|
572
580
|
type ProcedureConfig = AnyProcedure | ProcedureMap | ProcedureFactory;
|
|
581
|
+
type CrudQueryOptions<TTable extends PgTable> = {
|
|
582
|
+
where?: SQL;
|
|
583
|
+
orderBy?: SQL[];
|
|
584
|
+
select?: Partial<TTable['_']['columns']>;
|
|
585
|
+
};
|
|
573
586
|
/**
|
|
574
587
|
* CRUD Router 配置
|
|
575
588
|
*
|
|
@@ -601,7 +614,7 @@ type ProcedureConfig = AnyProcedure | ProcedureMap | ProcedureFactory;
|
|
|
601
614
|
* authorize: (ctx, resource) => resource.ownerId === ctx.user.id,
|
|
602
615
|
* })
|
|
603
616
|
*/
|
|
604
|
-
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> {
|
|
605
618
|
/** Drizzle 表定义 */
|
|
606
619
|
table: TTable;
|
|
607
620
|
/**
|
|
@@ -654,6 +667,11 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
654
667
|
updateSchema?: z.ZodType<TUpdate>;
|
|
655
668
|
/** 查询返回 Schema */
|
|
656
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>;
|
|
657
675
|
/**
|
|
658
676
|
* 列表查询输入 Schema(可选)
|
|
659
677
|
* - 默认使用内置基础列表输入:page、perPage、sort、filters、joinOperator
|
|
@@ -688,18 +706,14 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
688
706
|
exportInputSchema?: z.ZodType<TExportInput>;
|
|
689
707
|
/** Additional request conditions, ANDed before count/pagination/export limits.
|
|
690
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.
|
|
691
711
|
*/
|
|
692
712
|
query?: (params: {
|
|
693
713
|
ctx: TContext;
|
|
694
714
|
input: TListInput | TExportInput;
|
|
695
715
|
operation: 'list' | 'export';
|
|
696
|
-
}) =>
|
|
697
|
-
where?: SQL;
|
|
698
|
-
orderBy?: SQL[];
|
|
699
|
-
} | Promise<{
|
|
700
|
-
where?: SQL;
|
|
701
|
-
orderBy?: SQL[];
|
|
702
|
-
}>;
|
|
716
|
+
}) => CrudQueryOptions<TTable> | Promise<CrudQueryOptions<TTable>>;
|
|
703
717
|
/**
|
|
704
718
|
* Procedure 配置(统一字段)
|
|
705
719
|
*
|
|
@@ -863,7 +877,7 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
863
877
|
* }),
|
|
864
878
|
* }
|
|
865
879
|
*/
|
|
866
|
-
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput
|
|
880
|
+
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput, NoInfer<TListSelect>>;
|
|
867
881
|
}
|
|
868
882
|
interface CrudProcedures {
|
|
869
883
|
counts?: AnyProcedure;
|
|
@@ -1079,7 +1093,7 @@ declare const baseCountsInputSchema: z.ZodObject<{
|
|
|
1079
1093
|
* @typeParam TInsert - 创建输入类型
|
|
1080
1094
|
* @typeParam TUpdate - 更新输入类型
|
|
1081
1095
|
*/
|
|
1082
|
-
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;
|
|
1083
1097
|
//#endregion
|
|
1084
1098
|
//#region src/lib/middleware-helpers.d.ts
|
|
1085
1099
|
/**
|
|
@@ -1172,12 +1186,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
|
|
|
1172
1186
|
} } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
|
|
1173
1187
|
//#endregion
|
|
1174
1188
|
//#region src/routers/index.d.ts
|
|
1175
|
-
declare const appRouter:
|
|
1189
|
+
declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
|
|
1176
1190
|
ctx: Context;
|
|
1177
1191
|
meta: object;
|
|
1178
|
-
errorShape:
|
|
1192
|
+
errorShape: _trpc_server0.TRPCDefaultErrorShape;
|
|
1179
1193
|
transformer: true;
|
|
1180
|
-
},
|
|
1194
|
+
}, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
|
|
1181
1195
|
type AppRouter = typeof appRouter;
|
|
1182
1196
|
//#endregion
|
|
1183
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
|
@@ -1270,13 +1270,17 @@ function createCrudRouter(config) {
|
|
|
1270
1270
|
const rowsOnlySchema = listSchemaWithOptionalTotal(listInputSchema);
|
|
1271
1271
|
const optionalTotal = rowsOnlySchema !== listInputSchema;
|
|
1272
1272
|
const resolvedListInputSchema = optionalTotal ? (raw) => (raw && typeof raw === "object" && "total" in raw && raw.total === false ? rowsOnlySchema : listInputSchema).parseAsync(raw) : listInputSchema;
|
|
1273
|
-
const
|
|
1273
|
+
const fullListOutputSchema = z.object({
|
|
1274
1274
|
data: z.array(entityOutputSchema),
|
|
1275
1275
|
total: optionalTotal ? z.number().optional() : z.number(),
|
|
1276
1276
|
page: z.number(),
|
|
1277
1277
|
perPage: z.number(),
|
|
1278
1278
|
pageCount: z.number()
|
|
1279
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;
|
|
1280
1284
|
const metadataOutputSchema = z.object({
|
|
1281
1285
|
schema: z.unknown().optional(),
|
|
1282
1286
|
fields: z.record(z.string(), z.unknown()).optional(),
|
|
@@ -1488,14 +1492,27 @@ function createCrudRouter(config) {
|
|
|
1488
1492
|
input: listInput,
|
|
1489
1493
|
operation: "list"
|
|
1490
1494
|
});
|
|
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
|
+
}
|
|
1491
1508
|
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput);
|
|
1492
1509
|
const where = combineConditions(baseWhere, extra?.where);
|
|
1493
1510
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1494
|
-
let query = ctx.db.select().from(table).$dynamic();
|
|
1511
|
+
let query = (select ? ctx.db.select(select) : ctx.db.select()).from(table).$dynamic();
|
|
1495
1512
|
if (where) query = query.where(where);
|
|
1496
1513
|
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
|
|
1497
1514
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1498
|
-
const data = Promise.resolve(query.limit(effectiveInput.perPage).offset(offset)).then((rows$1) => enrichCrudRows(ctx, config, idField, rows$1));
|
|
1515
|
+
const data = Promise.resolve(query.limit(effectiveInput.perPage).offset(offset)).then((rows$1) => select ? rows$1 : enrichCrudRows(ctx, config, idField, rows$1));
|
|
1499
1516
|
const count = async () => {
|
|
1500
1517
|
if (skipTotal) return void 0;
|
|
1501
1518
|
let countQuery = ctx.db.select({ count: sql`count(*)::int` }).from(table).$dynamic();
|
|
@@ -1505,6 +1522,7 @@ function createCrudRouter(config) {
|
|
|
1505
1522
|
const [rows, total] = await Promise.all([data, count()]);
|
|
1506
1523
|
return {
|
|
1507
1524
|
data: rows,
|
|
1525
|
+
...select ? { projected: true } : {},
|
|
1508
1526
|
...total === void 0 ? {} : { total },
|
|
1509
1527
|
page: effectiveInput.page,
|
|
1510
1528
|
perPage: effectiveInput.perPage,
|
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,9 +48,9 @@
|
|
|
48
48
|
"typescript": "^5.9.3",
|
|
49
49
|
"vitest": "^4.0.18",
|
|
50
50
|
"zod": "^4.3.6",
|
|
51
|
-
"@internal/tsconfig": "0.1.0",
|
|
52
51
|
"@internal/prettier-config": "0.0.1",
|
|
53
52
|
"@internal/eslint-config": "0.3.0",
|
|
53
|
+
"@internal/tsconfig": "0.1.0",
|
|
54
54
|
"@internal/tsdown-config": "0.1.0",
|
|
55
55
|
"@internal/vitest-config": "0.1.0"
|
|
56
56
|
},
|