Created
August 14, 2023 23:56
-
-
Save micaiah-effiong/6349a455dd4845f06558fd0e64d9ff78 to your computer and use it in GitHub Desktop.
google cloud storage service for Nestjs
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, InternalServerErrorException } from '@nestjs/common'; | |
| import { Storage, Bucket, File } from '@google-cloud/storage'; | |
| import StorageKeyFile from 'src/config/storage-service-account.json'; | |
| import { ConfigService } from '@nestjs/config'; | |
| import { ENV } from 'src/config'; | |
| import { BucketDirectories } from './constants'; | |
| @Injectable() | |
| export class StorageService { | |
| private gcStorage = new Storage({ | |
| projectId: StorageKeyFile.project_id, | |
| credentials: StorageKeyFile, | |
| }); | |
| constructor(private readonly configService: ConfigService<ENV>) {} | |
| private getBucketName(): string { | |
| const _bucketName = this.configService.getOrThrow('storage'); | |
| if (!_bucketName) { | |
| throw new InternalServerErrorException('No storage name'); | |
| } | |
| return _bucketName; | |
| } | |
| async create( | |
| file: Express.Multer.File | Buffer, | |
| filename: string, | |
| bucketDirectory: BucketDirectories = BucketDirectories.default, | |
| ): Promise<{ name: string; url: string }> { | |
| const bucket = new Bucket(this.gcStorage, this.getBucketName()); | |
| const timestampCode = Date.now().toString(36); | |
| const newFilename = `${bucketDirectory}/${timestampCode}_${filename}`; | |
| const fileStorage = new File(bucket, newFilename); | |
| const fileBuffer: Buffer = file.buffer | |
| ? (file.buffer as Buffer) | |
| : (file as Buffer); | |
| if ((await fileStorage.exists())[0]) { | |
| const data = { name: newFilename, url: fileStorage.publicUrl() }; | |
| return data; | |
| } | |
| await fileStorage.save(fileBuffer); | |
| await fileStorage.makePublic(); | |
| return { name: newFilename, url: fileStorage.publicUrl() }; | |
| } | |
| async remove(filename: string): Promise<void> { | |
| const bucket = new Bucket(this.gcStorage, this.getBucketName()); | |
| const fileStorage = new File(bucket, filename); | |
| if ((await fileStorage.exists())[0]) { | |
| return void 0; | |
| } | |
| await fileStorage.delete(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment