import { Bucket, Storage, File, CopyResponse } from '@google-cloud/storage'; import { ONE_YEAR_IN_SECONDS, TO_BE_RESIZED_DIRECTORY_NAME, TO_COMPRESS_DIRECTORY_NAME } from './constants'; const storage = new Storage(); /* * Exists */ export const checkIfFileExists = async ({ bucket, filePath }: { bucket: Bucket; filePath: string }): Promise => { const [exists] = await bucket.file(filePath).exists(); if (!exists) { throw new Error(`File ${filePath} doesn't exist in bucket ${bucket.name}`); } }; /* * Utils */ export const buildFileURI = ({ bucket, filePath }: { bucket: Bucket; filePath: string }): string => `gs://${bucket.name}/${filePath}`; export const getDestination = (filePath: string): string => filePath .replace(`/${TO_BE_RESIZED_DIRECTORY_NAME}`, '') .replace(new RegExp(`/${TO_COMPRESS_DIRECTORY_NAME}`, 'gi'), ''); /* * Fetch */ export const getBucket = (bucketName: string): Bucket => storage.bucket(bucketName); /* * Download */ export const downloadFileFromBucket = async ({ bucket, localfilePath, filePath, }: { bucket: Bucket; localfilePath: string; filePath: string; }): Promise => { try { const file = bucket.file(filePath); await file.download({ destination: localfilePath }); console.log(`Successfully downloaded ${buildFileURI({ bucket, filePath })} to ${localfilePath}.`); return file; } catch (err) { throw new Error(`File ${buildFileURI({ bucket, filePath })} download failed: ${err}`); } }; /* * Upload * new: gs://static-dev.innovorder.fr/uploads/2f250927455d/minify/minify/3ec4314221577d915a77adbf0decb269.png * old: uploads/2f250927455d/minify/minify/minify/3ec4314221577d915a77adbf0decb269.png successfully deleted */ export const uploadFileToBucket = async ({ bucket, localfilePath, filePath, }: { bucket: Bucket; localfilePath: string; filePath: string; }): Promise => { try { await bucket.upload(localfilePath, { destination: getDestination(filePath), resumable: false, validation: 'md5', metadata: { cacheControl: `public, max-age=${ONE_YEAR_IN_SECONDS}`, }, public: true, }); console.log(`Succesfully uploaded image to: ${buildFileURI({ bucket, filePath: getDestination(filePath) })}`); } catch (err) { throw new Error( `Unable to upload image to ${buildFileURI({ bucket, filePath: getDestination(filePath) })}: ${err}`, ); } }; /* * Delete */ export const deleteOriginalImageFromBucket = async ({ bucket, filePath, }: { bucket: Bucket; filePath: string | File; }): Promise => { const file = typeof filePath === 'string' ? bucket.file(filePath) : filePath; await file.delete(); console.log(`Original image ${file.name} successfully deleted`); }; /* * Files */ export const copyFile = (file: File, destination: string): Promise => { return file.copy(destination); };