post.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
  2. import { FileService } from '@/server/modules/files/file.service';
  3. import { FileSchema, CreateFileDto } from '@/server/modules/files/file.schema';
  4. import { ErrorSchema } from '@/server/utils/errorHandler';
  5. import { AppDataSource } from '@/server/data-source';
  6. import { AuthContext } from '@/server/types/context';
  7. import { authMiddleware } from '@/server/middleware/auth.middleware';
  8. import { parseWithAwait } from '@/server/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. console.debug('user', user)
  60. // 创建文件服务实例
  61. const fileService = new FileService(AppDataSource);
  62. // 添加用户ID到文件数据
  63. const fileData = {
  64. ...data,
  65. uploadUserId: user.id,
  66. uploadTime: new Date()
  67. };
  68. const result = await fileService.createFile(fileData);
  69. console.debug('result', result)
  70. const typedResult = await parseWithAwait(CreateFileResponseSchema, result);
  71. return c.json(typedResult, 200);
  72. } catch (error) {
  73. if (error instanceof z.ZodError) {
  74. return c.json({
  75. code: 400,
  76. message: '参数错误',
  77. errors: error.issues
  78. }, 400);
  79. }
  80. const message = error instanceof Error ? error.message : '生成上传策略失败';
  81. return c.json({ code: 500, message }, 500);
  82. }
  83. });
  84. export default app;