首页 > 解决方案 > 云功能 - 更新实时数据库上的数据

问题描述

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

在 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) => {

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

标签: node.jsfirebase-realtime-databasegoogle-cloud-functions

解决方案


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

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

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

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


推荐阅读