简体   繁体   中英

How to set a variable in firebase realtime-database rules

So my database looks like this:

在此处输入图像描述

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM