Created
February 7, 2018 16:27
-
-
Save bossly/fb03686f2cb1699c2717a0359880cf84 to your computer and use it in GitHub Desktop.
Firebase Cloud Function to add record to database when new image uploaded
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
'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