diff --git a/src/app/api/upload/eco-speadsheet/route.ts b/src/app/api/upload/eco-speadsheet/route.ts new file mode 100644 index 0000000..931241e --- /dev/null +++ b/src/app/api/upload/eco-speadsheet/route.ts @@ -0,0 +1,59 @@ +import S3 from "aws-sdk/clients/s3"; +import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; + +const presignedUrlSchema = z.object({ + files: z.array( + z.object({ + fileKey: z.string(), + contentType: z.string(), + }) + ), +}); + +export async function POST(request: NextRequest) { + const body = await request.json(); + let validatedBody; + + try { + validatedBody = presignedUrlSchema.parse(body); + } catch (error) { + console.error("Invalid input: ", error); + return new NextResponse(JSON.stringify({ msg: "Invalid input" }), { + status: 400, + }); + } + + console.log("UPLOAD BODY", validatedBody); + + try { + const s3 = new S3({ + signatureVersion: "v4", + region: process.env.ECO_SPREADSHEET_AWS_REGION, + accessKeyId: process.env.ECO_SPREADSHEET_AWS_ACCESS_KEY, + secretAccessKey: process.env.ECO_SPREADSHEET_AWS_SECRET_KEY, + }); + + const { files } = validatedBody; + // generate a presigned URL for each file + const preSignedUrls = await Promise.all( + files.map(async (file: any) => { + return s3.getSignedUrlPromise("putObject", { + Bucket: process.env.ECO_SPREADSHEET_BUCKET, + Key: file.fileKey, + ContentType: file.contentType, + Expires: 5 * 60, + }); + }) + ); + + return new NextResponse(JSON.stringify({ urls: preSignedUrls }), { + status: 200, + }); + } catch (error) { + console.error(error); + return new NextResponse(JSON.stringify({ msg: "Internal server error" }), { + status: 500, + }); + } +}