generic-crud.routes.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from '@hono/zod-openapi';
  3. import { GenericCrudService, CrudOptions } from './generic-crud.service';
  4. import { ErrorSchema } from './errorHandler';
  5. import { AuthContext } from '../types/context';
  6. import { ObjectLiteral } from 'typeorm';
  7. import { AppDataSource } from '../data-source';
  8. import { parseWithAwait } from './parseWithAwait';
  9. export function createCrudRoutes<
  10. T extends ObjectLiteral,
  11. CreateSchema extends z.ZodSchema = z.ZodSchema,
  12. UpdateSchema extends z.ZodSchema = z.ZodSchema,
  13. GetSchema extends z.ZodSchema = z.ZodSchema,
  14. ListSchema extends z.ZodSchema = z.ZodSchema
  15. >(options: CrudOptions<T, CreateSchema, UpdateSchema, GetSchema, ListSchema>) {
  16. const { entity, createSchema, updateSchema, getSchema, listSchema, searchFields, relations, middleware = [], userTracking, relationFields, readOnly = false } = options;
  17. // 创建CRUD服务实例
  18. // 抽象类不能直接实例化,需要创建具体实现类
  19. class ConcreteCrudService extends GenericCrudService<T> {
  20. constructor() {
  21. super(AppDataSource, entity, { userTracking, relationFields });
  22. }
  23. }
  24. const crudService = new ConcreteCrudService();
  25. // 创建路由实例
  26. const app = new OpenAPIHono<AuthContext>();
  27. // 分页查询路由
  28. const listRoute = createRoute({
  29. method: 'get',
  30. path: '/',
  31. middleware,
  32. request: {
  33. query: z.object({
  34. page: z.coerce.number<number>().int().positive().default(1).openapi({
  35. example: 1,
  36. description: '页码,从1开始'
  37. }),
  38. pageSize: z.coerce.number<number>().int().positive().default(10).openapi({
  39. example: 10,
  40. description: '每页数量'
  41. }),
  42. keyword: z.string().optional().openapi({
  43. example: '搜索关键词',
  44. description: '搜索关键词'
  45. }),
  46. sortBy: z.string().optional().openapi({
  47. example: 'createdAt',
  48. description: '排序字段'
  49. }),
  50. sortOrder: z.enum(['ASC', 'DESC']).optional().default('DESC').openapi({
  51. example: 'DESC',
  52. description: '排序方向'
  53. }),
  54. // 增强的筛选参数
  55. filters: z.string().optional().openapi({
  56. example: '{"status": 1, "createdAt": {"gte": "2024-01-01", "lte": "2024-12-31"}}',
  57. description: '筛选条件(JSON字符串),支持精确匹配、范围查询、IN查询等'
  58. })
  59. })
  60. },
  61. responses: {
  62. 200: {
  63. description: '成功获取列表',
  64. content: {
  65. 'application/json': {
  66. schema: z.object({
  67. data: z.array(listSchema),
  68. pagination: z.object({
  69. total: z.number().openapi({ example: 100, description: '总记录数' }),
  70. current: z.number().openapi({ example: 1, description: '当前页码' }),
  71. pageSize: z.number().openapi({ example: 10, description: '每页数量' })
  72. })
  73. })
  74. }
  75. }
  76. },
  77. 400: {
  78. description: '参数错误',
  79. content: { 'application/json': { schema: ErrorSchema } }
  80. },
  81. 500: {
  82. description: '服务器错误',
  83. content: { 'application/json': { schema: ErrorSchema } }
  84. }
  85. }
  86. });
  87. // 创建资源路由
  88. const createRouteDef = createRoute({
  89. method: 'post',
  90. path: '/',
  91. middleware,
  92. request: {
  93. body: {
  94. content: {
  95. 'application/json': { schema: createSchema }
  96. }
  97. }
  98. },
  99. responses: {
  100. 201: {
  101. description: '创建成功',
  102. content: { 'application/json': { schema: getSchema } }
  103. },
  104. 400: {
  105. description: '输入数据无效',
  106. content: { 'application/json': { schema: ErrorSchema } }
  107. },
  108. 500: {
  109. description: '服务器错误',
  110. content: { 'application/json': { schema: ErrorSchema } }
  111. }
  112. }
  113. });
  114. // 获取单个资源路由
  115. const getRouteDef = createRoute({
  116. method: 'get',
  117. path: '/{id}',
  118. middleware,
  119. request: {
  120. params: z.object({
  121. id: z.coerce.number<number>().openapi({
  122. param: { name: 'id', in: 'path' },
  123. example: 1,
  124. description: '资源ID'
  125. })
  126. })
  127. },
  128. responses: {
  129. 200: {
  130. description: '成功获取详情',
  131. content: { 'application/json': { schema: getSchema } }
  132. },
  133. 400: {
  134. description: '资源不存在',
  135. content: { 'application/json': { schema: ErrorSchema } }
  136. },
  137. 404: {
  138. description: '参数验证失败',
  139. content: { 'application/json': { schema: ErrorSchema } }
  140. },
  141. 500: {
  142. description: '服务器错误',
  143. content: { 'application/json': { schema: ErrorSchema } }
  144. }
  145. }
  146. });
  147. // 更新资源路由
  148. const updateRouteDef = createRoute({
  149. method: 'put',
  150. path: '/{id}',
  151. middleware,
  152. request: {
  153. params: z.object({
  154. id: z.coerce.number<number>().openapi({
  155. param: { name: 'id', in: 'path' },
  156. example: 1,
  157. description: '资源ID'
  158. })
  159. }),
  160. body: {
  161. content: {
  162. 'application/json': { schema: updateSchema }
  163. }
  164. }
  165. },
  166. responses: {
  167. 200: {
  168. description: '更新成功',
  169. content: { 'application/json': { schema: getSchema } }
  170. },
  171. 400: {
  172. description: '无效输入',
  173. content: { 'application/json': { schema: ErrorSchema } }
  174. },
  175. 404: {
  176. description: '资源不存在',
  177. content: { 'application/json': { schema: ErrorSchema } }
  178. },
  179. 500: {
  180. description: '服务器错误',
  181. content: { 'application/json': { schema: ErrorSchema } }
  182. }
  183. }
  184. });
  185. // 删除资源路由
  186. const deleteRouteDef = createRoute({
  187. method: 'delete',
  188. path: '/{id}',
  189. middleware,
  190. request: {
  191. params: z.object({
  192. id: z.coerce.number<number>().openapi({
  193. param: { name: 'id', in: 'path' },
  194. example: 1,
  195. description: '资源ID'
  196. })
  197. })
  198. },
  199. responses: {
  200. 204: { description: '删除成功' },
  201. 404: {
  202. description: '资源不存在',
  203. content: { 'application/json': { schema: ErrorSchema } }
  204. },
  205. 500: {
  206. description: '服务器错误',
  207. content: { 'application/json': { schema: ErrorSchema } }
  208. }
  209. }
  210. });
  211. // 注册路由处理函数
  212. // 只读模式下只注册 GET 路由
  213. if (!readOnly) {
  214. // 完整 CRUD 路由
  215. const routes = app
  216. .openapi(listRoute, async (c) => {
  217. try {
  218. const query = c.req.valid('query') as any;
  219. const { page, pageSize, keyword, sortBy, sortOrder, filters } = query;
  220. // 构建排序对象
  221. const order: any = {};
  222. if (sortBy) {
  223. order[sortBy] = sortOrder || 'DESC';
  224. } else {
  225. order['id'] = 'DESC';
  226. }
  227. // 解析筛选条件
  228. let parsedFilters: any = undefined;
  229. if (filters) {
  230. try {
  231. parsedFilters = JSON.parse(filters);
  232. } catch (e) {
  233. return c.json({ code: 400, message: '筛选条件格式错误' }, 400);
  234. }
  235. }
  236. const [data, total] = await crudService.getList(
  237. page,
  238. pageSize,
  239. keyword,
  240. searchFields,
  241. undefined,
  242. relations || [],
  243. order,
  244. parsedFilters
  245. );
  246. return c.json({
  247. // data: z.array(listSchema).parse(data),
  248. data: await parseWithAwait(z.array(listSchema), data),
  249. pagination: { total, current: page, pageSize }
  250. }, 200);
  251. } catch (error) {
  252. if (error instanceof z.ZodError) {
  253. return c.json({ code: 400, message: '参数验证失败', errors: JSON.parse(error.message) }, 400);
  254. }
  255. return c.json({
  256. code: 500,
  257. message: error instanceof Error ? error.message : '获取列表失败'
  258. }, 500);
  259. }
  260. })
  261. .openapi(createRouteDef, async (c: any) => {
  262. try {
  263. const data = c.req.valid('json');
  264. const user = c.get('user');
  265. const result = await crudService.create(data, user?.id);
  266. return c.json(result, 201);
  267. } catch (error) {
  268. if (error instanceof z.ZodError) {
  269. return c.json({ code: 400, message: '参数验证失败', errors: JSON.parse(error.message) }, 400);
  270. }
  271. return c.json({
  272. code: 500,
  273. message: error instanceof Error ? error.message : '创建资源失败'
  274. }, 500);
  275. }
  276. })
  277. .openapi(getRouteDef, async (c: any) => {
  278. try {
  279. const { id } = c.req.valid('param');
  280. const result = await crudService.getById(id, relations || []);
  281. if (!result) {
  282. return c.json({ code: 404, message: '资源不存在' }, 404);
  283. }
  284. // return c.json(await getSchema.parseAsync(result), 200);
  285. return c.json(await parseWithAwait(getSchema, result), 200);
  286. } catch (error) {
  287. if (error instanceof z.ZodError) {
  288. return c.json({ code: 400, message: '参数验证失败', errors: JSON.parse(error.message) }, 400);
  289. }
  290. return c.json({
  291. code: 500,
  292. message: error instanceof Error ? error.message : '获取资源失败'
  293. }, 500);
  294. }
  295. })
  296. .openapi(updateRouteDef, async (c: any) => {
  297. try {
  298. const { id } = c.req.valid('param');
  299. const data = c.req.valid('json');
  300. const user = c.get('user');
  301. const result = await crudService.update(id, data, user?.id);
  302. if (!result) {
  303. return c.json({ code: 404, message: '资源不存在' }, 404);
  304. }
  305. return c.json(result, 200);
  306. } catch (error) {
  307. if (error instanceof z.ZodError) {
  308. return c.json({ code: 400, message: '参数验证失败', errors: JSON.parse(error.message) }, 400);
  309. }
  310. return c.json({
  311. code: 500,
  312. message: error instanceof Error ? error.message : '更新资源失败'
  313. }, 500);
  314. }
  315. })
  316. .openapi(deleteRouteDef, async (c: any) => {
  317. try {
  318. const { id } = c.req.valid('param');
  319. const success = await crudService.delete(id);
  320. if (!success) {
  321. return c.json({ code: 404, message: '资源不存在' }, 404);
  322. }
  323. return c.body(null, 204);
  324. } catch (error) {
  325. if (error instanceof z.ZodError) {
  326. return c.json({ code: 400, message: '参数验证失败', errors: JSON.parse(error.message) }, 400);
  327. }
  328. return c.json({
  329. code: 500,
  330. message: error instanceof Error ? error.message : '删除资源失败'
  331. }, 500);
  332. }
  333. });
  334. return routes;
  335. } else {
  336. // 只读模式,只注册 GET 路由
  337. const routes = app
  338. .openapi(listRoute, async (c) => {
  339. try {
  340. const query = c.req.valid('query') as any;
  341. const { page, pageSize, keyword, sortBy, sortOrder, filters } = query;
  342. // 构建排序对象
  343. const order: any = {};
  344. if (sortBy) {
  345. order[sortBy] = sortOrder || 'DESC';
  346. } else {
  347. order['id'] = 'DESC';
  348. }
  349. // 解析筛选条件
  350. let parsedFilters: any = undefined;
  351. if (filters) {
  352. try {
  353. parsedFilters = JSON.parse(filters);
  354. } catch (e) {
  355. return c.json({ code: 400, message: '筛选条件格式错误' }, 400);
  356. }
  357. }
  358. const [data, total] = await crudService.getList(
  359. page,
  360. pageSize,
  361. keyword,
  362. searchFields,
  363. undefined,
  364. relations || [],
  365. order,
  366. parsedFilters
  367. );
  368. return c.json({
  369. data: await parseWithAwait(z.array(listSchema), data),
  370. pagination: { total, current: page, pageSize }
  371. }, 200);
  372. } catch (error) {
  373. if (error instanceof z.ZodError) {
  374. return c.json({ code: 400, message: '参数验证失败', errors: JSON.parse(error.message) }, 400);
  375. }
  376. return c.json({
  377. code: 500,
  378. message: error instanceof Error ? error.message : '获取列表失败'
  379. }, 500);
  380. }
  381. })
  382. .openapi(getRouteDef, async (c: any) => {
  383. try {
  384. const { id } = c.req.valid('param');
  385. const result = await crudService.getById(id, relations || []);
  386. if (!result) {
  387. return c.json({ code: 404, message: '资源不存在' }, 404);
  388. }
  389. return c.json(await parseWithAwait(getSchema, result), 200);
  390. } catch (error) {
  391. if (error instanceof z.ZodError) {
  392. return c.json({ code: 400, message: '参数验证失败', errors: JSON.parse(error.message) }, 400);
  393. }
  394. return c.json({
  395. code: 500,
  396. message: error instanceof Error ? error.message : '获取资源失败'
  397. }, 500);
  398. }
  399. });
  400. return routes;
  401. }
  402. }