Created
June 12, 2018 23:20
-
-
Save birchb/6cf450f4b8d1804b2ac7d414f841400a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 gcs = require('@google-cloud/storage')({keyFilename: 'service-key.json'}); | |
const spawn = require('child-process-promise').spawn; | |
const path = require('path'); | |
const os = require('os'); | |
const fs = require('fs'); | |
exports.createCard = functions.firestore | |
.document('work_cards/{cardID}') | |
.onCreate((snap, context) => { | |
const newCardData = snap.data() | |
const bucket = gcs.bucket('your-project-id.appspot.com') | |
const file = bucket.file(newCardData.image_name) | |
const tempFilePath = path.join(os.tmpdir(), file.name); | |
const thumbFileName = `thumb_${file.name}`; | |
const thumbFilePath = bucket.file(thumbFileName) | |
const contentType = file.contentType; | |
const metadata = { | |
contentType: contentType | |
}; | |
return bucket.file(file.name).download({ | |
destination: tempFilePath, | |
}) | |
.then(() => { | |
return spawn('convert', [tempFilePath, '-thumbnail', '250x250', tempFilePath]); | |
}) | |
.then(() => { | |
return bucket.upload(tempFilePath, { | |
destination: thumbFilePath, | |
metadata: metadata, | |
}) | |
}) | |
.then(() => { | |
return thumbFilePath.getSignedUrl({ | |
action: 'read', | |
expires: '03-09-2491' | |
}) | |
}) | |
.then(signedUrls => { | |
const img_src = signedUrls[0] | |
return snap.ref.set({img_src}, {merge: true}); | |
}) | |
.then(() =>{ | |
bucket.file(file.name).delete() | |
fs.unlinkSync(tempFilePath) | |
return | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment