Created
October 19, 2022 12:02
-
-
Save dcortesnet/e20a2ef20a049c3da7700225a4efc300 to your computer and use it in GitHub Desktop.
Nestjs S3 example provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Injectable } from '@nestjs/common'; | |
| import { ConfigService } from '@nestjs/config'; | |
| import AWS from 'aws-sdk'; | |
| @Injectable() | |
| export class S3Provider { | |
| private s3: AWS.S3; | |
| private bucket: string; | |
| private folder: string; | |
| constructor(private configService: ConfigService) { | |
| this.s3 = new AWS.S3({ | |
| accessKeyId: this.configService.get<string>('AWS_ACCESS_KEY_ID'), | |
| secretAccessKey: this.configService.get<string>('AWS_SECRET_KEY'), | |
| region: this.configService.get<string>('AWS_REGION'), | |
| }); | |
| this.bucket = this.configService.get<string>('AWS_S3_BUCKET_NAME'); | |
| this.folder = this.configService.get<string>('AWS_S3_BUCKET_FOLDER'); | |
| } | |
| async uploadObject(keyName: string, file: Buffer, mimeType: string) { | |
| const params = { | |
| Bucket: this.bucket, | |
| Key: this.folder + '/' + keyName, | |
| Body: file, | |
| ContentType: mimeType, | |
| }; | |
| return await this.s3.upload(params).promise(); | |
| } | |
| async deleteObject(keyName: string) { | |
| const params = { | |
| Bucket: this.bucket, | |
| Key: this.folder + '/' + keyName, | |
| }; | |
| return await this.s3.deleteObject(params).promise(); | |
| } | |
| async updateObject(keyName: string, file: Buffer, mimeType: string) { | |
| const params = { | |
| Bucket: this.bucket, | |
| Body: file, | |
| Key: this.folder + '/' + keyName, | |
| ContentType: mimeType, | |
| }; | |
| return await this.s3.putObject(params).promise(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment