Supabase - equivalent to infinite value
P粉741223880
2023-08-15 18:53:11
<p>For the authorization flow, in the middleware, I want to match any value in the <code>.eq</code> statement. Ordinary users can only see posts created by themselves. Administrators can see all posts. </p>
<pre class="brush:js;toolbar:false;">const userMatcher = user.role === "admin" ? "*" : user.id;
const { data: post } = await supabase
.from("posts")
.select("*")
.eq("id", id)
.eq("userId", userMatcher)
.single();
</pre>
<p>Matching "*" has no effect here. If possible, I'd like to keep this code clean and not duplicate the query (minus the user matcher) for the admin case. </p>
<p>If possible, what is the cleanest way? </p>
Michael Coxon
's answer is perfect.Alternatively, you can achieve similar results through a combination of multiple
logical operators
.Try this:
For admin users: user.role === "admin", so the condition userId.eq.true always evaluates to true, allowing admin users to view all posts.
For other users: ConditionsuserId.eq.{userId: user.id}Limits the selection to only posts whose userId matches the current user's ID.
id.eq.${id} Ensure that the post with the specified id is retrieved.
Just split the query. You don't need to do everything in one line.