| 1 | import { |
| 2 | DeleteObjectCommand, |
| 3 | GetObjectCommand, |
| 4 | PutObjectCommand, |
| 5 | S3Client, |
| 6 | } from '@aws-sdk/client-s3' |
| 7 | import { getSignedUrl } from '@aws-sdk/s3-request-presigner' |
| 8 | import { createId } from '@paralleldrive/cuid2' |
| 9 | import { env } from '@/env' |
| 10 | |
| 11 | const SIGNED_URL_EXPIRES_IN = 3600 // 1 hour |
| 12 | |
| 13 | class S3Service { |
| 14 | private readonly client: S3Client |
| 15 | private readonly bucket: string |
| 16 | |
| 17 | constructor() { |
| 18 | this.client = new S3Client({ |
| 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 = env.S3_BUCKET |
| 28 | } |
| 29 | |
| 30 | async upload( |
| 31 | buffer: Buffer, |
| 32 | contentType: string, |
| 33 | folder: string |
| 34 | ): Promise<{ key: string }> { |
| 35 | const ext = contentType.split('/')[1]?.replace('jpeg', 'jpg') ?? 'bin' |
| 36 | const key = `${folder}/${createId()}.${ext}` |
| 37 | |
| 38 | await this.client.send( |
| 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: string): Promise<string> { |
| 52 | const command = new GetObjectCommand({ |
| 53 | Bucket: this.bucket, |
| 54 | Key: key, |
| 55 | }) |
| 56 | |
| 57 | return await getSignedUrl(this.client, command, { |
| 58 | expiresIn: SIGNED_URL_EXPIRES_IN, |
| 59 | }) |
| 60 | } |
| 61 | |
| 62 | async delete(key: string): Promise<void> { |
| 63 | await this.client.send( |
| 64 | new DeleteObjectCommand({ |
| 65 | Bucket: this.bucket, |
| 66 | Key: key, |
| 67 | }) |
| 68 | ) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | export const s3Service = new S3Service() |