All files / src/components/aws/services aws-s3.service.ts

12% Statements 6/50
0% Branches 0/20
11.11% Functions 1/9
12% Lines 6/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 1581x 1x 1x 1x           1x       18x                                                                                                                                                                                                                                                                                                
import { StringUtils } from '@logchain/utils';
import {HttpErrors} from '@loopback/rest';
import {S3} from 'aws-sdk';
import {AwsConfigs} from '../../../configs';
import {WalletBucketPutObjectRequest} from './aws-wallet.service';
 
/**
 * AWS S3 Service
 */
export class AwsS3Service {
  s3: S3;
 
  constructor() {
    this.s3 = new S3();
  }
 
  /**
   * Delete S3 Object by key.
   * @param key The S3 key
   */
  async deleteObject(key?: string, bucketName = AwsConfigs.s3Config.bucketName): Promise<S3.Types.DeleteObjectOutput | void> {
    if (!key) {
      return;
    }
 
    const params = {
      Bucket: bucketName,
      Key: key,
    };
 
    return this.s3.deleteObject(params).promise();
  }
 
  /**
   * Delete multiple S3 Object by key.
   * @param keys The S3 keys
   */
  async deleteObjects(keys?: string[]): Promise<S3.Types.DeleteObjectOutput | void> {
    const {s3Config} = AwsConfigs;
    if (!keys || !keys.length) {
      return;
    }
 
    const object_identifier_list = keys.map(key => {
      return {
        Key: key,
      };
    });
 
    const params = {
      Bucket: s3Config.bucketName,
      Delete: {
        Objects: object_identifier_list,
      },
    };
 
    return this.s3.deleteObjects(params).promise();
  }
 
  /**
   * Get metadata of Object in S3.
   * @param key The key of Object.
   */
  async getObjectMetadata(key: string): Promise<S3.Types.HeadObjectOutput> {
    const {s3Config} = AwsConfigs;
    const params = {
      Bucket: s3Config.bucketName,
      Key: key,
    };
 
    try {
      return await this.s3.headObject(params).promise();
    } catch (error) {
      if (error.code === 'NotFound') {
        throw new HttpErrors.NotFound(`File not found in bucket key: ${key}`);
      }
 
      throw error;
    }
  }
 
  /**
   * Get an Object in S3.
   * @param key The key of Object.
   */
  async getObject(key: string, bucketName: string = AwsConfigs.s3Config.bucketName) {
    const params = {
      Bucket: bucketName,
      Key: key,
    };
 
    try {
      return await this.s3.getObject(params).promise();
    } catch (error) {
      if (error.code === 'NotFound') {
        throw new Error(`File not found in bucket key: ${key}`);
      }
      throw error;
    }
  }
  
  /**
   * Put file into S3.
   * @param  {WalletBucketPutObjectRequest} data
   */
  async putObject(data: WalletBucketPutObjectRequest) {
    const {s3Config} = AwsConfigs;
    data.Bucket = data.Bucket ? data.Bucket : s3Config.bucketName;
    const params = {
      ...data,
    } as S3.PutObjectRequest;
    return this.s3.putObject(params).promise();
  }
 
  async duplicateObject(key: string) {
    const { s3Config } = AwsConfigs;
    const [ label = '', ext = '' ] = key.split('.');
    const pathToFile = label.split('/');
    const newKey = pathToFile.pop() + '_' + StringUtils.randomstring() + '.' + ext;
    pathToFile.push(newKey); // Replace oldfile with newfile
    const params: S3.CopyObjectRequest = {
      CopySource: '/' + s3Config.bucketName + '/' + key,
      Bucket: s3Config.bucketName,
      Key: pathToFile.join('/'),
      ContentType: 'application/pdf',
      ServerSideEncryption: 'AES256',
    };
    try {
      const result = {
        file_name: newKey,
        s3_uri: params.Key,
        ...await this.s3.copyObject(params).promise()
      }
 
      return result;
    } catch (error) {
      if (error.code === 'NotFound') {
        throw new HttpErrors.NotFound(`File not found in bucket key: ${key}`);
      }
 
      throw error;
    }
  }
 
  /**
   * @name getBufferObjectFromS3
   * @param {*} key
   */
  async getBufferObjectFromS3(key: string) {
    if (!key) {
      return;
    }
    const data = await this.getObject(key);
 
    return {contentType: data.ContentType, body: data.Body};
  }
}