【发布时间】:2019-06-07 06:34:32
【问题描述】:
首先,当“TotalMoney”节点被触发时,该函数会从“OldNewKey”中获取一个节点,然后再获取另一个节点并进行更新。但这是警告避免嵌套承诺。
exports.postMoneyUpdater = functions.database.ref('/TotalMoney/{fixedPostId}/').onWrite((change, context) => {
const fixedPostId = context.params.fixedPostId;
const moneyAmountBefore = change.before.val();
const moneyAmountAfter = change.after.val();
var oldPostKey;
// console.log("time "+ Date.now());
if(moneyAmountAfter>moneyAmountBefore){
const oldNewKeyRef = admin.database().ref(`/OldNewKey`).child(fixedPostId);
return oldNewKeyRef.once('value').then((oldNewKeySnapshot)=>{
if(!oldNewKeySnapshot.exists()){
oldPostKey = fixedPostId;
}else{
oldPostKey = oldNewKeySnapshot.val();
}
const postRef = admin.database().ref(`/Posts`).child(oldPostKey);
return postRef.once('value').then((postSnapshot)=>{
var postMap ={};
postSnapshot.forEach((child) =>{
postMap[child.key] = child.val();
});
const newPostKey = 9999999999999-Date.now();
var updateMap = {};
updateMap["post"] = postMap["post"];
updateMap["imageUrl"] = postMap["imageUrl"];
updateMap["userId"] = postMap["userId"];
updateMap["postId"] = postMap["postId"];
updateMap["dist"] = postMap["dist"];
updateMap["customId"] = postMap["customId"];
updateMap["newPostKey"] = newPostKey.toString();;
updateMap["money"] = moneyAmountAfter;
var writeMap = {};
writeMap['/Posts/'+oldPostKey] = null;
writeMap['/Locality/'+postMap["dist"]+'/'+oldPostKey] = null;
writeMap['/Posts/'+newPostKey] = updateMap;
writeMap['/Locality/'+postMap["dist"]+'/'+newPostKey] = updateMap;
writeMap['/MyPosts/'+fixedPostId] = updateMap;
writeMap['/OldNewKey/'+fixedPostId] = newPostKey.toString();;
return admin.database().ref().update(writeMap);
});
});
}else{
return null;
}
});
【问题讨论】:
标签: android firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions