Skip to content

Instantly share code, notes, and snippets.

@bossly
Created February 7, 2018 16:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bossly/fb03686f2cb1699c2717a0359880cf84 to your computer and use it in GitHub Desktop.
Save bossly/fb03686f2cb1699c2717a0359880cf84 to your computer and use it in GitHub Desktop.
Firebase Cloud Function to add record to database when new image uploaded
'use strict';
const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// on file upload to google cloud storage
exports.fileUploaded = functions.storage.object().onChange(event => {
const object = event.data; // the object that was just uploaded
const contentType = event.data.contentType; // This is the image Mimme type\
// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
// Get the Signed URLs for the thumbnail and original image.
const config = {
action: 'read',
expires: '03-01-2500'
};
const bucket = gcs.bucket(event.data.bucket);
const filePath = event.data.name;
const file = bucket.file(filePath);
file.getSignedUrl(config, function(err, fileURL) {
console.log(fileURL);
admin.database().ref('images').push({
src: fileURL
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment