Noobdeveloper
Noobdeveloper

Reputation: 505

Firestore security rules ternary operators is not working

Firebase firestore security rules ternary operators if else is not working I don't know why please help me with references to articles or answers

if author(userid)
                && data().postcounter != null
                ? data().postcounter >= 0
                : data().itemtype == 'jug'

What I found in testing is only first if operators return is working not the else part I am from dart background

Edit: data() = request.resource.data

Upvotes: 3

Views: 348

Answers (1)

Hessuew
Hessuew

Reputation: 773

Your question should specify what are you trying to accomplish with the code you have given.

Nevertheless I don't know if this solves the issue but at least this guides you to better and more clear code.

If you are trying to use custom function with request.resource.data I would suggest this way of giving permission. It will make code more readable and easier to maintain and also makes it possible to use same function in many permission check:

function exampleFunction(data) {
let postcounter = data.postcounter != null;
let postcounter2 = data.postcounter >= 0;
let itemtype = data.itemtype == 'jug';

return request.auth.uid != null && postcounter ? postcounter2 : itemtype;
}

match /ExampleColletion/{ID}{
    allow read, write, update, delete: if exampleFunction(request.resource.data);
  }

I myself use above example with project with something like 20 collections and have common functions to be used for permission check. This way giving permission is much cleaner and it makes creating and maintaining rules much more easier especially in larger projects with data validation and custom permission giving in Firestore rules.

Reference: https://firebase.google.com/docs/rules/rules-language#building_conditions
https://firebase.google.com/docs/firestore/security/rules-conditions

Upvotes: 2

Related Questions