I have a Firebase realtime database that's structured like this:
referrals
Test1: 0
Test2: 0
I'm trying to check if "referral_code" exists in the database, this is the code I'm using:
exports.validateReferral = functions.https.onCall((data, context) => {
const referral_code = data.ref
console.log("Cloud verifying referral code, code is " + referral_code)
admin.database().ref().child("referrals").once("value", snapshot => {
if (snapshot.hasChild(referral_code)) {
console.log("referral code is valid");
return true
} else {
console.log("referral code is not valid");
return false
}
})
})
When I run it, it shows "Cloud verifying referral code, code is Test1" but it also returns not valid despite the key being in the database.
Any idea how I can debug this? I tried logging the value of "snapshot" but none of the contents of Firebase snapshots show the actual values. Can anyone help me figure out how to locate the problem?
You're missing a return
at the top level of your code:
// 👇
return admin.database().ref().child("referrals").once("value").then((snapshot) => {
if (snapshot.hasChild(referral_code)) {
console.log("referral code is valid");
return true
} else {
console.log("referral code is not valid");
return false
}
})
Without the top-level return, the return value from the asynchronous callback never reaches your client, and (worse) the code probably gets terminated before the result is ever read from the database.
But I recommend also changing the code to not download the entire referrals
node just to check if one key exists. This accomplish the same and only downloads (at most) a single child node:
// 👇 👇
return admin.database().ref().child("referrals").child(referral_code).once("value").then((snapshot) => {
// 👇
if (snapshot.exists()) {
console.log("referral code is valid");
return true
} else {
console.log("referral code is not valid");
return false
}
})