首页 > 解决方案 > 如何使用 Firebase Cloud Functions 删除旧文件?

问题描述

我正在为 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);
    });
});

我该怎么做才能删除文件?提前致谢。

标签: node.jsfirebasefirebase-realtime-databasegoogle-cloud-functionsfirebase-storage

解决方案


这对我有用

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

推荐阅读