【问题标题】:How to delete old files with Firebase Cloud Functions?如何使用 Firebase Cloud Functions 删除旧文件?
【发布时间】:2020-01-12 11:16:00
【问题描述】:

我正在为 Firebase Cloud Functions 编写一个函数,我可以在其中从 Firebase 数据库中删除旧节点。每个节点上都有一个指向保存在 Firebase 存储中的文件的链接。

数据库结构

  "data" : {
    "-Lo0onTCSVeY-Kco5ujX" : {
      "photo" : "https://firebasestorage.googleapis.com/v0...",
      "idD" : "-Lo0onTCSVeY-Kco5ujX",
      "idUs" : "jh4Ch9rBgQPwBTfv43MgNissRUP2",
      "timestamp" : 1567693686925,
    }
  },

功能:

'use strict';

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

var DAY_MILLIS = 86400000 //1 Day

exports.deleteOldPosts = functions.database.ref('/data/{pushId}').onWrite(function(change) {
    var ref = change.after.ref.parent; // reference to the parent
    var now = Date.now();
    var cutoff = now - DAY_MILLIS;
    var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
    return oldItemsQuery.once('value').then(function(snapshot) {
      // create a map with all children that need to be removed
      var updates = {};
      snapshot.forEach(function(child) {
        updates[child.key] = null;
      });
      // execute all updates in one go and return the result to end the function
      return ref.update(updates);
    });
});

我怎样才能删除文件呢? 提前致谢。

【问题讨论】:

  • 将来,如果您知道文件在 Cloud Storage 中的路径,删除文件会容易得多。您现在拥有的是一个下载 URL,它在使用后端 SDK 时不容易转换为路径。如果您有路径,您只需将其提供给 Cloud Storage 节点 SDK 即可将其删除。
  • 您要删除所有早于某个日期的文件吗?

标签: node.js firebase firebase-realtime-database google-cloud-functions firebase-storage


【解决方案1】:

这对我有用

const promises = [];
promises.push(ref.update(updates));
const bucket = admin.storage().bucket();
promises.push(bucket.file(`file/${anotherFile}`).delete());
return Promise.all(promises);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 2021-11-04
    • 2021-11-23
    • 1970-01-01
    • 2019-05-03
    • 2018-10-01
    • 2018-08-02
    相关资源
    最近更新 更多