Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do a If Else or a Switch Statement Firestore Rules

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.

like image 256
Tinus Jackson Avatar asked May 28 '19 06:05

Tinus Jackson


1 Answers

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
            ) 
        )
    )
}
like image 81
Brian Neisler Avatar answered Nov 20 '22 03:11

Brian Neisler