簡體   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