@wordrhyme/auto-crud-server 2.3.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 +7 -2
- package/dist/index.cjs +50 -20
- package/dist/index.d.cts +21 -11
- package/dist/index.d.ts +14 -4
- package/dist/index.js +50 -20
- package/package.json +3 -3
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
|
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,41 +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
|
|
1514
|
+
const skipTotal = input[skipListTotal] === true;
|
|
1515
|
+
if (skipTotal) delete input[skipListTotal];
|
|
1516
|
+
const doList = async (listInput) => {
|
|
1492
1517
|
const extra = await config.query?.({
|
|
1493
1518
|
ctx,
|
|
1494
|
-
input: listInput
|
|
1519
|
+
input: listInput,
|
|
1495
1520
|
operation: "list"
|
|
1496
1521
|
});
|
|
1497
|
-
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput
|
|
1522
|
+
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput);
|
|
1498
1523
|
const where = combineConditions(baseWhere, extra?.where);
|
|
1499
1524
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1500
1525
|
let query = ctx.db.select().from(table).$dynamic();
|
|
1501
1526
|
if (where) query = query.where(where);
|
|
1502
1527
|
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
|
|
1503
1528
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
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()]);
|
|
1511
1537
|
return {
|
|
1512
|
-
data:
|
|
1513
|
-
total:
|
|
1538
|
+
data: rows,
|
|
1539
|
+
...total === void 0 ? {} : { total },
|
|
1514
1540
|
page: effectiveInput.page,
|
|
1515
1541
|
perPage: effectiveInput.perPage,
|
|
1516
|
-
pageCount: Math.ceil(
|
|
1542
|
+
pageCount: total === void 0 ? -1 : Math.ceil(total / effectiveInput.perPage)
|
|
1517
1543
|
};
|
|
1518
1544
|
};
|
|
1519
|
-
|
|
1520
|
-
|
|
1545
|
+
if (!m.list) return doList(input);
|
|
1546
|
+
const result = await m.list({
|
|
1521
1547
|
ctx,
|
|
1522
|
-
input
|
|
1523
|
-
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"
|
|
1524
1554
|
});
|
|
1525
|
-
return
|
|
1555
|
+
return result;
|
|
1526
1556
|
}),
|
|
1527
1557
|
get: resolved.procedureFactory("get").input(resolvedGetInputSchema).output(entityOutputSchema.nullable()).query(async ({ ctx, input }) => {
|
|
1528
1558
|
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,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 })
|
|
@@ -1161,12 +1171,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
|
|
|
1161
1171
|
} } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
|
|
1162
1172
|
//#endregion
|
|
1163
1173
|
//#region src/routers/index.d.ts
|
|
1164
|
-
declare const appRouter:
|
|
1174
|
+
declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
|
|
1165
1175
|
ctx: Context;
|
|
1166
1176
|
meta: object;
|
|
1167
|
-
errorShape:
|
|
1177
|
+
errorShape: _trpc_server0.TRPCDefaultErrorShape;
|
|
1168
1178
|
transformer: true;
|
|
1169
|
-
},
|
|
1179
|
+
}, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
|
|
1170
1180
|
type AppRouter = typeof appRouter;
|
|
1171
1181
|
//#endregion
|
|
1172
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
|
@@ -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 })
|
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,41 +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
|
|
1483
|
+
const skipTotal = input[skipListTotal] === true;
|
|
1484
|
+
if (skipTotal) delete input[skipListTotal];
|
|
1485
|
+
const doList = async (listInput) => {
|
|
1461
1486
|
const extra = await config.query?.({
|
|
1462
1487
|
ctx,
|
|
1463
|
-
input: listInput
|
|
1488
|
+
input: listInput,
|
|
1464
1489
|
operation: "list"
|
|
1465
1490
|
});
|
|
1466
|
-
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput
|
|
1491
|
+
const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput);
|
|
1467
1492
|
const where = combineConditions(baseWhere, extra?.where);
|
|
1468
1493
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1469
1494
|
let query = ctx.db.select().from(table).$dynamic();
|
|
1470
1495
|
if (where) query = query.where(where);
|
|
1471
1496
|
const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
|
|
1472
1497
|
if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
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()]);
|
|
1480
1506
|
return {
|
|
1481
|
-
data:
|
|
1482
|
-
total:
|
|
1507
|
+
data: rows,
|
|
1508
|
+
...total === void 0 ? {} : { total },
|
|
1483
1509
|
page: effectiveInput.page,
|
|
1484
1510
|
perPage: effectiveInput.perPage,
|
|
1485
|
-
pageCount: Math.ceil(
|
|
1511
|
+
pageCount: total === void 0 ? -1 : Math.ceil(total / effectiveInput.perPage)
|
|
1486
1512
|
};
|
|
1487
1513
|
};
|
|
1488
|
-
|
|
1489
|
-
|
|
1514
|
+
if (!m.list) return doList(input);
|
|
1515
|
+
const result = await m.list({
|
|
1490
1516
|
ctx,
|
|
1491
|
-
input
|
|
1492
|
-
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"
|
|
1493
1523
|
});
|
|
1494
|
-
return
|
|
1524
|
+
return result;
|
|
1495
1525
|
}),
|
|
1496
1526
|
get: resolved.procedureFactory("get").input(resolvedGetInputSchema).output(entityOutputSchema.nullable()).query(async ({ ctx, input }) => {
|
|
1497
1527
|
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.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,9 +48,9 @@
|
|
|
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
|
-
"@internal/prettier-config": "0.0.1",
|
|
53
51
|
"@internal/tsconfig": "0.1.0",
|
|
52
|
+
"@internal/prettier-config": "0.0.1",
|
|
53
|
+
"@internal/eslint-config": "0.3.0",
|
|
54
54
|
"@internal/tsdown-config": "0.1.0",
|
|
55
55
|
"@internal/vitest-config": "0.1.0"
|
|
56
56
|
},
|