繁体   English   中英

当从实时数据库中删除对象时,Firebase功能(用NodeJS编写)从云存储中删除文件

[英]Firebase function (written in NodeJS) to delete file from Cloud Storage when an object is removed from Realtime Database

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

我想要实现的目标:

  1. 当用户从Firebase DB中删除Photo对象时,应该触发该函数;
  2. 代码应从与Photo obj对应的Storage中删除文件对象。

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

照片/ {userUID} / {} photoUID

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

和Firebase存储格式:

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

我正在使用的NodeJS代码:

    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”

在此输入图像描述

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

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

提前感谢您的支持和耐心。

发现问题,这里的代码对我有用:

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开发人员,并且实际上没有测试它):

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}`)
    });

});

你也可以注意到我的路径改变了:

photos/{userUID}/{photoUID} 

至:

users/{userUID}/photos/{photoUID}

试试这个

const gcs  = require('@google-cloud/storage')()

    const fileBucketPush = 'Storage bucket.appspot.com'; // The Storage bucket that contains the file.
    const filePathPush = 'folder/'+nameImage; // File path in the bucket.
    vision.detectSafeSearch(gcs.bucket(fileBucketPush).file(filePathPush))
      .then((results) => {
       ..///

      })
      .catch((err) => {
        console.error('ERROR:', err);
      });

您启用Cloud Vision API?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM