For authorization flow, in middleware, I want to equal any value in a .eq
statement. A normal user should only see a post if they created it. An admin should see any post though.
const userMatcher = user.role === "admin" ? "*" : user.id;
const { data: post } = await supabase
.from("posts")
.select("*")
.eq("id", id)
.eq("userId", userMatcher)
.single();
Matching "*" here won’t work. I would like to keep this code clean and not duplicate the query (minus the user matcher) for the admin case.
What is the cleanest way to do this, if at all possible?
2
Answers
Just split up your query. You don’t need to do it all in one "line".
Michael Coxon
‘s answer is perfect.Alternatively, You can achieve the similar result via combination of multiple
logical operators
.Try this:
For Admin user.role === "admin", so the condition userId.eq.true always evaluates to true, allowing admin users to see all the posts.
For Others: the condition userId.eq.{userId: user.id} restricts the selection to posts where the userId matches the current user’s ID.
id.eq.${id} ensures that the post with the specified id is retrieved.