Update database through a Cloud Function - Firebase

0

Seeing a Jen Person tutorial on the Firebase channel on youtube, I wrote a javascript function that is triggered when a user in my app uploads an image in Firebase Storage. This function generates a thumbnail of the image and saves it in Firebase Storage as well. My problem is: I do not know much javascript. I already have the URLs of the images that are in Storage, but I need to update the values of the respective childs in Firebase Database, and I need to store them in the current user ID, that is, what uploaded the file. Within each user ID I have, among other fields, the "image" and "thumb_image" fields that should store the URL of your images in Storage.

Here is my code:

    exports.generateThumbnail = functions.storage.object().onChange(event => {
    const object = event.data
    const filePath = object.name
    const fileName = filePath.split('/').pop()
    const fileBucket = object.bucket
    const bucket = gcs.bucket(fileBucket)
    const tempFilePath = '/tmp/${fileName}'
    const ref = admin.database().ref()
    const file = bucket.file(filePath)
    const thumbFilePath = filePath.replace(/(\/)?([^\/]*)$/, '$1thumb_$2')

    if(fileName.startsWith('thumb_')) {
        console.log('This file is already a thumbnail')
        return
    }

    if(!object.contentType.startsWith('image/')) {
        console.log('This is not an image to create thumbnail.')
        return
    }
    if (object.resourceState === 'not_exists') {
        console.log('There has been an image deletion event.')
        return
    }

    return bucket.file(filePath).download({
        destination: tempFilePath
    }).then(() => {
        console.log('Image downloaded locally to', tempFilePath)
        return spawn('convert',[tempFilePath, '-thumbnail', '200x200>', tempFilePath])
    }).then(() => {
        console.log('Thumbnail created!')

        return bucket.upload(tempFilePath, {
            destination: thumbFilePath
        })
    }).then(() => {
        const thumbFile = bucket.file(thumbFilePath)
        const config = {
            action: 'read',
            expires: '03-09-2491'
        }
        return Promisse.all([
            thumbFile.getSignedUrl(config),
            file.getSignedUrl(config)
        ])
    }).then(results => {
        const thumbResult = results[0]
        const originalResult = results[1]
        const thumbFileUrl = thumbResult[0]
        const fileUrl = originalResult[0]


       // Não sei o que fazer a partir daqui
    })
})

Is there any way to do this? Thank you in advance.

This is the structure of my Database:

    
asked by anonymous 11.02.2018 / 04:22

0 answers