Skip to content

Instantly share code, notes, and snippets.

@birchb
Created June 12, 2018 23:20
Show Gist options
  • Save birchb/6cf450f4b8d1804b2ac7d414f841400a to your computer and use it in GitHub Desktop.
Save birchb/6cf450f4b8d1804b2ac7d414f841400a to your computer and use it in GitHub Desktop.
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