| 1 | import { |
| 2 | DeleteObjectCommand, |
| 3 | GetObjectCommand, |
| 4 | PutObjectCommand, |
| 5 | S3Client, |
| 6 | } from '@aws-sdk/client-s3' |
| 7 | import { getSignedUrl } |
| 8 | import { createId } |
| 9 | import { env } |
| 10 | |
| 11 | const SIGNED_URL_EXPIRES_IN = 3600 |
| 12 | |
| 13 | class S3Service { |
| 14 | private readonly client |
| 15 | private readonly bucket |
| 16 | |
| 17 | constructor() { |
| 18 | this.client = |
| 19 | endpoint: env.S3_ENDPOINT |
| 20 | region: env.S3_REGION |
| 21 | credentials: { |
| 22 | accessKeyId: env.S3_ACCESS_KEY_ID |
| 23 | secretAccessKey: env.S3_SECRET_ACCESS_KEY |
| 24 | }, |
| 25 | forcePathStyle: true, |
| 26 | }) |
| 27 | this.bucket = |
| 28 | } |
| 29 | |
| 30 | async upload( |
| 31 | buffer: Buffer |
| 32 | contentType: string, |
| 33 | folder: string |
| 34 | ): Promise |
| 35 | const ext = |
| 36 | const key = |
| 37 | |
| 38 | await this.client |
| 39 | new PutObjectCommand({ |
| 40 | Bucket: this.bucket |
| 41 | Key: key, |
| 42 | Body: buffer, |
| 43 | ContentType: contentType, |
| 44 | CacheControl: 'private, max-age=3600', |
| 45 | }) |
| 46 | ) |
| 47 | |
| 48 | return { key |
| 49 | } |
| 50 | |
| 51 | async getSignedUrl(key |
| 52 | const command = |
| 53 | Bucket: this.bucket |
| 54 | Key: key, |
| 55 | }) |
| 56 | |
| 57 | return await getSignedUrl |
| 58 | expiresIn: SIGNED_URL_EXPIRES_IN, |
| 59 | }) |
| 60 | } |
| 61 | |
| 62 | async delete(key |
| 63 | await this.client |
| 64 | new DeleteObjectCommand({ |
| 65 | Bucket: this.bucket |
| 66 | Key: key, |
| 67 | }) |
| 68 | ) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | export const s3Service = |