Looking for some help with structuring a Firebase query in Angular. I have a collection of documents, each with an array field containing a list of the userIds that are permitted to view the document.
This query works great for bringing back all the docs that have any given user in the array, and I have a corresponding rule on Firebase to ensure security.
return this.firestore
.collection('accounts', (ref) =>
ref.where('users', 'array-contains', this.userId)
)
.valueChanges();
So far, so good.
Some of the users have a custom claim set: admin=true and I want to restructure the above query so that the limit on the query is not enforced for these users and all documents will be returned. I don't particularly want to have the admins' userIds added to the array for every document - feels unnecessary.
I could write an admin version of the query and use the claim status to determine which one to execute at any time, but that feels rather painful and is going to be irritating when I have to do it for every query in the app.
Is there a smarter way to write a single query that will execute the 'where' only when the user does not have the admin=true claim? The Firebase security rule already allows any documents to be returned for admin users.
I can also do something like this:
return this.firestore
.collection('accounts', (ref) =>
this.isAdmin ? ref : ref.where('users', 'array-contains', this.userId)
)
.valueChanges();
but that still feels a bit clunky. Hopefully there's some really straightforward and clean way to achieve this. Maybe I'm not approaching the whole thing in the right way...?
CodePudding user response:
I don't think your solution is clunky. Just add a short comment like "fetch all documents if admin, otherwise fetch all documents authorized to read".