0
Generate signed URL
One script reply has been approved by the moderators Verified
Created by jansteinark898 23 days ago Viewed 187 times
0
Submitted by jansteinark898 Bun
Verified 23 days ago
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
// Define the S3 resource type
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} expiretime - 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, expiretime: number) {
25
  // Use the S3 resource to get credentials and configuration
26
  const bucketName = s3Resource.bucket; // Use the bucket from the S3 resource
27
  const region = s3Resource.region; // Use the region from the S3 resource
28

29

30
  // Initialize S3 client with credentials from the S3 resource
31
  const s3Client = new S3Client({
32
    region,
33
    credentials: {
34
      accessKeyId: s3Resource.accessKey, // Use access key from the S3 resource
35
      secretAccessKey: s3Resource.secretKey, // Use secret key from the S3 resource
36
    },
37
  });
38

39

40
  const getCommand = new GetObjectCommand({
41
    Bucket: bucketName,
42
    Key: file.s3, // Use the key from the S3Object parameter
43
  });
44

45
  const presignedUrl = await getSignedUrl(s3Client, getCommand, { expiresIn: expiretime });
46

47

48
  return presignedUrl;
49

50
}