All files / apps/web/src/providers s3.ts

16.66% Statements 2/12
0% Branches 0/4
0% Functions 0/2
16.66% Lines 2/12

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                              6x   6x                                                                  
import * as aws from "@aws-sdk/client-s3";
 
import type { UnauthorizedContext } from "~web/handlers/context";
import { env } from "~web/utils/env";
 
export type S3Options = {
	mock?: S3Client;
};
 
type S3Client = {
	putObject: (key: string, object: Buffer) => Promise<void>;
	bucket: string;
	endpoint: string;
};
 
let s3Client: S3Client | undefined = undefined;
 
export const getS3Client = (ctx: UnauthorizedContext): S3Client => {
	if (ctx.s3Options.mock) {
		return ctx.s3Options.mock;
	}
	if (s3Client) {
		return s3Client;
	}
	const { S3_BUCKET, S3_ENDPOINT, S3_REGION, S3_ACCESS_KEY_ID, S3_SECRET_KEY } =
		env;
 
	const client = new aws.S3Client({
		endpoint: S3_ENDPOINT,
		region: S3_REGION,
		credentials: {
			accessKeyId: S3_ACCESS_KEY_ID,
			secretAccessKey: S3_SECRET_KEY,
		},
	});
	s3Client = {
		putObject: async (key, object) => {
			const command = new aws.PutObjectCommand({
				Bucket: S3_BUCKET,
				Key: key,
				Body: object,
				CacheControl: "max-age=86400",
			});
			await client.send(command);
		},
		bucket: S3_BUCKET,
		endpoint: S3_ENDPOINT,
	};
	return s3Client;
};