我正在尝试通过Firebase设置实时数据库,并使用Firebase函数测试其中是否存在随机值。任何帮助将不胜感激。
我尝试了下面的代码,但最终遇到了“未处理的错误事件”。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.Exists = functions.https.onRequest((request, response) => {
console.log("Hello from Firebase!");
var result = '';
var characters = 'ABCDEFGHIJKLMNPRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
var charactersLength = characters.length;
for ( var i = 0; i < 4; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return admin.database().ref().once(result).then(snap => {
if (snap.exists()) {
response.send("exists");
}else{
response.send(result);
}
});
答案 0 :(得分:1)
您的数据库调用混乱了,应该是
admin.database().ref(result).once('value').then(snap => ...)
result
是您要寻找的钥匙value
是您一次“监听”的事件,您也可以继续通过ref().on('value', callback)
监听值的变化这是文档中的相关部分:https://firebase.google.com/docs/database/web/read-and-write#read_data_once
答案 1 :(得分:0)
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.test = functions.https.onRequest((request, response) => {
return ExistTest();
function RandCharGen(length){
var result = '';
var characters = 'ABCDEFGHIJKLMNPRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function ExistTest(){
var result = RandCharGen(4);
admin.database().ref(result).once('value', (snapshot) => {
if (snapshot.exists()) {
ExistTest();
}
else{
response.send(result);
return result;
}
});
}
});
对于任何想要正确答案或知道更清洁方法的人。