【问题标题】:Cloud functions - update data on realtime database云功能 - 更新实时数据库上的数据
【发布时间】:2019-08-12 02:08:55
【问题描述】:

自从 nodejs 中的重大更改(移至 nodejs 版本 8)以来,我的代码出现了严重的错误和问题。我已经查看了 google 文档如何重写函数,但我仍然无法管理它。

在 nodejs 版本 6 上,我编写了一个函数,当添加新项目时触发,然后更新实时数据库中的其他节点

例如

   // Keeps track of the length of the 'likes' child list in a separate property.
  exports.countlikechange = 
  functions.database.ref('/likes/{postid}/{userUID}').onWrite(event => {
   const collectionRef = event.data.ref.parent;
  const model = event.data.val();
  let genre = model.genre;
let videoID = model.videoID;
let userVideoID = model.userVideoID;

console.log("model: ",model);
console.log("genre: ",genre);
console.log("videoId: ",videoID);
console.log("userVideoID: ",userVideoID);

const countRef = collectionRef.child('likes');


// Return the promise from countRef.transaction() so our function 
// waits for this async event to complete before it exits.
 return countRef.transaction(current => {
  if (event.data.exists() && !event.data.previous.exists()) {
    const genreList = admin.database().ref(`${genre}/${videoID}/likes`).transaction(current => {
      return (current || 0) + 1;
    });
    const userList = admin.database().ref(`users/${userVideoID}/likes`).transaction(current => {
      return (current || 0) + 1;
    });
    const videoList = admin.database().ref(`videos/${userVideoID}/${videoID}/likes`).transaction(current => {
      return (current || 0) + 1;
    });
  }
 }).then(() => {
   console.log('Counter updated.');
   return null;
      });
   });

这个函数不再起作用,因为我已经将 nodejs 更新到版本 8。

在 google 文档中,参数发生了变化,例如:

    exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onWrite((change, context) => {

return 语句也发生了变化,它给了我需要使用 promise 的错误。 所以我有点困惑,我应该如何重写这个函数,所以当它触发时我会更新实时数据库中的节点。

【问题讨论】:

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


    【解决方案1】:

    这实际上与节点的版本没有任何关系。它与 firebase-functions SDK 的版本有关。您之前使用的是非常旧的预发布版本。自 1.0.0 以来,签名已更改是描述更改的文档中的迁移指南。特别是read this section

    从适用于 Cloud Functions 的 Firebase SDK 1.0 版开始,该事件 异步函数的参数已过时。它已被替换 通过两个新参数:数据和上下文。

    您需要学习新的 API 并移植您的代码。

    返回值的要求没有改变。当您的函数中的所有异步工作完成时,您仍然有义务返回一个 promise the resolves。如果您看到新的错误消息,那是因为您还升级了工具,它们现在正在为您检查未处理的 Promise。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 2020-05-15
      • 2023-03-09
      • 2021-09-07
      • 2023-02-09
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多