【问题标题】:Firebase Function onDelete from database and storageFirebase 函数 onDelete 从数据库和存储中删除
【发布时间】:2020-12-29 15:56:49
【问题描述】:

我希望能够在触发 onDelete 函数时删除 Firebase 存储中的文件夹。

这是我的firebase节点代码,删除后会触发函数删除firebase存储中的相应文件夹。我允许用户删除他们包含图像的消息转换。我可以在不使用 {friendId} 的情况下删除该文件夹,但需要 {friendId} 以防用户与两个不同的用户进行转换。

我的 Firebase 存储如下

messages_image_from_friends/

  iLJ6nGJodeat2HRi5Q2xdTUmZnw2/

    MXGCZv96aVUkSHZeU8kNTZqTQ0n2/

      image.png

和 Firebase 函数

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} 到前缀。

我尝试过“snapshot”和“then()”,但不知道如何实现它,因为我是函数新手。请帮忙。

更新!!! 2020 年 9 月 12 日

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

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 应用中调用该函数的代码

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 初始化文件夹.. 当它连接为 onDelete 并且它只更新 index.js 而不是整个功能文件夹时,我犯了直接在云功能控制台中重新部署的错误。所以不要做我所做的,因为你会得到一个 TypeError: Cannot read property 'origin' of undefined at /srv/node_modules/cors/lib/

希望这对其他人有帮助!!!

20 年 9 月 18 日更新

我可以让它与 onDelete 一起工作

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


 });

【问题讨论】:

    标签: javascript firebase google-cloud-functions


    【解决方案1】:

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

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

    我建议查看数据库触发器的文档,尤其是 specifying the path 上的部分:

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

    【讨论】:

    • 我应该做 const {friendId } = context.params.userId.friendId; ?
    • 不,只使用我在答案中给你的内容。
    • 我试过 event.params.friendId 但它给了我 ReferenceError: event is not defined
    • 没错,您没有名为“event”的变量。我的代码不建议这样做。链接的文档可能有所不同。
    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2017-12-26
    • 2019-06-12
    • 1970-01-01
    相关资源
    最近更新 更多