All files / lib/lambda getUploadUrl.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 1/1
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                1x       1x 4x 4x 3x   3x 1x         2x 2x 2x 2x 2x 2x                     1x         2x 2x            
import { response } from "libs/handler-lib";
import { APIGatewayEvent } from "aws-lambda";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { v4 as uuidv4 } from "uuid";
import * as path from "node:path";
import { validateEnvVariable } from "shared-utils";
 
const s3 = new S3Client({
  region: process.env.attachmentsBucketRegion,
});
 
export const handler = async (event: APIGatewayEvent) => {
  try {
    validateEnvVariable("attachmentsBucketName");
    validateEnvVariable("attachmentsBucketRegion");
 
    if (!event.body) {
      return response({
        statusCode: 400,
        body: { message: "Event body required" },
      });
    }
    const body = JSON.parse(event.body);
    const bucket = process.env.attachmentsBucketName;
    const fileName = body.fileName;
    const extension = path.extname(fileName);
    const key = `${uuidv4()}${extension}`; // ex:  123e4567-e89b-12d3-a456-426614174000.pdf
    const url = await getSignedUrl(
      s3,
      new PutObjectCommand({
        Bucket: bucket,
        Key: key,
      }),
      {
        expiresIn: 60,
      },
    );
 
    return response<unknown>({
      statusCode: 200,
      body: { url, bucket, key },
    });
  } catch (error) {
    console.error({ error });
    return response({
      statusCode: 500,
      body: { message: "Internal server error" },
    });
  }
};