本文介绍了当从实时数据库中删除对象时,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. 代码应该从 Storage 中移除与 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: Not found"

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 中删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:23