【发布时间】:2018-04-15 19:46:35
【问题描述】:
我正在使用 firebase 函数,并且每次都尝试通过我在正文中发送的请求来更新/增加值。 那是我在 firebase 中的节点
"global-counters": {
"1": "0",
"2": "0",
"3": "0"
},
这是我写的函数
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
let answers = { '1': 0, '2': 0, '3': 0 }
exports.tryGetCount = functions.https.onRequest((req, res) => {
console.log(`req method ${req.method}`)
let userAnswer = req.body.answer;
console.log(`user answer is ${userAnswer}`)
let userInformation = req.body.userInfo;
if (answers.hasOwnProperty(userAnswer)) {
admin.database().ref('/global-counters').child(userAnswer).transaction(eventSnapshot => {
let parseAnswer = parseInt(eventSnapshot)
eventSnapshot = parseAnswer +1; // here i want to increment the value
return eventSnapshot;
}).then((e) => {
return admin.database().ref('/questionsTest').child(userInformation.uid).set(userInformation).then((snapshot) => {
return res.send({ snapshot: snapshot, answers:e})
}).catch((e)=>{
return res.status(400).json({error:e})
})
}).catch((e) => {
return res.status(400).json({ error: e });
})
} else {
return res.status(400).json({ error: 'invalid property user answer' })
}
});
这就是我做的 post http 请求
{
"answer":"3",
"userInfo":{
"uid":"1239",
"gid": "1",
"qid":"2",
"aid":"3"
}
}
我想做的是,例如用户发送
'answer':'3'
所以我想将索引“3”增加 +1 到 firebase,然后将用户数据保存在其他节点中。
其次,当我尝试使用邮递员或任何方式发出请求时,我收到此错误
Error: could not handle the request
当我以这种方式更改功能时
exports.tryGetCount = functions.https.onRequest((req, res) => {
console.log(`req method ${req.method}`)
console.info(req.body)
let userAnswer = req.body.answer;
console.log(`user answer is ${userAnswer}`)
console.log(`typeof is`,typeof userAnswer) // i get "type of string"
let userInformation = req.body.userInfo;
if (answers.hasOwnProperty(userAnswer)) {
return admin.database().ref(`/global-counters/${userAnswer}`).transaction(eventSnapshot => {
console.info(`event snapshot ${eventSnapshot}`)
let parseAnswer = parseInt(eventSnapshot);
eventSnapshot = parseAnswer +1;
return eventSnapshot;
}).then((e) => {
return admin.database().ref('/questionsTest').child(userInformation.uid).set(userInformation).then((snapshot) => {
return res.send({ snapshot: snapshot, answers:e})
}).catch((e)=>{
return res.status(400).json({error:e})
})
}).catch((e) => {
return res.status(400).json({ error: e });
})
} else {
return res.status(400).json({ error: 'invalid property user answer' })
}
});
所以这种方式交替工作。例如,我通过邮递员运行它,4 次尝试中的 3 次,它不起作用它显示错误
错误:无法处理请求
我最后一次尝试,它工作并返回
{
"answers": {
"committed": true,
"snapshot": 4
}
}
【问题讨论】:
-
console.info(event snapshot ${eventSnapshot})注销什么? -
有时它显示我正在寻找的特定键的当前值,有时它为空。当它发生时我拍了这个屏幕视频,如果有什么方法可以分享,我很乐意这样做
标签: javascript firebase firebase-realtime-database google-cloud-functions