从实时数据库中删除对象时,Firebase函数(用NodeJS编写)可从Cloud Storage中删除文件 [英] Firebase function (written in NodeJS) to delete file from Cloud Storage when an object is removed from Realtime Database

本文介绍了从实时数据库中删除对象时,Firebase函数(用NodeJS编写)可从Cloud Storage中删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是NodeJS的新手,我正在尝试为Cloud Functions for Firebase编写下一个方法.

I am new to NodeJS and I am trying to write the next method for Cloud Functions for Firebase.

我要实现的目标:

  1. 当用户从Firebase DB中删除Photo对象时,应触发该功能;
  2. 代码应从存储对象中删除与Photo obj对应的文件对象.

这些是我的Firebase数据库结构:

These is my Firebase DB structure:

照片/{userUID}/{photoUID}

{
"dateCreated":      "2017-07-27T16:40:31.000000Z",
"isProfilePhoto":   true,
"isSafe":           true,
"uid":              "{photoUID}",
"userUID":          "{userUID}"
}

以及Firebase存储格式:

And the Firebase Storage format:

照片/{userUID}/{photoUID} .png

以及我正在使用的NodeJS代码:

And the NodeJS code that I am using:

    const functions = require('firebase-functions')
    const googleCloudStorage = require('@google-cloud/storage')({keyFilename: 'firebase_admin_sdk.json' })
    const admin = require('firebase-admin')
    const vision = require('@google-cloud/vision')();

    admin.initializeApp(functions.config().firebase)

    exports.sanitizePhoto = functions.database.ref('photos/{userUID}/{photoUID}')
        .onDelete(event => {

            let photoUID = event.data.key
            let userUID = event.data.ref.parent.key

            console.log(`userUID: ${userUID}, photoUID: ${photoUID}`);

            if (typeof photoUID === 'undefined' || typeof userUID === 'undefined') {
                console.error('Error while sanitize photo, user uid or photo uid are missing');
                return
            }

            console.log(`Deleting photo: ${photoUID}`)

            googleCloudStorage.bucket(`photos/${userUID}/${photoUID}.png`).delete().then(() => {
                console.log(`Successfully deleted photo with UID: ${photoUID}, userUID : ${userUID}`)
            }).catch(err => {
                console.log(`Failed to remove photo, error: ${err}`)
            });

        });

当我运行它时,出现下一个错误:"ApiError:未找到"

While I run it I get the next error: "ApiError: Not found"

我认为代码的这些部分是导致问题的那一部分:

I think these part of the code is the the one that causes the issue:

googleCloudStorage.bucket(`photos/${userUID}/${photoUID}.png`).delete()

预先感谢您的支持和耐心.

Thanks in advance for support and patience.

推荐答案

发现了问题,下面的代码对我有用:

Found the issue, here it is the code that works for me:

const functions = require('firebase-functions');

实时数据库:

exports.sanitizePhoto = functions.database.ref('photos/{userUID}/{photoUID}').onDelete(event => {

        let photoUID = event.data.key
        let userUID = event.data.ref.parent.key

        console.log(`userUID: ${userUID}, photoUID: ${photoUID}`);

        if (typeof photoUID === 'undefined' || typeof userUID === 'undefined') {
            console.error('Error while sanitize photo, user uid or photo uid are missing');
            return
        }

        console.log(`Deleting photo: ${photoUID}`)

        const filePath = `photos/${userUID}/${photoUID}.png`
        const bucket = googleCloudStorage.bucket('myBucket-12345.appspot.com')
        const file = bucket.file(filePath)

        file.delete().then(() => {
            console.log(`Successfully deleted photo with UID: ${photoUID}, userUID : ${userUID}`)
        }).catch(err => {
            console.log(`Failed to remove photo, error: ${err}`)
        });

    });

这里也是Firestore的相同代码(不确定它是否有效,因为我不是NodeJS开发人员,并且并未实际对其进行测试):

Also here is the same code but for Firestore (not sure if it works, as I am not a NodeJS developer and didn't actually test it):

exports.sanitizePhoto = functions.firestore.document('users/{userUID}/photos/{photoUID}').onDelete((snap, context) =>{

    const deletedValue = snap.data();

    let photoUID = context.params.photoUID 
    let userUID = context.params.userUID

    console.log(`userUID: ${userUID}, photoUID: ${photoUID}`);

    if (typeof photoUID === 'undefined' || typeof userUID === 'undefined') {
        console.error('Error while sanitize photo, user uid or photo uid are missing');
        return
    }

    console.log(`Deleting photo: ${photoUID}`)

    const filePath = `photos/${userUID}/${photoUID}.png`
    const bucket = googleCloudStorage.bucket('myBucket-12345.appspot.com')
    const file = bucket.file(filePath)

    file.delete().then(() => {
        console.log(`Successfully deleted photo with UID: ${photoUID}, userUID : ${userUID}`)
    }).catch(err => {
        console.error(`Failed to remove photo, error: ${err}`)
    });

});

您还可以注意到我的路径从:

Also you can notice that my path changed from:

photos/{userUID}/{photoUID} 

收件人:

users/{userUID}/photos/{photoUID}

这篇关于从实时数据库中删除对象时,Firebase函数(用NodeJS编写)可从Cloud Storage中删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆