Can only call Firebase database value with literal string, not with variable

Viewed 85

I'm using the below Firebase cloud function to confirm that a variable "referral_code" exists in the "referrals" part of my real-time database.

exports.validateReferral = functions.https.onCall((data, context) => {
    const referral_code = data.ref
    console.log("Cloud verifying referral code, code is " + referral_code)
    return admin.database().ref().child("referrals").child(referral_code.trim()).once("value").then((snapshot) => {
        console.log(snapshot.val())
        if (snapshot.exists()) {
            console.log("referral code is valid");
            return true
        } else {
            console.log("referral code is not valid");
            return false
        }
    })
})

For context, here is my database structure.

enter image description here

The above code works as expected (mostly), if I pass "Test1" or "Test2" to it, it returns valid, if I pass "Test3" it's not valid.

>  Cloud verifying referral code, code is Test1
>  0
>  referral code is valid
>  Cloud verifying referral code, code is Test2
>  0
>  referral code is valid
>  Cloud verifying referral code, code is Test3
>  null
>  referral code is not valid

But...if I pass "Test3" or a value that's not in the database, despite the cloud function showing it's not valid, the client-side code I use to call that function returns valid anyway.

var ref = new URLSearchParams(window.location.search).get('ref')
console.log("checkReferral ref is " + ref)
console.log("checkReferral window.location.search is " + window.location.search)
if (ref) {
    console.log("checkReferral ref found")
    if (validateReferral({ ref: ref })) {
        console.log("checkReferral ref is valid")
        return true
    } else {
        console.log("checkReferral ref is not valid")
        return false
    }
}

And this is the output:

checkReferral ref is Test3
checkReferral window.location.search is ?ref=Test3
checkReferral ref found
checkReferral ref is valid

Any ideas why this could be?

1 Answers

Figured out the problem. When calling validateReferral from the client side, I needed to wrap the function call in a promise.

Related