1 | import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3"; |
2 | import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; |
3 | import { S3Object } from 'windmill-client'; |
4 |
|
5 | |
6 | type S3 = { |
7 | port: number, |
8 | bucket: string, |
9 | region: string, |
10 | useSSL: boolean, |
11 | endPoint: string, |
12 | accessKey: string, |
13 | pathStyle: boolean, |
14 | secretKey: string |
15 | } |
16 |
|
17 | |
18 | * * Generates a presigned URL for accessing an S3 object |
19 | * @param {S3Object} file - The uploaded file |
20 | * @param {S3} s3Resource - The S3 resource configuration |
21 | * @param {number} expiresIn - The time that the link is valid. Maximum is 604800 seconds (7 days) |
22 | * @returns Promise<string> - The presigned URL |
23 | */ |
24 | export async function main(file: S3Object, s3Resource: S3, expiresIn: number) { |
25 | |
26 | const bucketName = s3Resource.bucket; |
27 | const region = s3Resource.region; |
28 |
|
29 | const protocol = s3Resource.useSSL ? 'https' : 'http'; |
30 | const endpoint = `${protocol}://${s3Resource.endPoint}${s3Resource.port ? ':' + s3Resource.port : ''}`; |
31 |
|
32 | |
33 | const s3Client = new S3Client({ |
34 | region, |
35 | endpoint, |
36 | forcePathStyle: s3Resource.pathStyle, |
37 | credentials: { |
38 | accessKeyId: s3Resource.accessKey, |
39 | secretAccessKey: s3Resource.secretKey, |
40 | }, |
41 | }); |
42 |
|
43 | if (typeof file === 'string') { |
44 | throw new Error("This script does not support S3Object in string format") |
45 | } |
46 |
|
47 | const getCommand = new GetObjectCommand({ |
48 | Bucket: bucketName, |
49 | Key: file.s3, |
50 | }); |
51 |
|
52 | const presignedUrl = await getSignedUrl(s3Client, getCommand, { expiresIn }); |
53 |
|
54 | return presignedUrl; |
55 |
|
56 | } |