post.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
  2. import { FileService } from '../../../modules/files/file.service';
  3. import { FileSchema, CreateFileDto } from '../../../modules/files/file.schema';
  4. import { ErrorSchema } from '../../../utils/errorHandler';
  5. import { AppDataSource } from '../../../data-source';
  6. import { AuthContext } from '../../../types/context';
  7. import { authMiddleware } from '../../../middleware/auth.middleware';
  8. import { parseWithAwait } from '../../../utils/parseWithAwait';
  9. const CreateFileResponseSchema = z.object({
  10. file: FileSchema,
  11. uploadPolicy: z.object({
  12. 'x-amz-algorithm': z.string(),
  13. 'x-amz-credential': z.string(),
  14. 'x-amz-date': z.string(),
  15. 'x-amz-security-token': z.string().optional(),
  16. policy: z.string(),
  17. 'x-amz-signature': z.string(),
  18. host: z.string(),
  19. key: z.string(),
  20. bucket: z.string()
  21. })
  22. });
  23. // 创建文件上传策略路由
  24. const createUploadPolicyRoute = createRoute({
  25. method: 'post',
  26. path: '/',
  27. middleware: [authMiddleware],
  28. request: {
  29. body: {
  30. content: {
  31. 'application/json': { schema: CreateFileDto }
  32. }
  33. }
  34. },
  35. responses: {
  36. 200: {
  37. description: '生成文件上传策略成功',
  38. content: {
  39. 'application/json': {
  40. schema: CreateFileResponseSchema
  41. }
  42. }
  43. },
  44. 400: {
  45. description: '请求参数错误',
  46. content: { 'application/json': { schema: ErrorSchema } }
  47. },
  48. 500: {
  49. description: '服务器错误',
  50. content: { 'application/json': { schema: ErrorSchema } }
  51. }
  52. }
  53. });
  54. // 创建路由实例
  55. const app = new OpenAPIHono<AuthContext>().openapi(createUploadPolicyRoute, async (c) => {
  56. try {
  57. const data = await c.req.json();
  58. const user = c.get('user');
  59. // 创建文件服务实例
  60. const fileService = new FileService(AppDataSource);
  61. // 添加用户ID到文件数据
  62. const fileData = {
  63. ...data,
  64. uploadUserId: user.id,
  65. uploadTime: new Date()
  66. };
  67. const result = await fileService.createFile(fileData);
  68. const typedResult = await parseWithAwait(CreateFileResponseSchema, result);
  69. return c.json(typedResult, 200);
  70. } catch (error) {
  71. if (error instanceof z.ZodError) {
  72. return c.json({
  73. code: 400,
  74. message: '参数错误',
  75. errors: error.issues
  76. }, 400);
  77. }
  78. const message = error instanceof Error ? error.message : '生成上传策略失败';
  79. return c.json({ code: 500, message }, 500);
  80. }
  81. });
  82. export default app;