33} from '@aws-sdk/client-s3' ;
44import { getSignedUrl } from '@aws-sdk/s3-request-presigner' ;
55import { Request , Response } from 'express' ;
6+ import crypto from 'crypto' ;
7+ import path from 'path' ;
8+ import { makeId } from '@gitroom/nestjs-libraries/services/make.is' ;
69
710const { CLOUDFLARE_ACCOUNT_ID , CLOUDFLARE_ACCESS_KEY , CLOUDFLARE_SECRET_ACCESS_KEY , CLOUDFLARE_BUCKETNAME , CLOUDFLARE_BUCKET_URL } =
811 process . env ;
@@ -16,12 +19,16 @@ const R2 = new S3Client({
1619 } ,
1720} ) ;
1821
22+ // Function to generate a random string
23+ function generateRandomString ( ) {
24+ return makeId ( 20 ) ;
25+ }
26+
1927export default async function handleR2Upload (
2028 endpoint : string ,
2129 req : Request ,
2230 res : Response
2331) {
24-
2532 switch ( endpoint ) {
2633 case 'create-multipart-upload' :
2734 return createMultipartUpload ( req , res ) ;
@@ -39,30 +46,35 @@ export default async function handleR2Upload(
3946 return res . status ( 404 ) . end ( ) ;
4047}
4148
42- export async function simpleUpload ( data : Buffer , key : string , contentType : string ) {
49+ export async function simpleUpload ( data : Buffer , originalFilename : string , contentType : string ) {
50+ const fileExtension = path . extname ( originalFilename ) ; // Extract extension
51+ const randomFilename = generateRandomString ( ) + fileExtension ; // Append extension
52+
4353 const params = {
4454 Bucket : CLOUDFLARE_BUCKETNAME ,
45- Key : key ,
55+ Key : randomFilename ,
4656 Body : data ,
4757 ContentType : contentType ,
4858 } ;
4959
5060 const command = new PutObjectCommand ( { ...params } ) ;
5161 await R2 . send ( command ) ;
5262
53- return CLOUDFLARE_BUCKET_URL + '/' + key ;
63+ return CLOUDFLARE_BUCKET_URL + '/' + randomFilename ;
5464}
5565
5666export async function createMultipartUpload (
5767 req : Request ,
5868 res : Response
5969) {
6070 const { file, fileHash, contentType } = req . body ;
61- const filename = file . name ;
71+ const fileExtension = path . extname ( file . name ) ; // Extract extension
72+ const randomFilename = generateRandomString ( ) + fileExtension ; // Append extension
73+
6274 try {
6375 const params = {
6476 Bucket : CLOUDFLARE_BUCKETNAME ,
65- Key : `resources/ ${ fileHash } / ${ filename } ` ,
77+ Key : `${ randomFilename } ` ,
6678 ContentType : contentType ,
6779 Metadata : {
6880 'x-amz-meta-file-hash' : fileHash ,
0 commit comments