import { checkIfFileExists, deleteOriginalImageFromBucket, downloadFileFromBucket, getBucket, uploadFileToBucket, } from './buckets'; import { deleteFile, getFilename, getLocalFilePath } from './local'; import { resizeImageToFitDimensions, shouldResizeImage } from './resize'; import { compressImage, shouldCompressImage } from './compress'; import { RESULT_RETURN_LABELS } from './constants'; const getReturnLabel = ({ shouldCompress, shouldResize, }: { shouldCompress: boolean; shouldResize: boolean; }): RESULT_RETURN_LABELS => { switch (true) { case !shouldCompress && !shouldResize: return RESULT_RETURN_LABELS.NOTHING_TO_DO; case shouldCompress && !shouldResize: return RESULT_RETURN_LABELS.ONLY_COMPRESS; case shouldResize && !shouldCompress: return RESULT_RETURN_LABELS.ONLY_RESIZE; case shouldResize && shouldCompress: default: return RESULT_RETURN_LABELS.BOTH; } }; // This method implements the call from Cloud Storage new object trigger https://cloud.google.com/functions/docs/calling/storage#object_finalize const compressAndResizeBucketImage = async ( { bucket: bucketName, name: filePath }: { bucket: string; name: string }, // eslint-disable-next-line @typescript-eslint/no-explicit-any context: any, callback: (e: Error | null, label?: RESULT_RETURN_LABELS) => void, ): Promise => { try { /* * PREPARE */ const shouldResize = shouldResizeImage(filePath); const shouldCompress = shouldCompressImage(filePath); if (!shouldResize && !shouldCompress) { return callback(null, getReturnLabel({ shouldResize, shouldCompress })); } console.log(`[TRIGGERED] Compress and Resizing ${filePath}`); const bucket = getBucket(bucketName); const filename = getFilename(filePath); const localfilePath = getLocalFilePath(filename); /* * FETCH */ await checkIfFileExists({ bucket, filePath }); const file = await downloadFileFromBucket({ bucket, localfilePath, filePath }); /* * RESIZE */ if (shouldResize) { await resizeImageToFitDimensions(localfilePath); } /* * COMPRESS */ if (shouldCompress) { await compressImage(localfilePath); } /* * UPLOAD */ // Upload resized image to base_directory await uploadFileToBucket({ bucket, localfilePath, filePath }); /* * CLEAN */ // Remove image from base_directory/toBeResized await deleteOriginalImageFromBucket({ bucket, filePath: file }); await deleteFile(localfilePath); // callback const returnLabel = getReturnLabel({ shouldResize, shouldCompress }); return callback(null, returnLabel); } catch (e) { // TODO(@kevin ?): handle error console.error(e); return callback(e as Error); } }; export { compressAndResizeBucketImage };