Firebase Function onDelete从数据库和存储中删除 [英] Firebase Function onDelete from database and storage

查看:40
本文介绍了Firebase Function onDelete从数据库和存储中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在触发功能中的onDelete的同时删除Firebase存储中的文件夹.

I want to be able to delete a folder in firebase storage while onDelete in functions is triggered.

这是我的Firebase节点代码,一旦删除,它将触发函数删除Firebase存储中的相应文件夹.我允许用户删除其包含图像的消息转换.我可以删除该文件夹而无需使用{friendId},但是如果用户与两个不同的用户进行了转换,则需要{friendId}.

here is my firebase node code, once deleted, it will trigger functions to delete the corresponding folder in firebase storage. I am allowing user to delete their message conversion that includes images. I was able to delete the folder without using the {friendId} but {friendId} is needed in case the user have conversions with two different users.

我的Firebase存储如下

My Firebase storage is as follow

messages_image_from_friends/

  iLJ6nGJodeat2HRi5Q2xdTUmZnw2/

    MXGCZv96aVUkSHZeU8kNTZqTQ0n2/

      image.png

和Firebase函数

and Firebase Functions

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const firebase = admin.initializeApp();

exports.deletePhotos = functions.database.ref('/messagesFriends/{userId}/{friendId}')
                .onDelete((snap, context) => {

               const { userId } = context.params;

         <---- const { friendId } = context.params.friendId; ????? ---- >

               const bucket = firebase.storage().bucket();


         return bucket.deleteFiles({
         prefix: `messages_image_from_friends/${userId}/{friendId}`
             }, function(err) {

              if (err) {
                 console.log(err);
                } else {
             console.log(`All the Firebase Storage files in 
            messages_image_from_friends/${userId}/{friendId} have been deleted`);
                    }

                  });
  });

日志指出{friendId}未定义.如何从导出到前缀中获取{friendId}.

Log states that {friendId} is undefined. How do i get {friendId} from exports into prefix.

我尝试过快照"和"then()"但是由于我是函数新手,所以真的不知道如何实现它.请帮忙.

I have tried "snapshot" and "then()" but do not really know how to implement it as I am new to functions. Please help.

更新!!! 2020年9月12日

Update!!! 9/12/2020

我能够通过将onDelete更改为functions.https.onCall来使用hashmap来实现此功能.希望对其他人有帮助

I was able to get this working by changing onDelete to functions.https.onCall to use hashmap instead.. hope this help others

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const firebase = admin.initializeApp();

exports.deletePhotos = functions.https.onCall((data, context) => {

const userId = data.userId;
const friendId = data.friendId;

console.log(userId, friendId); 

const bucket = firebase.storage().bucket();

return bucket.deleteFiles({
    prefix: `messages_image_from_friends/`+userId+`/`+friendId+`/`
    }, function(err) {
        if (err) {
            console.log(err);
            } else {
                
console.log(`messages_image_from_friends/`+userId+`/`+friendId);
                }
                });

// return {response:"This means success"};

});

以及从您的android应用中调用该函数的代码

and the code to call the function from your android app

private FirebaseFunctions mFunctions;

protected void onCreate(Bundle savedInstanceState) {
mFunctions = FirebaseFunctions.getInstance();

 
////String userId is current firebase user id
////String friendId is from getIntent(), etc 

deletePhotos(userId, friendId);

}

private Task<String> deletePhotos(String userId, String friendId) {
    // Create the arguments to the callable function.
    Map<String, Object> data = new HashMap<>();
    data.put("userId", userId);
    data.put("friendId", friendId);

    return mFunctions
            .getHttpsCallable("deletePhotos")
            .call(data)
            .continueWith(new Continuation<HttpsCallableResult, 
       String>() {
                @Override
                public String then(@NonNull Task<HttpsCallableResult> 
       task) throws Exception {
                    // This continuation runs on either success or 
        failure, but if the task
                    // has failed then getResult() will throw an 
        Exception which will be
                    // propagated down.
                    String result = (String) 
       task.getResult().getData();
                    return result;
                }
            });
      }

确保您创建了新的FIREBASE INIT文件夹. 我直接在云功能控制台上重新部署了此错误,尽管它已作为onDelete连接,并且仅使用index.js代替了整个功能文件夹.所以不做我该怎么办,因为您将得到一个TypeError:无法在/srv/node_modules/cors/lib/

MAKE SURE YOU MAKE A NEW FIREBASE INIT FOLDER.. I MADE THE MISTAKE OF REDEPLOYING THIS DIRECTLY IN CLOUD FUNCTION CONSOLE WHILE IT WAS CONNECTED AS onDelete and IT WAS UPDATING THE index.js ONLY INSTEAD OF THE WHOLE FUNCTION FOLDER. SO DON'T DO WHAT I DID BECAUSE YOU WILL GET A TypeError: Cannot read property 'origin' of undefined at /srv/node_modules/cors/lib/

希望这能帮助其他人!

更新9/18/20

我能够通过它使它与onDelete一起使用

I was able to make it work with onDelete with this

'use-strict'

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const firebase = admin.initializeApp();

exports.deletePhotos = 
functions.database.ref('/messagesFriends/{userId}/{friendId}')
            .onDelete((snap, context) => {

const userId = context.params.userId;
const friendId = context.params.friendId;

const bucket = firebase.storage().bucket();

console.log(userId + ' ' + friendId + " found");

return bucket.deleteFiles({
    prefix: `messages_image_from_friends/`+userId+`/`+friendId
    }, function(err) {
        if (err) {
            
console.log(`messages_image_from_friends/`+userId+`/`+friendId + ` 
remove error`);
            } else {
                
 console.log(`messages_image_from_friends/`+userId+`/`+friendId + ` 
 removed`);
                }
                });


 });

推荐答案

context.params是一个对象,其属性由触发路径中的每个通配符填充.您没有正确使用它.

context.params is an object whose properties are populated with each of the wildcards from the trigger path. You're not using it correctly.

const userId = context.params.userId;
const friendId = context.params.friendId;

我建议您查看数据库触发器的文档,尤其是指定路径:

I suggest reviewing the documentation for database triggers, especially the part on specifying the path:

您可以使用大括号将路径组件指定为通配符; ref('foo/{bar}')/foo的任何子项匹配.这些通配符路径组件的值在函数的EventContext.params对象中可用.在此示例中,该值可作为event.params.bar.

You can specify a path component as a wildcard by surrounding it with curly brackets; ref('foo/{bar}') matches any child of /foo. The values of these wildcard path components are available within the EventContext.params object of your function. In this example, the value is available as event.params.bar.

这篇关于Firebase Function onDelete从数据库和存储中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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