简体   繁体   中英

How to delete old files with Firebase Cloud Functions?

I'm writing a function for Firebase Cloud Functions in which I can delete old nodes from Firebase Database. On each of these nodes is a link to a file saved in Firebase Storage.

Database Structure

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

Function:

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

How can I do to delete the file too? Thanks in advance.

This works for me

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM