import * as fs from 'fs' ; import { AWSError , S3 } from 'aws-sdk' ; import { promisify } from 'util' ; import { Response } from 'express' ; import { Injectable , InternalServerErrorException , NotFoundException , OnModuleInit } from '@nestjs/common' ; import { AppConfigService as ConfigService } from '../../ConfigModule/service/app-config.service' ; import { PromiseResult } from 'aws-sdk/lib/request' ; const fileAccess = promisify ( fs . access ) ; @ Injectable ( ) export class UploadService implements OnModuleInit { private s3 : S3 ; constructor ( private readonly configService ) { } onModuleInit ( ) { this . s3 = new S3 ( this . configService . getAwsConfiguration ( ) ) ; } public async uploadUserPhoto ( filePath , fileBuffer ) { const params = { Bucket : this . configService . awsUserBucket , Key : filePath , Body : fileBuffer , } ; return this . s3 . putObject ( params ) . promise ( ) ; } public async getUserPhoto ( filePath ) { const params = { Bucket : this . configService . awsUserBucket , Key : filePath , } ; return this . s3 . getSignedUrlPromise ( 'getObject' , params ) ; } public async getFile ( filePath ) { const params = { Bucket : this . configService . awsUserBucket , Key : filePath , } ; return this . s3 . getObject ( params ) . promise ( ) ; } public async fileExists ( filePath ) { const params = { Bucket : this . configService . awsUserBucket , Key : filePath , } ; try { await this . s3 . headObject ( params ) . promise ( ) ; return true ; } catch ( e ) { if ( e . code === 'NotFound' ) { return false ; } throw new InternalServerErrorException ( e ) ; } } public getFilesInsideFolder ( folderName ) { const params = { Bucket : this . configService . awsUserBucket , Prefix : folderName , } ; return this . s3 . listObjectsV2 ( params ) . promise ( ) ; } public uploadDataToS3 ( filePath , data ) { const params = { Bucket : this . configService . awsUserBucket , Key : filePath , Body : JSON . stringify ( data ) , ContentType : 'application/json' , } ; return this . s3 . putObject ( params ) . promise ( ) ; } public async sendFile ( fileName , response ) { await this . ensureFileExists ( fileName ) ; await this . sendFileToResponse ( fileName , response ) ; } private async ensureFileExists ( fileName ) { try { const path = `${ __dirname }/../../../upload/${ fileName }` ; await fileAccess ( path , fs . constants . F_OK ) ; } catch ( error ) { throw new NotFoundException ( `File '${ fileName }' not found` ) ; } } private async sendFileToResponse ( fileName , response ) { const sendFile = promisify ( response . sendFile . bind ( response ) ) ; try { await sendFile ( fileName , { root : 'upload' } ) ; } catch ( error ) { throw new InternalServerErrorException ( error . message ) ; } } }