如何使用 Cloud Functions for Firebase 与 .onWrite 或 onchange 比较新旧值?

How to compare old and new value with Cloud Functions for Firebase with .onWrite or onchange?

让我们采用以下数据结构:

现在我想用 Firebase 函数刷新 accessTokenFacebook。 我测试了两个选项:

  1. onWrite,以及:
  2. onChanged

onWrite 对我来说看起来最好,但具有以下功能:

exports.getFacebookAccessTokenOnchange = functions.database.ref('/users/{uid}/userAccountInfo/lastLogin').onWrite(event => {
  const lastLogin = event.data;
  let dateObject = new Date();
  let currentDate = dateObject.toUTCString();

  return lastLogin.ref.parent.parent.child('services').child('facebook').update({'accessTokenFacebook': currentDate});

});

发生了一些我没有解决的问题understand/can:当我删除整个 userUID 记录(用于清理)时,userUID 记录会自动创建,然后仅使用以下路径 {uid}/services/facebood/accesTokenFacebook...

好像删除也会触发onWrite

我也尝试了 .onchange,但只有当仍然没有 accessTokenFacebook 时才会触发。当更改进行此更改时,更改再也不会触发。

所以接下来我要做的是比较新旧值。你有例子吗?或者有更好的解决方案吗?

更新: Cloud Functions 最近对 API 进行了更改,如 here.

所述

现在 (>= v1.0.0)

exports.dbWrite = functions.database.ref('/path').onWrite((change, context) => {
  const beforeData = change.before.val(); // data before the write
  const afterData = change.after.val(); // data after the write
});

之前 (<= v0.9.1)

exports.dbWrite = functions.database.ref('/path').onWrite((event) => {
  const beforeData = event.data.previous.val(); // data before the write
  const afterData = event.data.val(); // data after the write
});

现在这些函数已被弃用,这是该主题的第一搜索结果,这是 Cloud Functions 现在使用的新更新版本。

exports.yourFunction = functions.database.ref('/path/{randomPath}/goes/here').onWrite((change, context) => {
    // Your value after the write
    const newVal = change.after.val();
    // Your value before the write
    const oldVal = change.before.val();
});