3
3
} from '@aws-sdk/client-s3' ;
4
4
import { getSignedUrl } from '@aws-sdk/s3-request-presigner' ;
5
5
import { Request , Response } from 'express' ;
6
+ import crypto from 'crypto' ;
7
+ import path from 'path' ;
8
+ import { makeId } from '@gitroom/nestjs-libraries/services/make.is' ;
6
9
7
10
const { CLOUDFLARE_ACCOUNT_ID , CLOUDFLARE_ACCESS_KEY , CLOUDFLARE_SECRET_ACCESS_KEY , CLOUDFLARE_BUCKETNAME , CLOUDFLARE_BUCKET_URL } =
8
11
process . env ;
@@ -16,12 +19,16 @@ const R2 = new S3Client({
16
19
} ,
17
20
} ) ;
18
21
22
+ // Function to generate a random string
23
+ function generateRandomString ( ) {
24
+ return makeId ( 20 ) ;
25
+ }
26
+
19
27
export default async function handleR2Upload (
20
28
endpoint : string ,
21
29
req : Request ,
22
30
res : Response
23
31
) {
24
-
25
32
switch ( endpoint ) {
26
33
case 'create-multipart-upload' :
27
34
return createMultipartUpload ( req , res ) ;
@@ -39,30 +46,35 @@ export default async function handleR2Upload(
39
46
return res . status ( 404 ) . end ( ) ;
40
47
}
41
48
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
+
43
53
const params = {
44
54
Bucket : CLOUDFLARE_BUCKETNAME ,
45
- Key : key ,
55
+ Key : randomFilename ,
46
56
Body : data ,
47
57
ContentType : contentType ,
48
58
} ;
49
59
50
60
const command = new PutObjectCommand ( { ...params } ) ;
51
61
await R2 . send ( command ) ;
52
62
53
- return CLOUDFLARE_BUCKET_URL + '/' + key ;
63
+ return CLOUDFLARE_BUCKET_URL + '/' + randomFilename ;
54
64
}
55
65
56
66
export async function createMultipartUpload (
57
67
req : Request ,
58
68
res : Response
59
69
) {
60
70
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
+
62
74
try {
63
75
const params = {
64
76
Bucket : CLOUDFLARE_BUCKETNAME ,
65
- Key : `resources/ ${ fileHash } / ${ filename } ` ,
77
+ Key : `${ randomFilename } ` ,
66
78
ContentType : contentType ,
67
79
Metadata : {
68
80
'x-amz-meta-file-hash' : fileHash ,
0 commit comments