Skip to content

Instantly share code, notes, and snippets.

@micaiah-effiong
Created August 14, 2023 23:56
Show Gist options
  • Select an option

  • Save micaiah-effiong/6349a455dd4845f06558fd0e64d9ff78 to your computer and use it in GitHub Desktop.

Select an option

Save micaiah-effiong/6349a455dd4845f06558fd0e64d9ff78 to your computer and use it in GitHub Desktop.
google cloud storage service for Nestjs
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