Home > OS >  How to set a variable in firebase realtime-database rules
How to set a variable in firebase realtime-database rules

Time:11-30

So my database looks like this:

enter image description here

And my rules look like this:

{
  "rules": {
    ".read": true,
    ".write": true,
    "_default_user":{            <---- this is what I need to change
      "cart":{
        ".indexOn": "product/id"
      }
    }
  }
}

This is my code for removing a product from cart:

removeFromCart(itemRemoved){

    let account = JSON.parse(localStorage.getItem('user')) === null ? '' : JSON.parse(localStorage.getItem('user')).email
    account == '' ?  account = ['_default', ''] : account = /([^@] )/.exec(account)

    const cartRef = firebase.database().ref('/'   account[0]   '_user'   '/cart');
                               // Do I need to change this ^ as well?

    const itemQuery = cartRef.orderByChild("product/id").equalTo(itemRemoved.id);

    let itemRef:any = ''
    itemQuery.get().then((snapshot) => {
       snapshot.forEach((productSnapshot) => {
          itemRef = firebase.database().ref('/'   account[0]   '_user'   '/cart'   '/'   productSnapshot.key);
       })
    itemRef.remove()
    })
}

For now, to remove an item from cart I need to manually add accounts to my rules, which of course, is not feasible. I basically need to have indexOn on all possible accounts without actually doing all that manually.

CodePudding user response:

Turn out I just need to do this:

    {
      "rules": {
        ".read": true,
        ".write": true,
        "$user":{                 // <---
          "cart":{
            ".indexOn": "product/id"
          }
        }
      }
    }

Just type in the variable and .indexOn will apply to every node in root( in my case )

https://firebase.google.com/docs/database/security/core-syntax

  • Related