| 27 | } |
| 28 | |
| 29 | async function handler(request: NextApiRequest, response: NextApiResponse) { |
| 30 | if (request.method === 'OPTIONS') { |
| 31 | return preflight(request, response, ['POST']); |
| 32 | } |
| 33 | cors(request, response); |
| 34 | |
| 35 | if (request.method === 'POST') { |
| 36 | const schema = z.object({ |
| 37 | communityId: z.string(), |
| 38 | type: z.nativeEnum(UploadEnum), |
| 39 | }); |
| 40 | |
| 41 | const parsedReq = schema.parse(request.query); |
| 42 | |
| 43 | // const permissions = await PermissionsService.get({ |
| 44 | // request, |
| 45 | // response, |
| 46 | // params: { communityId: parsedReq.communityId }, |
| 47 | // }); |
| 48 | |
| 49 | // if (!permissions.chat) { |
| 50 | // return response.status(401).json({}); |
| 51 | // } |
| 52 | |
| 53 | // we could refactor this to use fileWriteStreamHandler and send to s3 directly |
| 54 | const form = formidable({ |
| 55 | ...(parsedReq.type === 'slack-import' |
| 56 | ? { |
| 57 | maxFileSize: FILE_SIZE_LIMIT_IN_BYTES * 1000, // 2gb |
| 58 | } |
| 59 | : { |
| 60 | maxFileSize: FILE_SIZE_LIMIT_IN_BYTES, // 2mb |
| 61 | }), |
| 62 | maxFields: 10, |
| 63 | keepExtensions: true, |
| 64 | allowEmptyFiles: false, |
| 65 | }); |
| 66 | |
| 67 | try { |
| 68 | const files: File[] = await new Promise((resolve, reject) => { |
| 69 | form.parse(request, function (error, _, files) { |
| 70 | if (error) { |
| 71 | return reject(error); |
| 72 | } |
| 73 | resolve(Object.values(files) as any); |
| 74 | }); |
| 75 | }); |
| 76 | const data = await Promise.all( |
| 77 | files.map(async (file) => { |
| 78 | const buffer = await readFile(file.filepath); |
| 79 | const name = normalizeFilename(file.originalFilename); |
| 80 | return await UploadService.upload( |
| 81 | { |
| 82 | id: name, |
| 83 | name, |
| 84 | buffer, |
| 85 | }, |
| 86 | parsedReq.type |