2022-06-12 17:34:33 +02:00
|
|
|
import { config, Endpoint, S3 } from 'aws-sdk'
|
|
|
|
|
|
|
|
type GeneratePresignedUrlProps = {
|
|
|
|
filePath: string
|
2022-07-01 17:52:58 +02:00
|
|
|
fileType?: string
|
2022-06-21 16:53:45 +02:00
|
|
|
sizeLimit?: number
|
2022-06-12 17:34:33 +02:00
|
|
|
}
|
|
|
|
|
2022-06-21 16:53:45 +02:00
|
|
|
const tenMB = 10 * 1024 * 1024
|
2022-07-02 08:37:35 +02:00
|
|
|
const tenMinutes = 10 * 60
|
2022-06-12 17:34:33 +02:00
|
|
|
|
|
|
|
export const generatePresignedUrl = ({
|
|
|
|
filePath,
|
|
|
|
fileType,
|
2022-06-21 16:53:45 +02:00
|
|
|
sizeLimit = tenMB,
|
2022-06-12 17:34:33 +02:00
|
|
|
}: GeneratePresignedUrlProps): S3.PresignedPost => {
|
|
|
|
if (
|
|
|
|
!process.env.S3_ENDPOINT ||
|
|
|
|
!process.env.S3_ACCESS_KEY ||
|
|
|
|
!process.env.S3_SECRET_KEY
|
|
|
|
)
|
|
|
|
throw new Error(
|
|
|
|
'S3 not properly configured. Missing one of those variables: S3_ENDPOINT, S3_ACCESS_KEY, S3_SECRET_KEY'
|
|
|
|
)
|
|
|
|
|
|
|
|
const sslEnabled =
|
|
|
|
process.env.S3_SSL && process.env.S3_SSL === 'false' ? false : true
|
|
|
|
config.update({
|
|
|
|
accessKeyId: process.env.S3_ACCESS_KEY,
|
|
|
|
secretAccessKey: process.env.S3_SECRET_KEY,
|
|
|
|
region: process.env.S3_REGION,
|
|
|
|
sslEnabled,
|
|
|
|
})
|
|
|
|
const protocol = sslEnabled ? 'https' : 'http'
|
|
|
|
const s3 = new S3({
|
|
|
|
endpoint: new Endpoint(
|
|
|
|
`${protocol}://${process.env.S3_ENDPOINT}${
|
|
|
|
process.env.S3_PORT ? `:${process.env.S3_PORT}` : ''
|
|
|
|
}`
|
|
|
|
),
|
|
|
|
})
|
|
|
|
|
|
|
|
const presignedUrl = s3.createPresignedPost({
|
|
|
|
Bucket: process.env.S3_BUCKET ?? 'typebot',
|
|
|
|
Fields: {
|
|
|
|
key: filePath,
|
|
|
|
'Content-Type': fileType,
|
|
|
|
},
|
2022-07-02 08:37:35 +02:00
|
|
|
Expires: tenMinutes,
|
2022-06-21 16:53:45 +02:00
|
|
|
Conditions: [['content-length-range', 0, sizeLimit]],
|
2022-06-12 17:34:33 +02:00
|
|
|
})
|
|
|
|
return presignedUrl
|
|
|
|
}
|