Is it possible to do a Switch Statement or an if else in firestore rules?
I have tried to search for it with no luck of finding an answer.
What i tried was
function getTier() {
return get(/users/$(request.auth.uid)).data.userTier;
}
function canAddProduct() {
if getTier() == 'UserTier.FREE'
// Do additional code
return doSomethingBasedOnFreeTier();
else if getTier() == 'UserTier.SILVER'
// Do additional code
return doSomethingBasedOnSilverTier()
else if getTier() == 'UserTier.GOLD'
// Do additional code
return doSomethingBasedOnGoldTier()
else if getTier() == 'UserTier.COMPANY'
// Do additional code
return doSomethingBasedOnCompanyTier()
}
Any help would be greatly appreciated.
As of Feb 13, 2020 Firestore now supports the ternary operator
https://firebase.google.com/support/release-notes/security-rules#february_13_2020
Here's the documentation for the available operators (ternary is at the bottom)
https://firebase.google.com/docs/rules/rules-language#building_conditions
Taking the example code from the question, the solution can be achieved by using a nested set of ternary operators
function getTier() {
return get(/users/$(request.auth.uid)).data.userTier;
}
function canAddProduct() {
return getTier() == 'UserTier.FREE' ?
doSomethingBasedOnFreeTier() :
(
getTier() == 'UserTier.SILVER' ?
doSomethingBasedOnSilverTier() :
(
getTier() == 'UserTier.GOLD' ?
doSomethingBasedOnGoldTier() :
(
getTier() == 'UserTier.COMPANY' ?
doSomethingBasedOnCompanyTier() :
null
)
)
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With