@wordrhyme/auto-crud-server 2.0.2 → 2.1.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 +8 -0
- package/dist/index.cjs +86 -21
- package/dist/index.d.cts +69 -11
- package/dist/index.d.ts +62 -4
- package/dist/index.js +86 -22
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -1308,3 +1308,11 @@ const t = initTRPC
|
|
|
1308
1308
|
.meta<Partial<CrudResourceMetadata> & { permission?: string }>()
|
|
1309
1309
|
.create();
|
|
1310
1310
|
```
|
|
1311
|
+
|
|
1312
|
+
## Optional batch counts
|
|
1313
|
+
|
|
1314
|
+
Set `counts: true` on `createCrudRouter` to expose `counts({ queries })`. Each query has a unique `key` and the ordinary list `filters`, `joinOperator`, and optional `search`. A batch accepts 1–100 queries and returns `{ counts: { [key]: number } }` from one conditional aggregate SQL query.
|
|
1315
|
+
|
|
1316
|
+
This route uses the list procedure, guard, scope, soft deletion and extension conditions. It does not load or enrich rows. Keep the supplied database scoped to the caller. Counts are disabled by default. If list middleware transforms filters or enforces additional visibility restrictions, supply the equivalent transformation through `middleware.counts({ ctx, input, next })` before opting in; row enrichment middleware is deliberately not executed.
|
|
1317
|
+
|
|
1318
|
+
The database provider must implement governed `$counts(table, predicates)`, applying the same tenant, row and field observation rules as scalar counts. Missing support returns `PRECONDITION_FAILED`; this route never falls back to raw aggregation or repeated list calls. Deliver the Host capability before enabling counts in consumers, and pin a published Components version containing this route.
|
package/dist/index.cjs
CHANGED
|
@@ -1157,6 +1157,15 @@ function combineConditions(...conditions) {
|
|
|
1157
1157
|
if (filtered.length === 1) return filtered[0];
|
|
1158
1158
|
return (0, drizzle_orm.and)(...filtered);
|
|
1159
1159
|
}
|
|
1160
|
+
const baseCountsInputSchema = zod.z.object({ queries: zod.z.array(baseListInputSchema.pick({
|
|
1161
|
+
filters: true,
|
|
1162
|
+
search: true,
|
|
1163
|
+
joinOperator: true
|
|
1164
|
+
}).extend({ key: zod.z.string().trim().min(1).max(100).refine((key) => ![
|
|
1165
|
+
"__proto__",
|
|
1166
|
+
"constructor",
|
|
1167
|
+
"prototype"
|
|
1168
|
+
].includes(key), { message: "Count query key is reserved" }) }).strict()).min(1).max(100) }).strict().refine((input) => new Set(input.queries.map((query) => query.key)).size === input.queries.length, { message: "Count query keys must be unique" });
|
|
1160
1169
|
/**
|
|
1161
1170
|
* 创建 CRUD Router
|
|
1162
1171
|
*
|
|
@@ -1319,6 +1328,30 @@ function createCrudRouter(config) {
|
|
|
1319
1328
|
message: `Forbidden: Cannot ${operation} this resource`
|
|
1320
1329
|
});
|
|
1321
1330
|
};
|
|
1331
|
+
const queryWhere = async (ctx, input) => {
|
|
1332
|
+
const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, input);
|
|
1333
|
+
const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
|
|
1334
|
+
const filterCondition = validatedFilters?.length ? filterColumns({
|
|
1335
|
+
table,
|
|
1336
|
+
filters: validatedFilters,
|
|
1337
|
+
joinOperator: effectiveInput.joinOperator,
|
|
1338
|
+
resolveColumn: (columnId) => {
|
|
1339
|
+
const id = String(columnId);
|
|
1340
|
+
if (id === idField) return getTableColumn(table, idField);
|
|
1341
|
+
return resolveColumnTarget({
|
|
1342
|
+
table,
|
|
1343
|
+
columnId: id,
|
|
1344
|
+
allowedColumns: filterableColumns
|
|
1345
|
+
});
|
|
1346
|
+
},
|
|
1347
|
+
resolveDateRange: ctx.resolveDateRange
|
|
1348
|
+
}) : void 0;
|
|
1349
|
+
const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
|
|
1350
|
+
return {
|
|
1351
|
+
effectiveInput,
|
|
1352
|
+
where: buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition))
|
|
1353
|
+
};
|
|
1354
|
+
};
|
|
1322
1355
|
const procedures = {
|
|
1323
1356
|
meta: metaProcedure.output(metadataOutputSchema).query(async ({ ctx }) => {
|
|
1324
1357
|
await withGuard(ctx, "list");
|
|
@@ -1328,29 +1361,35 @@ function createCrudRouter(config) {
|
|
|
1328
1361
|
if (!provider?.getMetadata) return withCrudCapabilities({}, capabilities, disabledCapabilities);
|
|
1329
1362
|
return withCrudCapabilities(await provider.getMetadata({ id: target.id }), capabilities, disabledCapabilities);
|
|
1330
1363
|
}),
|
|
1364
|
+
...config.counts ? { counts: resolved.procedureFactory("list").input(baseCountsInputSchema).output(zod.z.object({ counts: zod.z.record(zod.z.string(), zod.z.number().int().nonnegative()) })).query(async ({ ctx, input }) => {
|
|
1365
|
+
await withGuard(ctx, "list");
|
|
1366
|
+
const count = async (batch) => {
|
|
1367
|
+
if (typeof ctx.db.$counts !== "function") throw new __trpc_server.TRPCError({
|
|
1368
|
+
code: "PRECONDITION_FAILED",
|
|
1369
|
+
message: "Batch counts require a database provider with scoped $counts support"
|
|
1370
|
+
});
|
|
1371
|
+
const conditions = Object.create(null);
|
|
1372
|
+
for (const query of batch.queries) {
|
|
1373
|
+
const { where } = await queryWhere(ctx, {
|
|
1374
|
+
...query,
|
|
1375
|
+
page: 1,
|
|
1376
|
+
perPage: 1
|
|
1377
|
+
});
|
|
1378
|
+
conditions[query.key] = where;
|
|
1379
|
+
}
|
|
1380
|
+
return { counts: await ctx.db.$counts(table, conditions) };
|
|
1381
|
+
};
|
|
1382
|
+
return m.counts ? m.counts({
|
|
1383
|
+
ctx,
|
|
1384
|
+
input,
|
|
1385
|
+
next: async (modified) => count(modified ?? input)
|
|
1386
|
+
}) : count(input);
|
|
1387
|
+
}) } : {},
|
|
1331
1388
|
list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
|
|
1332
1389
|
await withGuard(ctx, "list");
|
|
1333
1390
|
const doList = async (listInput$1) => {
|
|
1334
|
-
const effectiveInput = await
|
|
1391
|
+
const { effectiveInput, where } = await queryWhere(ctx, listInput$1);
|
|
1335
1392
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1336
|
-
const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
|
|
1337
|
-
const filterCondition = validatedFilters?.length ? filterColumns({
|
|
1338
|
-
table,
|
|
1339
|
-
filters: validatedFilters,
|
|
1340
|
-
joinOperator: effectiveInput.joinOperator,
|
|
1341
|
-
resolveColumn: (columnId) => {
|
|
1342
|
-
const id = String(columnId);
|
|
1343
|
-
if (id === idField) return getTableColumn(table, idField);
|
|
1344
|
-
return resolveColumnTarget({
|
|
1345
|
-
table,
|
|
1346
|
-
columnId: id,
|
|
1347
|
-
allowedColumns: filterableColumns
|
|
1348
|
-
});
|
|
1349
|
-
},
|
|
1350
|
-
resolveDateRange: ctx.resolveDateRange
|
|
1351
|
-
}) : void 0;
|
|
1352
|
-
const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
|
|
1353
|
-
const where = buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
|
|
1354
1393
|
let query = ctx.db.select().from(table).$dynamic();
|
|
1355
1394
|
if (where) query = query.where(where);
|
|
1356
1395
|
const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, true);
|
|
@@ -1494,6 +1533,10 @@ function createCrudRouter(config) {
|
|
|
1494
1533
|
let deleted;
|
|
1495
1534
|
if (softDelete) [deleted] = await writeCtx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(where).returning();
|
|
1496
1535
|
else [deleted] = await writeCtx.db.delete(table).where(where).returning();
|
|
1536
|
+
if (!deleted) throw new __trpc_server.TRPCError({
|
|
1537
|
+
code: "NOT_FOUND",
|
|
1538
|
+
message: "Resource not found or access denied"
|
|
1539
|
+
});
|
|
1497
1540
|
await emitCrudWriteLifecycle(writeCtx, config, "delete", {
|
|
1498
1541
|
id: input,
|
|
1499
1542
|
row: deleted,
|
|
@@ -1515,8 +1558,29 @@ function createCrudRouter(config) {
|
|
|
1515
1558
|
await withGuard(ctx, "deleteMany");
|
|
1516
1559
|
const where = buildWhere(ctx, "deleteMany", (0, drizzle_orm.inArray)(getIdColumn(), input));
|
|
1517
1560
|
const doDeleteMany = async () => {
|
|
1518
|
-
|
|
1519
|
-
|
|
1561
|
+
return runCrudExtensionWriteTransaction(ctx, config, {
|
|
1562
|
+
data: {},
|
|
1563
|
+
rawValues: { ids: input },
|
|
1564
|
+
baseValues: {},
|
|
1565
|
+
extraValues: null
|
|
1566
|
+
}, async (writeCtx) => {
|
|
1567
|
+
const emitLifecycle = shouldWrapCrudLifecycleTransaction(writeCtx, config);
|
|
1568
|
+
const existingRows = emitLifecycle && softDelete ? await writeCtx.db.select().from(table).where(where).for("update") : [];
|
|
1569
|
+
const existingById = new Map(existingRows.map((row) => [row[idField], row]));
|
|
1570
|
+
const deleteWhere = emitLifecycle && softDelete ? (0, drizzle_orm.and)(where, (0, drizzle_orm.inArray)(getIdColumn(), [...existingById.keys()])) : where;
|
|
1571
|
+
const query = softDelete ? writeCtx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(deleteWhere) : writeCtx.db.delete(table).where(where);
|
|
1572
|
+
const deleted = emitLifecycle ? await query.returning() : await query.returning({ id: getIdColumn() });
|
|
1573
|
+
if (emitLifecycle) for (const row of deleted) {
|
|
1574
|
+
const id = row[idField];
|
|
1575
|
+
await emitCrudWriteLifecycle(writeCtx, config, "delete", {
|
|
1576
|
+
id,
|
|
1577
|
+
row,
|
|
1578
|
+
existing: softDelete ? existingById.get(id) : row,
|
|
1579
|
+
entityId: id
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
return { deleted: deleted.length };
|
|
1583
|
+
});
|
|
1520
1584
|
};
|
|
1521
1585
|
if (m.deleteMany) return m.deleteMany({
|
|
1522
1586
|
ctx,
|
|
@@ -1849,6 +1913,7 @@ const appRouter = router({});
|
|
|
1849
1913
|
//#endregion
|
|
1850
1914
|
exports.afterMiddleware = afterMiddleware;
|
|
1851
1915
|
exports.appRouter = appRouter;
|
|
1916
|
+
exports.baseCountsInputSchema = baseCountsInputSchema;
|
|
1852
1917
|
exports.baseExportInputSchema = baseExportInputSchema;
|
|
1853
1918
|
exports.baseGetInputSchema = baseGetInputSchema;
|
|
1854
1919
|
exports.baseListInputSchema = baseListInputSchema;
|
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';
|
|
@@ -146,9 +146,17 @@ interface ListInput {
|
|
|
146
146
|
}>;
|
|
147
147
|
joinOperator: 'and' | 'or';
|
|
148
148
|
}
|
|
149
|
-
/**
|
|
150
|
-
|
|
151
|
-
|
|
149
|
+
/** Named filters for a single batch count. */
|
|
150
|
+
type CountQuery = Pick<ListInput, 'search' | 'filters' | 'joinOperator'> & {
|
|
151
|
+
key: string;
|
|
152
|
+
};
|
|
153
|
+
interface CountsInput {
|
|
154
|
+
queries: CountQuery[];
|
|
155
|
+
}
|
|
156
|
+
interface CountsResult {
|
|
157
|
+
counts: Record<string, number>;
|
|
158
|
+
}
|
|
159
|
+
/** 列表查询结果类型 */
|
|
152
160
|
interface ListResult<TSelect> {
|
|
153
161
|
data: TSelect[];
|
|
154
162
|
total: number;
|
|
@@ -419,6 +427,12 @@ interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknow
|
|
|
419
427
|
* 列表查询包装器
|
|
420
428
|
*/
|
|
421
429
|
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput>) => Promise<ListResult<TSelect>>;
|
|
430
|
+
/** Batch counts use list authorization, but do not run row enrichment. */
|
|
431
|
+
counts?: (params: {
|
|
432
|
+
ctx: TContext;
|
|
433
|
+
input: CountsInput;
|
|
434
|
+
next: (input?: CountsInput) => Promise<CountsResult>;
|
|
435
|
+
}) => Promise<CountsResult>;
|
|
422
436
|
/**
|
|
423
437
|
* 单条查询包装器
|
|
424
438
|
*/
|
|
@@ -581,6 +595,8 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
581
595
|
* - provider/function: explicitly use this provider.
|
|
582
596
|
*/
|
|
583
597
|
extensions?: CrudExtensionsConfig<TContext>;
|
|
598
|
+
/** Opt in after supplying any list-specific filter transformations in middleware.counts. */
|
|
599
|
+
counts?: boolean;
|
|
584
600
|
/**
|
|
585
601
|
* 主 Schema(用于 create/upsert 输入验证)
|
|
586
602
|
* - 如果不传,自动从 table 派生并排除 omitFields
|
|
@@ -804,6 +820,7 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
804
820
|
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput>;
|
|
805
821
|
}
|
|
806
822
|
interface CrudProcedures {
|
|
823
|
+
counts?: AnyProcedure;
|
|
807
824
|
meta: AnyProcedure;
|
|
808
825
|
list: AnyProcedure;
|
|
809
826
|
get: AnyProcedure;
|
|
@@ -916,6 +933,47 @@ declare const baseExportInputSchema: z.ZodObject<{
|
|
|
916
933
|
}>>;
|
|
917
934
|
limit: z.ZodOptional<z.ZodNumber>;
|
|
918
935
|
}, z.core.$strip>;
|
|
936
|
+
declare const baseCountsInputSchema: z.ZodObject<{
|
|
937
|
+
queries: z.ZodArray<z.ZodObject<{
|
|
938
|
+
search: z.ZodOptional<z.ZodString>;
|
|
939
|
+
filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
940
|
+
id: z.ZodString;
|
|
941
|
+
value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
|
|
942
|
+
variant: z.ZodEnum<{
|
|
943
|
+
number: "number";
|
|
944
|
+
boolean: "boolean";
|
|
945
|
+
date: "date";
|
|
946
|
+
text: "text";
|
|
947
|
+
range: "range";
|
|
948
|
+
dateRange: "dateRange";
|
|
949
|
+
select: "select";
|
|
950
|
+
multiSelect: "multiSelect";
|
|
951
|
+
}>;
|
|
952
|
+
operator: z.ZodEnum<{
|
|
953
|
+
iLike: "iLike";
|
|
954
|
+
notILike: "notILike";
|
|
955
|
+
eq: "eq";
|
|
956
|
+
ne: "ne";
|
|
957
|
+
isEmpty: "isEmpty";
|
|
958
|
+
isNotEmpty: "isNotEmpty";
|
|
959
|
+
lt: "lt";
|
|
960
|
+
lte: "lte";
|
|
961
|
+
gt: "gt";
|
|
962
|
+
gte: "gte";
|
|
963
|
+
isBetween: "isBetween";
|
|
964
|
+
isRelativeToToday: "isRelativeToToday";
|
|
965
|
+
inArray: "inArray";
|
|
966
|
+
notInArray: "notInArray";
|
|
967
|
+
}>;
|
|
968
|
+
filterId: z.ZodString;
|
|
969
|
+
}, z.core.$strip>>>;
|
|
970
|
+
joinOperator: z.ZodDefault<z.ZodEnum<{
|
|
971
|
+
and: "and";
|
|
972
|
+
or: "or";
|
|
973
|
+
}>>;
|
|
974
|
+
key: z.ZodString;
|
|
975
|
+
}, z.core.$strict>>;
|
|
976
|
+
}, z.core.$strict>;
|
|
919
977
|
/**
|
|
920
978
|
* 创建 CRUD Router
|
|
921
979
|
*
|
|
@@ -1021,12 +1079,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
|
|
|
1021
1079
|
} } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
|
|
1022
1080
|
//#endregion
|
|
1023
1081
|
//#region src/routers/index.d.ts
|
|
1024
|
-
declare const appRouter:
|
|
1082
|
+
declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
|
|
1025
1083
|
ctx: Context;
|
|
1026
1084
|
meta: object;
|
|
1027
|
-
errorShape:
|
|
1085
|
+
errorShape: _trpc_server0.TRPCDefaultErrorShape;
|
|
1028
1086
|
transformer: true;
|
|
1029
|
-
},
|
|
1087
|
+
}, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
|
|
1030
1088
|
type AppRouter = typeof appRouter;
|
|
1031
1089
|
//#endregion
|
|
1032
|
-
export { type AnyProcedure, type AppRouter, 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 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, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
|
|
1090
|
+
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 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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -147,9 +147,17 @@ interface ListInput {
|
|
|
147
147
|
}>;
|
|
148
148
|
joinOperator: 'and' | 'or';
|
|
149
149
|
}
|
|
150
|
-
/**
|
|
151
|
-
|
|
152
|
-
|
|
150
|
+
/** Named filters for a single batch count. */
|
|
151
|
+
type CountQuery = Pick<ListInput, 'search' | 'filters' | 'joinOperator'> & {
|
|
152
|
+
key: string;
|
|
153
|
+
};
|
|
154
|
+
interface CountsInput {
|
|
155
|
+
queries: CountQuery[];
|
|
156
|
+
}
|
|
157
|
+
interface CountsResult {
|
|
158
|
+
counts: Record<string, number>;
|
|
159
|
+
}
|
|
160
|
+
/** 列表查询结果类型 */
|
|
153
161
|
interface ListResult<TSelect> {
|
|
154
162
|
data: TSelect[];
|
|
155
163
|
total: number;
|
|
@@ -420,6 +428,12 @@ interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknow
|
|
|
420
428
|
* 列表查询包装器
|
|
421
429
|
*/
|
|
422
430
|
list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput>) => Promise<ListResult<TSelect>>;
|
|
431
|
+
/** Batch counts use list authorization, but do not run row enrichment. */
|
|
432
|
+
counts?: (params: {
|
|
433
|
+
ctx: TContext;
|
|
434
|
+
input: CountsInput;
|
|
435
|
+
next: (input?: CountsInput) => Promise<CountsResult>;
|
|
436
|
+
}) => Promise<CountsResult>;
|
|
423
437
|
/**
|
|
424
438
|
* 单条查询包装器
|
|
425
439
|
*/
|
|
@@ -582,6 +596,8 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
582
596
|
* - provider/function: explicitly use this provider.
|
|
583
597
|
*/
|
|
584
598
|
extensions?: CrudExtensionsConfig<TContext>;
|
|
599
|
+
/** Opt in after supplying any list-specific filter transformations in middleware.counts. */
|
|
600
|
+
counts?: boolean;
|
|
585
601
|
/**
|
|
586
602
|
* 主 Schema(用于 create/upsert 输入验证)
|
|
587
603
|
* - 如果不传,自动从 table 派生并排除 omitFields
|
|
@@ -805,6 +821,7 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
|
|
|
805
821
|
middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput>;
|
|
806
822
|
}
|
|
807
823
|
interface CrudProcedures {
|
|
824
|
+
counts?: AnyProcedure;
|
|
808
825
|
meta: AnyProcedure;
|
|
809
826
|
list: AnyProcedure;
|
|
810
827
|
get: AnyProcedure;
|
|
@@ -917,6 +934,47 @@ declare const baseExportInputSchema: z.ZodObject<{
|
|
|
917
934
|
}>>;
|
|
918
935
|
limit: z.ZodOptional<z.ZodNumber>;
|
|
919
936
|
}, z.core.$strip>;
|
|
937
|
+
declare const baseCountsInputSchema: z.ZodObject<{
|
|
938
|
+
queries: z.ZodArray<z.ZodObject<{
|
|
939
|
+
search: z.ZodOptional<z.ZodString>;
|
|
940
|
+
filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
941
|
+
id: z.ZodString;
|
|
942
|
+
value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
|
|
943
|
+
variant: z.ZodEnum<{
|
|
944
|
+
number: "number";
|
|
945
|
+
boolean: "boolean";
|
|
946
|
+
date: "date";
|
|
947
|
+
text: "text";
|
|
948
|
+
range: "range";
|
|
949
|
+
dateRange: "dateRange";
|
|
950
|
+
select: "select";
|
|
951
|
+
multiSelect: "multiSelect";
|
|
952
|
+
}>;
|
|
953
|
+
operator: z.ZodEnum<{
|
|
954
|
+
iLike: "iLike";
|
|
955
|
+
notILike: "notILike";
|
|
956
|
+
eq: "eq";
|
|
957
|
+
ne: "ne";
|
|
958
|
+
isEmpty: "isEmpty";
|
|
959
|
+
isNotEmpty: "isNotEmpty";
|
|
960
|
+
lt: "lt";
|
|
961
|
+
lte: "lte";
|
|
962
|
+
gt: "gt";
|
|
963
|
+
gte: "gte";
|
|
964
|
+
isBetween: "isBetween";
|
|
965
|
+
isRelativeToToday: "isRelativeToToday";
|
|
966
|
+
inArray: "inArray";
|
|
967
|
+
notInArray: "notInArray";
|
|
968
|
+
}>;
|
|
969
|
+
filterId: z.ZodString;
|
|
970
|
+
}, z.core.$strip>>>;
|
|
971
|
+
joinOperator: z.ZodDefault<z.ZodEnum<{
|
|
972
|
+
and: "and";
|
|
973
|
+
or: "or";
|
|
974
|
+
}>>;
|
|
975
|
+
key: z.ZodString;
|
|
976
|
+
}, z.core.$strict>>;
|
|
977
|
+
}, z.core.$strict>;
|
|
920
978
|
/**
|
|
921
979
|
* 创建 CRUD Router
|
|
922
980
|
*
|
|
@@ -1030,4 +1088,4 @@ declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
|
|
|
1030
1088
|
}, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
|
|
1031
1089
|
type AppRouter = typeof appRouter;
|
|
1032
1090
|
//#endregion
|
|
1033
|
-
export { type AnyProcedure, type AppRouter, 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 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, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
|
|
1091
|
+
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 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 };
|
package/dist/index.js
CHANGED
|
@@ -1126,6 +1126,15 @@ function combineConditions(...conditions) {
|
|
|
1126
1126
|
if (filtered.length === 1) return filtered[0];
|
|
1127
1127
|
return and(...filtered);
|
|
1128
1128
|
}
|
|
1129
|
+
const baseCountsInputSchema = z.object({ queries: z.array(baseListInputSchema.pick({
|
|
1130
|
+
filters: true,
|
|
1131
|
+
search: true,
|
|
1132
|
+
joinOperator: true
|
|
1133
|
+
}).extend({ key: z.string().trim().min(1).max(100).refine((key) => ![
|
|
1134
|
+
"__proto__",
|
|
1135
|
+
"constructor",
|
|
1136
|
+
"prototype"
|
|
1137
|
+
].includes(key), { message: "Count query key is reserved" }) }).strict()).min(1).max(100) }).strict().refine((input) => new Set(input.queries.map((query) => query.key)).size === input.queries.length, { message: "Count query keys must be unique" });
|
|
1129
1138
|
/**
|
|
1130
1139
|
* 创建 CRUD Router
|
|
1131
1140
|
*
|
|
@@ -1288,6 +1297,30 @@ function createCrudRouter(config) {
|
|
|
1288
1297
|
message: `Forbidden: Cannot ${operation} this resource`
|
|
1289
1298
|
});
|
|
1290
1299
|
};
|
|
1300
|
+
const queryWhere = async (ctx, input) => {
|
|
1301
|
+
const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, input);
|
|
1302
|
+
const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
|
|
1303
|
+
const filterCondition = validatedFilters?.length ? filterColumns({
|
|
1304
|
+
table,
|
|
1305
|
+
filters: validatedFilters,
|
|
1306
|
+
joinOperator: effectiveInput.joinOperator,
|
|
1307
|
+
resolveColumn: (columnId) => {
|
|
1308
|
+
const id = String(columnId);
|
|
1309
|
+
if (id === idField) return getTableColumn(table, idField);
|
|
1310
|
+
return resolveColumnTarget({
|
|
1311
|
+
table,
|
|
1312
|
+
columnId: id,
|
|
1313
|
+
allowedColumns: filterableColumns
|
|
1314
|
+
});
|
|
1315
|
+
},
|
|
1316
|
+
resolveDateRange: ctx.resolveDateRange
|
|
1317
|
+
}) : void 0;
|
|
1318
|
+
const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
|
|
1319
|
+
return {
|
|
1320
|
+
effectiveInput,
|
|
1321
|
+
where: buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition))
|
|
1322
|
+
};
|
|
1323
|
+
};
|
|
1291
1324
|
const procedures = {
|
|
1292
1325
|
meta: metaProcedure.output(metadataOutputSchema).query(async ({ ctx }) => {
|
|
1293
1326
|
await withGuard(ctx, "list");
|
|
@@ -1297,29 +1330,35 @@ function createCrudRouter(config) {
|
|
|
1297
1330
|
if (!provider?.getMetadata) return withCrudCapabilities({}, capabilities, disabledCapabilities);
|
|
1298
1331
|
return withCrudCapabilities(await provider.getMetadata({ id: target.id }), capabilities, disabledCapabilities);
|
|
1299
1332
|
}),
|
|
1333
|
+
...config.counts ? { counts: resolved.procedureFactory("list").input(baseCountsInputSchema).output(z.object({ counts: z.record(z.string(), z.number().int().nonnegative()) })).query(async ({ ctx, input }) => {
|
|
1334
|
+
await withGuard(ctx, "list");
|
|
1335
|
+
const count = async (batch) => {
|
|
1336
|
+
if (typeof ctx.db.$counts !== "function") throw new TRPCError({
|
|
1337
|
+
code: "PRECONDITION_FAILED",
|
|
1338
|
+
message: "Batch counts require a database provider with scoped $counts support"
|
|
1339
|
+
});
|
|
1340
|
+
const conditions = Object.create(null);
|
|
1341
|
+
for (const query of batch.queries) {
|
|
1342
|
+
const { where } = await queryWhere(ctx, {
|
|
1343
|
+
...query,
|
|
1344
|
+
page: 1,
|
|
1345
|
+
perPage: 1
|
|
1346
|
+
});
|
|
1347
|
+
conditions[query.key] = where;
|
|
1348
|
+
}
|
|
1349
|
+
return { counts: await ctx.db.$counts(table, conditions) };
|
|
1350
|
+
};
|
|
1351
|
+
return m.counts ? m.counts({
|
|
1352
|
+
ctx,
|
|
1353
|
+
input,
|
|
1354
|
+
next: async (modified) => count(modified ?? input)
|
|
1355
|
+
}) : count(input);
|
|
1356
|
+
}) } : {},
|
|
1300
1357
|
list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
|
|
1301
1358
|
await withGuard(ctx, "list");
|
|
1302
1359
|
const doList = async (listInput$1) => {
|
|
1303
|
-
const effectiveInput = await
|
|
1360
|
+
const { effectiveInput, where } = await queryWhere(ctx, listInput$1);
|
|
1304
1361
|
const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
|
|
1305
|
-
const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
|
|
1306
|
-
const filterCondition = validatedFilters?.length ? filterColumns({
|
|
1307
|
-
table,
|
|
1308
|
-
filters: validatedFilters,
|
|
1309
|
-
joinOperator: effectiveInput.joinOperator,
|
|
1310
|
-
resolveColumn: (columnId) => {
|
|
1311
|
-
const id = String(columnId);
|
|
1312
|
-
if (id === idField) return getTableColumn(table, idField);
|
|
1313
|
-
return resolveColumnTarget({
|
|
1314
|
-
table,
|
|
1315
|
-
columnId: id,
|
|
1316
|
-
allowedColumns: filterableColumns
|
|
1317
|
-
});
|
|
1318
|
-
},
|
|
1319
|
-
resolveDateRange: ctx.resolveDateRange
|
|
1320
|
-
}) : void 0;
|
|
1321
|
-
const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
|
|
1322
|
-
const where = buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
|
|
1323
1362
|
let query = ctx.db.select().from(table).$dynamic();
|
|
1324
1363
|
if (where) query = query.where(where);
|
|
1325
1364
|
const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, true);
|
|
@@ -1463,6 +1502,10 @@ function createCrudRouter(config) {
|
|
|
1463
1502
|
let deleted;
|
|
1464
1503
|
if (softDelete) [deleted] = await writeCtx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(where).returning();
|
|
1465
1504
|
else [deleted] = await writeCtx.db.delete(table).where(where).returning();
|
|
1505
|
+
if (!deleted) throw new TRPCError({
|
|
1506
|
+
code: "NOT_FOUND",
|
|
1507
|
+
message: "Resource not found or access denied"
|
|
1508
|
+
});
|
|
1466
1509
|
await emitCrudWriteLifecycle(writeCtx, config, "delete", {
|
|
1467
1510
|
id: input,
|
|
1468
1511
|
row: deleted,
|
|
@@ -1484,8 +1527,29 @@ function createCrudRouter(config) {
|
|
|
1484
1527
|
await withGuard(ctx, "deleteMany");
|
|
1485
1528
|
const where = buildWhere(ctx, "deleteMany", inArray(getIdColumn(), input));
|
|
1486
1529
|
const doDeleteMany = async () => {
|
|
1487
|
-
|
|
1488
|
-
|
|
1530
|
+
return runCrudExtensionWriteTransaction(ctx, config, {
|
|
1531
|
+
data: {},
|
|
1532
|
+
rawValues: { ids: input },
|
|
1533
|
+
baseValues: {},
|
|
1534
|
+
extraValues: null
|
|
1535
|
+
}, async (writeCtx) => {
|
|
1536
|
+
const emitLifecycle = shouldWrapCrudLifecycleTransaction(writeCtx, config);
|
|
1537
|
+
const existingRows = emitLifecycle && softDelete ? await writeCtx.db.select().from(table).where(where).for("update") : [];
|
|
1538
|
+
const existingById = new Map(existingRows.map((row) => [row[idField], row]));
|
|
1539
|
+
const deleteWhere = emitLifecycle && softDelete ? and(where, inArray(getIdColumn(), [...existingById.keys()])) : where;
|
|
1540
|
+
const query = softDelete ? writeCtx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(deleteWhere) : writeCtx.db.delete(table).where(where);
|
|
1541
|
+
const deleted = emitLifecycle ? await query.returning() : await query.returning({ id: getIdColumn() });
|
|
1542
|
+
if (emitLifecycle) for (const row of deleted) {
|
|
1543
|
+
const id = row[idField];
|
|
1544
|
+
await emitCrudWriteLifecycle(writeCtx, config, "delete", {
|
|
1545
|
+
id,
|
|
1546
|
+
row,
|
|
1547
|
+
existing: softDelete ? existingById.get(id) : row,
|
|
1548
|
+
entityId: id
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1551
|
+
return { deleted: deleted.length };
|
|
1552
|
+
});
|
|
1489
1553
|
};
|
|
1490
1554
|
if (m.deleteMany) return m.deleteMany({
|
|
1491
1555
|
ctx,
|
|
@@ -1816,4 +1880,4 @@ function composeMiddleware(...middlewares) {
|
|
|
1816
1880
|
const appRouter = router({});
|
|
1817
1881
|
|
|
1818
1882
|
//#endregion
|
|
1819
|
-
export { afterMiddleware, appRouter, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
|
|
1883
|
+
export { afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wordrhyme/auto-crud-server",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.0
|
|
4
|
+
"version": "2.1.0",
|
|
5
5
|
"description": "tRPC server utilities for auto-crud - automatic CRUD routers for Drizzle ORM",
|
|
6
6
|
"author": "wordrhyme",
|
|
7
7
|
"license": "MIT",
|
|
@@ -49,10 +49,10 @@
|
|
|
49
49
|
"vitest": "^4.0.18",
|
|
50
50
|
"zod": "^4.3.6",
|
|
51
51
|
"@internal/eslint-config": "0.3.0",
|
|
52
|
-
"@internal/prettier-config": "0.0.1",
|
|
53
|
-
"@internal/tsconfig": "0.1.0",
|
|
54
52
|
"@internal/tsdown-config": "0.1.0",
|
|
55
|
-
"@internal/
|
|
53
|
+
"@internal/tsconfig": "0.1.0",
|
|
54
|
+
"@internal/vitest-config": "0.1.0",
|
|
55
|
+
"@internal/prettier-config": "0.0.1"
|
|
56
56
|
},
|
|
57
57
|
"prettier": "@internal/prettier-config",
|
|
58
58
|
"scripts": {
|