Last active
April 1, 2017 20:48
-
-
Save gmaclennan/7b96abf52b61556ce2d9bb73c448df26 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const functions = require('firebase-functions') | |
const path = require('path') | |
const gcs = require('@google-cloud/storage')() | |
module.exports = functions.storage.object().onChange(event => { | |
const object = event.data | |
const bucket = gcs.bucket(object.bucket) | |
// Exit if this is triggered on a file that is not an image. | |
if (!object.contentType.startsWith('image/')) { | |
console.log('This is not an image.') | |
return | |
} | |
// Exit if this is a move or deletion event. | |
if (object.resourceState === 'not_exists') { | |
console.log('This is a deletion event.') | |
return | |
} | |
// Skip if this is the output of a copy op. | |
if (path.parse(object.name).name.endsWith('-copy')) { | |
console.log('This is an image that is already copied') | |
return | |
} | |
const writeOpts = { | |
public: true, | |
resumable: false, | |
metadata: { | |
contentType: object.contentType, | |
cacheControl: 'public, max-age=31557600' | |
} | |
} | |
const source = bucket.file(object.name).createReadStream() | |
const destFilename = createDestFilename(object.name) | |
const dest = bucket.file(destFilename).createWriteStream(writeOpts) | |
var start = Date.now() | |
source.pipe(dest).on('finish', () => { | |
console.log('copy complete %s ms', Date.now() - start) | |
}) | |
}) | |
function createDestFilename (filename) { | |
const parsed = path.parse(filename) | |
return path.join(parsed.dir, parsed.name + '-copy' + parsed.ext) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment