云功能-更新实时数据库上的数据

时间:2019-08-11 18:03:08

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

由于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) => {

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

1 个答案:

答案 0 :(得分:1)

这实际上与节点的版本无关。它与firebase-functions SDK的版本有关。您以前使用的是非常的旧发行版。从1.0.0版本开始,签名已更改,它是说明更改的文档中的迁移指南。特别是read this section

  

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

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

对返回值的要求未更改。当您的函数中的所有异步工作都完成时,您仍然有义务返回承诺解决方案。如果您看到有关此问题的新错误消息,那是因为您还升级了工具,他们现在正在为您检查未处理的承诺。

相关问题