【问题标题】:How to compare old and new value with Cloud Functions for Firebase with .onWrite or onchange?如何使用 .onWrite 或 onchange 将新旧值与 Cloud Functions for Firebase 进行比较?
【发布时间】:2017-09-09 22:43:48
【问题描述】:

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

现在我想用 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});

});

发生了一些我不明白/可以解决的事情:当我删除整个 userUID 记录(用于清理)时,userUID 记录会自动创建,然后仅使用以下路径 {uid}/services/facebood/accesTokenFacebook。 ..

似乎删除也会触发onWrite。

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

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

【问题讨论】:

  • functions.database.ref(...).onWrite(e => console.log(e.data.previous.val(), e.data.val()))
  • @Michael,快速响应 :) 看起来很简单,我会尽快尝试。
  • @Michael,谢谢!我工作正常。
  • @MichaelBleigh 您应该发表您的评论作为答案。它帮助了我,但我几乎错过了它,因为它只是一个评论。与此同时,我会发布一个答案,这样其他人就不会做同样的事情,但如果你想发布你的答案并获得功劳,我会很高兴地把我的拿下来! :)

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


【解决方案1】:

更新: 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
});

之前 (

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

【讨论】:

  • 值得补充的是,与此等效的打字稿是:export const someFunction = functions.firestore .document('SomeCollection/SomeDocumentId') .onWrite((snap, context) => { const newVal = snap.after.data(); const oldVal = snap.before.data(); });
【解决方案2】:

现在这些函数已被弃用,这是该主题的第一搜索结果,这里是 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();
});

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 2018-01-26
    • 2018-01-19
    • 2017-09-01
    • 2017-11-10
    • 2017-08-25
    • 2017-09-04
    • 2018-01-17
    • 2018-10-11
    相关资源
    最近更新 更多