日期后删除项目(Firebase Cloud功能)

时间:2018-07-02 11:26:06

标签: javascript firebase google-cloud-functions

我正在尝试编写一个Firebase云函数,以便在经过日期之后自动删除一个事件。

基于这个示例Firebase exemple,我想到了这一点,但是当我将其上传到Firebase时,它正在Firebase端运行,但并未删除事件。

你们对我的代码有意见或发现错误吗?问题可能来自触发器onWrite()吗?

/* My database structure

   /events
                item1: {
                    MyTimestamp: 1497911193083
                },
                item2: {
                    MyTimestamp: 1597911193083                    
                }
                ...
*/


// Cloud function to delete events after the date is passed

'use strict';

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

exports.deleteOldItems = functions.database.ref('/events/{eventId}').onWrite((change) => {
  
  const ref = change.after.ref.parent; // reference to the parent
  const now = Date.now();
  const oldItemsQuery = ref.orderByChild('MyTimestamp').endAt(now);

  return oldItemsQuery.once('value').then((snapshot) => {
    // create a map with all children that need to be removed
    const updates = {};
    	snapshot.forEach(child => {
      		updates[child.key] = null;
    	});
    return ref.update(updates);
    // execute all updates in one go and return the result to end the function
  });
});

2 个答案:

答案 0 :(得分:3)

代码没有任何问题,只需更新您的云功能和管理员即可:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.deleteOldItems = functions.database.ref("/events/{eventId}").onWrite((change, context) => {
  if (change.after.exists() && !change.before.exists()) {
    const ref = change.after.ref.parent;
    const now = Date.now();
    const oldItemsQuery = ref.orderByChild('MyTimestamp').endAt(now);
    return oldItemsQuery.once('value').then((snapshot) => {
      const updates = {};
      snapshot.forEach(child => {
        updates[child.key] = null;
      });
      return ref.update(updates);
    });
  } else {
    return null;
  }
});

在functions文件夹中运行以下命令:

npm install firebase-functions@latest --save npm install firebase-admin@5.11.0 --save

参考here了解更多详情

答案 1 :(得分:0)

尝试更改

 admin.initializeApp();

至:

admin.initializeApp(functions.config().firebase);