问题
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.
回答1:
Firestore Rules are meant to define the rules for accessing the particular collections in your Project. They are primarily used to check access for the user. They are not meant for anything other than checking logic. So they don't support switch statements, if..else conditions and conditional expressions.
You can use OR condition to check if the user can add the product according to the UserTier he/she belongs to.
function canAddProduct() {
return ( getTier() == 'UserTier.FREE' || getTier() == 'UserTier.SILVER'
|| getTier() == 'UserTier.GOLD' || getTier() == 'UserTier.COMPANY' );
}
This is the simplest way of checking access.
However for your particular case try this. I'm assuming that you have further checks on the user according to the tier they belong to. Here I'm checking if the user's trial period is expired only if he is belonging to the FREE Tier.
function getUser() {
//Get the user
return get(/users/$(request.auth.uid)).data;
}
function canAddProduct() {
return ( getTier() == 'UserTier.FREE' && checkFreeTierAccess(getUser()) ||
getTier() == 'UserTier.SILVER' && checkSilverTierAccess(getUser()) ||
getTier() == 'UserTier.GOLD' && checkGoldTierAccess(getUser()) ||
getTier() == 'UserTier.COMPANY' && checkCompanyTierAccess(getUser())
);
}
function checkFreeTierAccess(user) {
//do the checks
return user.isTrailPeriodExpired;
}
Hope this solves your problem.
回答2:
One other hack to be aware of is the use of objects. It took me a while to figure out this was possible. You can put your different cases into an object and use the object keys as the switch.
function switchOnTier(tier) {
return {
'UserTier.FREE': doSomethingBasedOnFreeTier(),
'UserTier.SILVER': doSomethingBasedOnSilverTier(),
'UserTier.GOLD': doSomethingBasedOnGoldTier(),
'UserTier.COMPANY': doSomethingBasedOnCompanyTier()
}[tier]
}
Which you can then use like this..
return switchOnTier(getTier())
I'm using this for a simple case of trying to pluralize a string (which was surprisingly difficult to do)
function pluralize(str) {
return {
'AccessToken': 'AccessTokens',
'Image': 'Images',
'Index': 'Indexes'
}[str]
}
Hope this helps anyone else struggling to figure this out.
来源:https://stackoverflow.com/questions/56336274/possible-to-do-a-if-else-or-a-switch-statement-firestore-rules