From 6d506007a54fd85d5be6339ff7f4cf710ba0a49c Mon Sep 17 00:00:00 2001 From: Regalijan Date: Fri, 22 Mar 2024 15:55:27 -0400 Subject: [PATCH] Create R2 upload generator --- functions/api/upload.ts | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 functions/api/upload.ts diff --git a/functions/api/upload.ts b/functions/api/upload.ts new file mode 100644 index 0000000..154a5ad --- /dev/null +++ b/functions/api/upload.ts @@ -0,0 +1,40 @@ +import { AwsClient } from "aws4fetch"; + +const contentTypes: { [k: string]: string } = { + gif: "image/gif", + m4v: "video/x-m4v", + mkv: "video/x-matroska", + mov: "video/mp4", + mp4: "video/mp4", + webm: "video/webm", + wmv: "video/x-ms-wmv", +}; + +export default async function ( + env: Env, + path: string, + size: number, + extension: string, +) { + const aws = new AwsClient({ + accessKeyId: env.R2_ACCESS_KEY, + secretAccessKey: env.R2_SECRET_KEY, + }); + + return ( + await aws.sign( + `https://car-crushers.${env.R2_ZONE}.r2.cloudflarestorage.com/${path}`, + { + aws: { + allHeaders: true, + signQuery: true, + }, + headers: { + "content-length": size.toString(), + "content-type": contentTypes[extension], + }, + method: "PUT", + }, + ) + ).url; +}