All files / libs/vendors/google-cloud/cloud-storage/src/lib cloud-storage-download.service.ts

70.27% Statements 26/37
66.66% Branches 2/3
66.66% Functions 2/3
70.27% Lines 26/37

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 381x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                       1x  
import { type Readable } from 'node:stream';
 
import { Storage } from '@google-cloud/storage';
import { Injectable } from '@nestjs/common';
 
import { type Company } from '@amalia/core/models';
 
import { FilePathBuilder } from './builders/file-path.builder';
 
@Injectable()
export class CloudStorageDownloadService {
  public constructor(private readonly storage: Storage) {}
 
  public streamFile(
    company: Pick<Company, 'id'>,
    folder: string,
    fileName: string,
    bucketName: string,
  ): Readable | null {
    const filePath = FilePathBuilder.forCompany(company).withFolder(folder).withFileName(fileName).build();
 
    return this.storage.bucket(bucketName).file(filePath).createReadStream() as Readable | null;
  }
 
  public async getFileAsBase64(
    company: Pick<Company, 'id'>,
    folder: string,
    fileName: string,
    bucketName: string,
  ): Promise<string> {
    const filePath = FilePathBuilder.forCompany(company).withFolder(folder).withFileName(fileName).build();

    const [buffer] = await this.storage.bucket(bucketName).file(filePath).download();

    return buffer.toString('base64');
  }
}