Generate signed URL
One script reply has been approved by the moderators Verified
Created by jansteinark898 386 days ago Picked 6 times
Submitted by jansteinark898 Bun
Verified 25 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} 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
  // 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
  const protocol = s3Resource.useSSL ? 'https' : 'http';
30
  const endpoint = `${protocol}://${s3Resource.endPoint}${s3Resource.port ? ':' + s3Resource.port : ''}`;
31

32
  // Initialize S3 client with credentials from the S3 resource
33
  const s3Client = new S3Client({
34
    region,
35
    endpoint,
36
    forcePathStyle: s3Resource.pathStyle,
37
    credentials: {
38
      accessKeyId: s3Resource.accessKey, // Use access key from the S3 resource
39
      secretAccessKey: s3Resource.secretKey, // Use secret key from the S3 resource
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, // Use the key from the S3Object parameter
50
  });
51

52
  const presignedUrl = await getSignedUrl(s3Client, getCommand, { expiresIn });
53

54
  return presignedUrl;
55

56
}