node.js - 云功能 - 更新实时数据库上的数据
问题描述
由于 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.js 的版本没有任何关系。它与 firebase-functions SDK 的版本有关。您之前使用的是非常旧的预发布版本。自 1.0.0 以来,签名已更改是描述更改的文档中的迁移指南。特别要阅读本节。
从适用于 Cloud Functions 的 Firebase SDK v 1.0 开始,异步函数的事件参数已过时。它已被两个新参数取代:数据和上下文。
您将需要学习新的 API 并移植您的代码。
返回值的要求没有改变。当您的函数中的所有异步工作都完成时,您仍然有义务返回一个 promise the resolves。如果您看到有关此的新错误消息,那是因为您还升级了工具,并且他们现在正在为您检查未处理的承诺。
推荐阅读
- amazon-web-services - 每天将批处理文件从 Linux EC2 实例自动传输到 Windows EC2 实例
- sql - 如果满足某些条件,则存入相同价值的情况
- c# - 通过 SQL 脚本任务触发 HTTP Logic App
- python - 如何将 entry_point/console 脚本添加到使用参数的 setup.py
- html - 如何将图像完全放入 div 而不会溢出?
- c# - BouncyCastle - 将 X509CrlEntry.SerialNumber 转换为“CAPI 样式”十六进制字符串
- ansible - 使用 win_lineinfile 不更新文件中的行
- go - 如何从参数传播参数
- azure - 使用 IAM for Azure Service Bus,如何将角色分配给应用程序?
- react-native - Expo Signature - Crash onChange 内容