|
| 1 | +import * as GCS from '@google-cloud/storage' |
| 2 | +import { green } from 'colorette' |
| 3 | +import { addDays } from 'date-fns' |
| 4 | +import fs from 'fs' |
| 5 | +import path from 'path' |
| 6 | +import { logger } from '~/config/logger' |
| 7 | +import { __dirname } from '~/lib/string' |
| 8 | +import { ms } from '../date' |
| 9 | +import { GoogleCloudStorageParams, UploadFileParams } from './types' |
| 10 | + |
| 11 | +export default class GoogleCloudStorage { |
| 12 | + public client: GCS.Storage |
| 13 | + |
| 14 | + private _access_key: string |
| 15 | + private _filepath: string |
| 16 | + private _bucket: string |
| 17 | + private _expires: string |
| 18 | + |
| 19 | + constructor(params: GoogleCloudStorageParams) { |
| 20 | + this._access_key = params.access_key |
| 21 | + this._bucket = params.bucket |
| 22 | + this._expires = params.expires |
| 23 | + this._filepath = path.resolve(`${__dirname}/${params.filepath}`) |
| 24 | + |
| 25 | + const msgType = `${green('storage - google cloud storage')}` |
| 26 | + |
| 27 | + if (!this._access_key && !fs.existsSync(this._filepath)) { |
| 28 | + const message = `${msgType} serviceAccount is missing on root directory` |
| 29 | + logger.error(message) |
| 30 | + |
| 31 | + throw new Error( |
| 32 | + 'Missing GCP Service Account!!!\nCopy gcp-serviceAccount from your console google to root directory "gcp-serviceAccount.json"' |
| 33 | + ) |
| 34 | + } |
| 35 | + |
| 36 | + if (this._access_key) { |
| 37 | + const message = `${msgType} - ${this._filepath}` |
| 38 | + logger.info(message) |
| 39 | + } |
| 40 | + |
| 41 | + this.client = new GCS.Storage({ |
| 42 | + projectId: this._access_key, |
| 43 | + keyFilename: this._filepath, |
| 44 | + }) |
| 45 | + } |
| 46 | + |
| 47 | + private _generateKeyfile(values: string[]) { |
| 48 | + return values.join('/') |
| 49 | + } |
| 50 | + |
| 51 | + public expiresObject() { |
| 52 | + const getExpired = this._expires.replace(/[^0-9]/g, '') |
| 53 | + |
| 54 | + const expiresIn = ms(this._expires) |
| 55 | + const expiryDate = addDays(new Date(), Number(getExpired)) |
| 56 | + |
| 57 | + return { expiresIn, expiryDate } |
| 58 | + } |
| 59 | + |
| 60 | + async initialize() { |
| 61 | + const msgType = `${green('storage - google cloud storage')}` |
| 62 | + const bucketName = this._bucket |
| 63 | + |
| 64 | + try { |
| 65 | + const data = this.client.bucket(bucketName) |
| 66 | + const getBucket = await data.exists() |
| 67 | + const getMetadata = await data.getMetadata() |
| 68 | + |
| 69 | + if (getBucket[0]) { |
| 70 | + const message = `${msgType} - ${bucketName} bucket found` |
| 71 | + logger.info(message) |
| 72 | + console.log(getMetadata[0]) |
| 73 | + } |
| 74 | + } catch (error) { |
| 75 | + const message = `${msgType} - ${bucketName} bucket not found` |
| 76 | + logger.error(message) |
| 77 | + // create bucket if not exists |
| 78 | + await this._createBucket() |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private async _createBucket() { |
| 83 | + const msgType = `${green('storage - google cloud storage')}` |
| 84 | + const bucketName = this._bucket |
| 85 | + |
| 86 | + try { |
| 87 | + const data = await this.client.createBucket(bucketName) |
| 88 | + const getMetadata = await data[0].getMetadata() |
| 89 | + |
| 90 | + const message = `${msgType} - ${bucketName} bucket created` |
| 91 | + logger.info(message) |
| 92 | + console.log(getMetadata[0]) |
| 93 | + } catch (error: any) { |
| 94 | + const message = `${msgType} error: ${error.message ?? error}` |
| 95 | + logger.error(message) |
| 96 | + process.exit(1) |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + async uploadFile({ directory, file }: UploadFileParams) { |
| 101 | + const keyfile = this._generateKeyfile([directory, file.filename]) |
| 102 | + |
| 103 | + // For a destination object that does not yet exist, |
| 104 | + // set the ifGenerationMatch precondition to 0 |
| 105 | + // If the destination object already exists in your bucket, set instead a |
| 106 | + // generation-match precondition using its generation number. |
| 107 | + const generationMatchPrecondition = 0 |
| 108 | + |
| 109 | + const options: GCS.UploadOptions = { |
| 110 | + destination: keyfile, |
| 111 | + preconditionOpts: { ifGenerationMatch: generationMatchPrecondition }, |
| 112 | + } |
| 113 | + |
| 114 | + const data = await this.client.bucket(this._bucket).upload(file.path, options) |
| 115 | + const signedUrl = await this.presignedURL(keyfile) |
| 116 | + |
| 117 | + return { data: data[1], signedUrl } |
| 118 | + } |
| 119 | + |
| 120 | + async presignedURL(keyfile: string) { |
| 121 | + const msgType = `${green('storage - google cloud storage')}` |
| 122 | + const bucketName = this._bucket |
| 123 | + |
| 124 | + const { expiresIn } = this.expiresObject() |
| 125 | + const options: GCS.GetSignedUrlConfig = { |
| 126 | + version: 'v4', |
| 127 | + action: 'read', |
| 128 | + virtualHostedStyle: true, |
| 129 | + expires: Date.now() + expiresIn, |
| 130 | + } |
| 131 | + |
| 132 | + const data = await this.client.bucket(bucketName).file(keyfile).getSignedUrl(options) |
| 133 | + const signedUrl = data[0] |
| 134 | + |
| 135 | + const message = `${msgType} - ${keyfile} presigned URL generated` |
| 136 | + logger.info(message) |
| 137 | + |
| 138 | + return signedUrl |
| 139 | + } |
| 140 | +} |
0 commit comments