@wordrhyme/auto-crud-server 0.4.0 → 0.6.1

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/dist/index.d.cts CHANGED
@@ -1,6 +1,5 @@
1
- import * as _trpc_server5 from "@trpc/server";
1
+ import * as _trpc_server2 from "@trpc/server";
2
2
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
3
- import * as node_modules__trpc_server_dist_unstable_core_do_not_import_d_CjQPvBRI_mjs0 from "node_modules/@trpc/server/dist/unstable-core-do-not-import.d-CjQPvBRI.mjs";
4
3
  import { SQL } from "drizzle-orm";
5
4
  import { PgTable } from "drizzle-orm/pg-core";
6
5
  import { z } from "zod";
@@ -13,16 +12,16 @@ import { z } from "zod";
13
12
  interface Context {
14
13
  db: PostgresJsDatabase<Record<string, never>>;
15
14
  }
16
- declare const router: _trpc_server5.TRPCRouterBuilder<{
15
+ declare const router: _trpc_server2.TRPCRouterBuilder<{
17
16
  ctx: Context;
18
17
  meta: object;
19
- errorShape: _trpc_server5.TRPCDefaultErrorShape;
18
+ errorShape: _trpc_server2.TRPCDefaultErrorShape;
20
19
  transformer: true;
21
20
  }>;
22
- declare const publicProcedure: _trpc_server5.TRPCProcedureBuilder<Context, object, object, _trpc_server5.TRPCUnsetMarker, _trpc_server5.TRPCUnsetMarker, _trpc_server5.TRPCUnsetMarker, _trpc_server5.TRPCUnsetMarker, false>;
21
+ declare const publicProcedure: _trpc_server2.TRPCProcedureBuilder<Context, object, object, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, false>;
23
22
  //#endregion
24
23
  //#region src/types/config.d.ts
25
- type CrudOperation = "list" | "get" | "create" | "update" | "delete" | "deleteMany" | "updateMany";
24
+ type CrudOperation = "list" | "get" | "create" | "update" | "delete" | "deleteMany" | "updateMany" | "upsert";
26
25
  type WriteOperation = "create" | "update";
27
26
  type AnyProcedure = any;
28
27
  interface SoftDeleteConfig {
@@ -71,100 +70,136 @@ interface ListResult<TSelect> {
71
70
  perPage: number;
72
71
  pageCount: number;
73
72
  }
73
+ interface ListMiddlewareParams<TContext, TSelect> {
74
+ ctx: TContext;
75
+ input: ListInput;
76
+ next: (input?: ListInput) => Promise<ListResult<TSelect>>;
77
+ }
78
+ interface GetMiddlewareParams<TContext, TSelect> {
79
+ ctx: TContext;
80
+ id: string;
81
+ next: () => Promise<TSelect | null>;
82
+ }
83
+ interface CreateMiddlewareParams<TContext, TSelect, TInsert> {
84
+ ctx: TContext;
85
+ input: TInsert;
86
+ next: (input?: TInsert) => Promise<TSelect>;
87
+ }
88
+ interface UpdateMiddlewareParams<TContext, TSelect, TUpdate> {
89
+ ctx: TContext;
90
+ id: string;
91
+ data: TUpdate;
92
+ existing: TSelect;
93
+ next: (data?: TUpdate) => Promise<TSelect>;
94
+ }
95
+ interface DeleteMiddlewareParams<TContext, TSelect> {
96
+ ctx: TContext;
97
+ id: string;
98
+ existing: TSelect;
99
+ next: () => Promise<TSelect>;
100
+ }
101
+ interface DeleteManyMiddlewareParams<TContext> {
102
+ ctx: TContext;
103
+ ids: string[];
104
+ next: () => Promise<{
105
+ deleted: number;
106
+ }>;
107
+ }
108
+ interface UpdateManyMiddlewareParams<TContext, TUpdate> {
109
+ ctx: TContext;
110
+ ids: string[];
111
+ data: TUpdate;
112
+ next: (data?: TUpdate) => Promise<{
113
+ updated: number;
114
+ }>;
115
+ }
116
+ interface UpsertMiddlewareParams<TContext, TSelect, TInsert> {
117
+ ctx: TContext;
118
+ input: TInsert;
119
+ next: (input?: TInsert) => Promise<{
120
+ data: TSelect;
121
+ isNew: boolean;
122
+ }>;
123
+ }
74
124
  /**
75
- * CRUD 生命周期钩子
125
+ * 操作包装器 - 类似 tRPC middleware 的 next 模式
126
+ *
127
+ * 功能:
128
+ * - 修改输入数据(传参给 next)
129
+ * - 修改返回值(处理 next 的结果)
130
+ * - 执行副作用(日志、通知、审计)
131
+ * - 条件拦截(不调用 next 直接返回/抛错)
132
+ * - 包装事务(try/catch 包裹 next)
133
+ *
134
+ * @typeParam TContext - 上下文类型
135
+ * @typeParam TSelect - 查询返回类型(从 selectSchema 推断)
136
+ * @typeParam TInsert - 创建输入类型(从 insertSchema 推断)
137
+ * @typeParam TUpdate - 更新输入类型(从 updateSchema 推断)
76
138
  *
77
139
  * @example
78
- * hooks: {
79
- * beforeCreate: async (ctx, data) => {
80
- * // 修改数据
81
- * return { ...data, slug: slugify(data.title) };
82
- * },
83
- * afterCreate: async (ctx, created) => {
84
- * // 发送通知
85
- * await sendNotification(created);
140
+ * // 修改输入 + 执行副作用
141
+ * middleware: {
142
+ * create: async ({ ctx, input, next }) => {
143
+ * const data = { ...input, slug: slugify(input.title) };
144
+ * const result = await next(data);
145
+ * await sendNotification(result);
146
+ * return result;
86
147
  * },
87
148
  * }
88
149
  */
89
- interface CrudHooks<TContext = unknown> {
150
+ interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown> {
90
151
  /**
91
- * 列表查询前
92
- * 可修改查询参数
152
+ * 列表查询包装器
93
153
  */
94
- beforeList?: (ctx: TContext, input: ListInput) => ListInput | void | Promise<ListInput | void>;
154
+ list?: (params: ListMiddlewareParams<TContext, TSelect>) => Promise<ListResult<TSelect>>;
95
155
  /**
96
- * 列表查询后
97
- * 可修改返回结果
156
+ * 单条查询包装器
98
157
  */
99
- afterList?: <TSelect>(ctx: TContext, result: ListResult<TSelect>) => ListResult<TSelect> | void | Promise<ListResult<TSelect> | void>;
158
+ get?: (params: GetMiddlewareParams<TContext, TSelect>) => Promise<TSelect | null>;
100
159
  /**
101
- * 单条查询前
160
+ * 创建包装器
102
161
  */
103
- beforeGet?: (ctx: TContext, id: string) => void | Promise<void>;
162
+ create?: (params: CreateMiddlewareParams<TContext, TSelect, TInsert>) => Promise<TSelect>;
104
163
  /**
105
- * 单条查询后
106
- * 可修改返回结果
164
+ * 更新包装器
165
+ * existing: 更新前的记录
107
166
  */
108
- afterGet?: <TSelect>(ctx: TContext, result: TSelect | null) => TSelect | null | void | Promise<TSelect | null | void>;
167
+ update?: (params: UpdateMiddlewareParams<TContext, TSelect, TUpdate>) => Promise<TSelect>;
109
168
  /**
110
- * 创建前
111
- * 可修改输入数据,返回新数据或抛出错误阻止创建
169
+ * 删除包装器
170
+ * existing: 删除前的记录
112
171
  */
113
- beforeCreate?: <TInsert>(ctx: TContext, data: TInsert) => TInsert | void | Promise<TInsert | void>;
172
+ delete?: (params: DeleteMiddlewareParams<TContext, TSelect>) => Promise<TSelect>;
114
173
  /**
115
- * 创建后
116
- * 用于副作用(日志、通知、同步等)
174
+ * 批量删除包装器
117
175
  */
118
- afterCreate?: <TSelect>(ctx: TContext, created: TSelect) => void | Promise<void>;
119
- /**
120
- * 更新前
121
- * 可修改输入数据,existing 为更新前的记录
122
- */
123
- beforeUpdate?: <TUpdate, TSelect>(ctx: TContext, id: string, data: TUpdate, existing: TSelect) => TUpdate | void | Promise<TUpdate | void>;
124
- /**
125
- * 更新后
126
- */
127
- afterUpdate?: <TSelect>(ctx: TContext, updated: TSelect) => void | Promise<void>;
128
- /**
129
- * 删除前
130
- * existing 为删除前的记录,可抛出错误阻止删除
131
- */
132
- beforeDelete?: <TSelect>(ctx: TContext, id: string, existing: TSelect) => void | Promise<void>;
133
- /**
134
- * 删除后
135
- */
136
- afterDelete?: <TSelect>(ctx: TContext, deleted: TSelect) => void | Promise<void>;
137
- /**
138
- * 批量删除前
139
- */
140
- beforeDeleteMany?: (ctx: TContext, ids: string[]) => void | Promise<void>;
141
- /**
142
- * 批量删除后
143
- */
144
- afterDeleteMany?: (ctx: TContext, result: {
176
+ deleteMany?: (params: DeleteManyMiddlewareParams<TContext>) => Promise<{
145
177
  deleted: number;
146
- }) => void | Promise<void>;
178
+ }>;
147
179
  /**
148
- * 批量更新前
149
- * 可修改输入数据
180
+ * 批量更新包装器
150
181
  */
151
- beforeUpdateMany?: <TUpdate>(ctx: TContext, ids: string[], data: TUpdate) => TUpdate | void | Promise<TUpdate | void>;
182
+ updateMany?: (params: UpdateManyMiddlewareParams<TContext, TUpdate>) => Promise<{
183
+ updated: number;
184
+ }>;
152
185
  /**
153
- * 批量更新后
186
+ * Upsert 包装器
187
+ * isNew: 是否为新建(冲突检测后)
154
188
  */
155
- afterUpdateMany?: (ctx: TContext, result: {
156
- updated: number;
157
- }) => void | Promise<void>;
189
+ upsert?: (params: UpsertMiddlewareParams<TContext, TSelect, TInsert>) => Promise<{
190
+ data: TSelect;
191
+ isNew: boolean;
192
+ }>;
158
193
  }
159
- interface CrudRouterConfigBase<TContext = unknown> {
194
+ interface CrudRouterConfigBase<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown> {
160
195
  /** Drizzle 表定义 */
161
196
  table: PgTable;
162
197
  /** 查询返回 Schema */
163
- selectSchema?: z.ZodType;
198
+ selectSchema?: z.ZodType<TSelect>;
164
199
  /** 创建输入 Schema */
165
- insertSchema: z.ZodType;
200
+ insertSchema: z.ZodType<TInsert>;
166
201
  /** 更新输入 Schema */
167
- updateSchema: z.ZodType;
202
+ updateSchema: z.ZodType<TUpdate>;
168
203
  /** ID 字段名,默认 "id" */
169
204
  idField?: string;
170
205
  /** 可过滤的列白名单 */
@@ -192,22 +227,36 @@ interface CrudRouterConfigBase<TContext = unknown> {
192
227
  */
193
228
  softDelete?: SoftDeleteOption;
194
229
  /**
195
- * 生命周期钩子
196
- * CRUD 操作前后注入自定义逻辑
230
+ * 操作中间件
231
+ * 类似 tRPC middleware 的 next 模式,完全控制操作流程
197
232
  *
198
233
  * @example
199
- * hooks: {
200
- * beforeCreate: async (ctx, data) => {
201
- * return { ...data, slug: slugify(data.title) };
202
- * },
203
- * afterCreate: async (ctx, created) => {
204
- * await sendNotification(created);
234
+ * // 完整控制
235
+ * middleware: {
236
+ * create: async ({ ctx, input, next }) => {
237
+ * const data = { ...input, slug: slugify(input.title) };
238
+ * const result = await next(data);
239
+ * await sendNotification(result);
240
+ * return result;
205
241
  * },
206
242
  * }
243
+ *
244
+ * @example
245
+ * // 使用工具函数简化
246
+ * import { afterMiddleware, beforeMiddleware } from "@wordrhyme/auto-crud-server";
247
+ *
248
+ * middleware: {
249
+ * create: afterMiddleware(async (ctx, result) => {
250
+ * await sendEmail(result);
251
+ * }),
252
+ * update: beforeMiddleware(async (ctx, data) => {
253
+ * return { ...data, updatedAt: new Date() };
254
+ * }),
255
+ * }
207
256
  */
208
- hooks?: CrudHooks<TContext>;
257
+ middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate>;
209
258
  }
210
- interface DeclarativeConfig<TContext = unknown> extends CrudRouterConfigBase<TContext> {
259
+ interface DeclarativeConfig<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown> extends CrudRouterConfigBase<TContext, TSelect, TInsert, TUpdate> {
211
260
  mode?: "declarative";
212
261
  /**
213
262
  * 基础 procedure(认证)
@@ -245,9 +294,9 @@ interface DeclarativeConfig<TContext = unknown> extends CrudRouterConfigBase<TCo
245
294
  * @example
246
295
  * authorize: (ctx, resource, op) => resource.ownerId === ctx.user.id
247
296
  */
248
- authorize?: (ctx: TContext, resource: Record<string, unknown>, operation: CrudOperation) => boolean | Promise<boolean>;
297
+ authorize?: (ctx: TContext, resource: TSelect, operation: CrudOperation) => boolean | Promise<boolean>;
249
298
  }
250
- interface FactoryConfig<TContext = unknown> extends CrudRouterConfigBase<TContext> {
299
+ interface FactoryConfig<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown> extends CrudRouterConfigBase<TContext, TSelect, TInsert, TUpdate> {
251
300
  mode: "factory";
252
301
  /**
253
302
  * Procedure 工厂函数
@@ -266,7 +315,7 @@ interface FactoryConfig<TContext = unknown> extends CrudRouterConfigBase<TContex
266
315
  */
267
316
  inject?: (ctx: TContext, operation: WriteOperation) => Record<string, unknown>;
268
317
  }
269
- interface ProceduresConfig<TContext = unknown> extends CrudRouterConfigBase<TContext> {
318
+ interface ProceduresConfig<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown> extends CrudRouterConfigBase<TContext, TSelect, TInsert, TUpdate> {
270
319
  mode: "procedures";
271
320
  /**
272
321
  * 按操作指定不同的 procedure
@@ -290,49 +339,95 @@ interface ProceduresConfig<TContext = unknown> extends CrudRouterConfigBase<TCon
290
339
  */
291
340
  inject?: (ctx: TContext, operation: WriteOperation) => Record<string, unknown>;
292
341
  }
293
- type CrudRouterConfig<TContext = unknown> = DeclarativeConfig<TContext> | FactoryConfig<TContext> | ProceduresConfig<TContext>;
342
+ type CrudRouterConfig<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown> = DeclarativeConfig<TContext, TSelect, TInsert, TUpdate> | FactoryConfig<TContext, TSelect, TInsert, TUpdate> | ProceduresConfig<TContext, TSelect, TInsert, TUpdate>;
343
+ interface CrudProcedures<TSelect, TInsert, TUpdate> {
344
+ list: AnyProcedure;
345
+ get: AnyProcedure;
346
+ create: AnyProcedure;
347
+ update: AnyProcedure;
348
+ delete: AnyProcedure;
349
+ deleteMany: AnyProcedure;
350
+ updateMany: AnyProcedure;
351
+ upsert: AnyProcedure;
352
+ }
294
353
  //#endregion
295
354
  //#region src/routers/_factory.d.ts
296
- declare function createCrudRouter<TContext = unknown>(config: CrudRouterConfig<TContext>): node_modules__trpc_server_dist_unstable_core_do_not_import_d_CjQPvBRI_mjs0.Router<{
297
- ctx: Context;
298
- meta: object;
299
- errorShape: _trpc_server5.TRPCDefaultErrorShape;
300
- transformer: true;
301
- }, _trpc_server5.TRPCDecorateCreateRouterOptions<{
302
- list: any;
303
- getById: any;
304
- create: any;
305
- update: any;
306
- delete: any;
307
- deleteMany: any;
308
- updateMany: any;
309
- }>> & _trpc_server5.TRPCDecorateCreateRouterOptions<{
310
- list: any;
311
- getById: any;
312
- create: any;
313
- update: any;
314
- delete: any;
315
- deleteMany: any;
316
- updateMany: any;
317
- }> & {
318
- procedures: {
319
- list: any;
320
- getById: any;
321
- create: any;
322
- update: any;
323
- delete: any;
324
- deleteMany: any;
325
- updateMany: any;
326
- };
355
+ /**
356
+ * 创建 CRUD Router
357
+ *
358
+ * @typeParam TContext - 上下文类型(包含 db)
359
+ * @typeParam TSelect - 查询返回类型(从 selectSchema 或 insertSchema 推断)
360
+ * @typeParam TInsert - 创建输入类型(从 insertSchema 推断)
361
+ * @typeParam TUpdate - 更新输入类型(从 updateSchema 推断)
362
+ */
363
+ declare function createCrudRouter<TContext = unknown, TSelect = unknown, TInsert = unknown, TUpdate = unknown>(config: CrudRouterConfig<TContext, TSelect, TInsert, TUpdate>): ReturnType<typeof router> & {
364
+ procedures: CrudProcedures<TSelect, TInsert, TUpdate>;
365
+ };
366
+ //#endregion
367
+ //#region src/lib/middleware-helpers.d.ts
368
+ /**
369
+ * Middleware 便捷工具函数
370
+ * 简化常见场景的 middleware 创建
371
+ */
372
+ /**
373
+ * 创建 after-only 的 middleware(最常见场景)
374
+ * 在操作完成后执行副作用,不修改返回值
375
+ *
376
+ * @example
377
+ * middleware: {
378
+ * create: afterMiddleware(async (ctx, result) => {
379
+ * await sendEmail(result);
380
+ * await logAudit(ctx.user, 'create', result);
381
+ * }),
382
+ * }
383
+ */
384
+ declare function afterMiddleware<TContext, TResult>(fn: (ctx: TContext, result: TResult) => void | Promise<void>): (params: {
385
+ ctx: TContext;
386
+ next: () => Promise<TResult>;
387
+ [key: string]: any;
388
+ }) => Promise<TResult>;
389
+ /**
390
+ * 创建 before-only 的 middleware
391
+ * 在操作执行前修改输入数据
392
+ *
393
+ * @example
394
+ * middleware: {
395
+ * create: beforeMiddleware(async (ctx, input) => {
396
+ * return { ...input, slug: slugify(input.title), createdBy: ctx.user.id };
397
+ * }),
398
+ * }
399
+ */
400
+ declare function beforeMiddleware<TContext, TInput>(fn: (ctx: TContext, input: TInput) => TInput | Promise<TInput>): <TResult>(params: {
401
+ ctx: TContext;
402
+ input: TInput;
403
+ next: (input?: TInput) => Promise<TResult>;
404
+ [key: string]: any;
405
+ }) => Promise<TResult>;
406
+ type AnyMiddlewareParams<TContext> = {
407
+ ctx: TContext;
408
+ next: (...args: any[]) => Promise<any>;
409
+ [key: string]: any;
327
410
  };
411
+ /**
412
+ * 组合多个 middleware 为一个
413
+ *
414
+ * @example
415
+ * middleware: {
416
+ * create: composeMiddleware(
417
+ * beforeMiddleware((ctx, input) => ({ ...input, slug: slugify(input.title) })),
418
+ * afterMiddleware((ctx, result) => sendEmail(result)),
419
+ * ),
420
+ * }
421
+ */
422
+ declare function composeMiddleware<TContext, TResult>(...middlewares: Array<(params: AnyMiddlewareParams<TContext>) => Promise<any>>): (params: AnyMiddlewareParams<TContext>) => Promise<TResult>;
328
423
  //#endregion
329
424
  //#region src/routers/index.d.ts
330
- declare const appRouter: _trpc_server5.TRPCBuiltRouter<{
425
+ declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
331
426
  ctx: Context;
332
427
  meta: object;
333
- errorShape: _trpc_server5.TRPCDefaultErrorShape;
428
+ errorShape: _trpc_server2.TRPCDefaultErrorShape;
334
429
  transformer: true;
335
- }, _trpc_server5.TRPCDecorateCreateRouterOptions<{}>>;
430
+ }, _trpc_server2.TRPCDecorateCreateRouterOptions<{}>>;
336
431
  type AppRouter = typeof appRouter;
337
432
  //#endregion
338
- export { type AnyProcedure, type AppRouter, type CrudHooks, type CrudOperation, type CrudRouterConfig, type DeclarativeConfig, type FactoryConfig, type ListInput, type ListResult, type ProceduresConfig, type SoftDeleteConfig, type SoftDeleteOption, type WriteOperation, appRouter, createCrudRouter, publicProcedure, router };
433
+ export { type AnyProcedure, type AppRouter, type CreateMiddlewareParams, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudRouterConfig, type CrudRouterConfigBase, type DeclarativeConfig, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type FactoryConfig, type GetMiddlewareParams, type ListInput, type ListMiddlewareParams, type ListResult, type ProceduresConfig, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };