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



由于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。

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

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

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

这实际上与节点的版本没有任何关系。 这与Firebase-functions SDK的版本有关。 您之前使用的是非常旧的预发布版本。 从 1.0.0 开始,签名已更改是文档中描述更改的迁移指南。 特别是,请阅读本节。

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

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

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

相关内容

最新更新