import { Storage } from '@google-cloud/storage' ; import { spawn } from 'child-process-promise' ; import { storage } from 'firebase-functions' ; import fs from 'fs' ; import mkdirp from 'mkdirp' ; import os from 'os' ; import path from 'path' ; const gcs = new Storage ( ) ; export const optimizeImages = storage . object ( ) . onFinalize ( ( object ) => { const { contentType } = object ; if ( ! contentType . startsWith ( 'image/' ) ) { console . log ( 'This is not an image.' ) ; return null ; } return optimizeImage ( object ) ; } ) ; async function optimizeImage ( object ) { const filePath = object . name ; const tempLocalFile = path . join ( os . tmpdir ( ) , filePath ) ; const tempLocalDir = path . dirname ( tempLocalFile ) ; const bucket = gcs . bucket ( object . bucket ) ; const file = bucket . file ( filePath ) ; const [ metadata ] = await file . getMetadata ( ) ; if ( metadata . metadata && metadata . metadata . optimized ) { console . log ( 'Image has been already optimized' ) ; return null ; } await mkdirp ( tempLocalDir ) ; await file . download ( { destination : tempLocalFile } ) ; console . log ( 'The file has been downloaded to' , tempLocalFile ) ; await spawn ( 'convert' , [ tempLocalFile , '-strip' , '-interlace' , 'Plane' , '-quality' , '82' , tempLocalFile , ] ) ; console . log ( 'Optimized image created at' , tempLocalFile ) ; const destination = bucket . file ( filePath ) ; const [ newFile ] = await bucket . upload ( tempLocalFile , { destination , metadata : { metadata : { optimized : true , } , } , } ) ; await newFile . makePublic ( ) ; console . log ( 'Optimized image uploaded to Storage' ) ; return Promise . all ( [ fs . unlinkSync ( tempLocalFile ) ] ) ; }