2
0

generic-crud.routes.ts 14 KB

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