<p>对于授权流程,在中间件中,我想要在<code>.eq</code>语句中匹配任何值。普通用户只能看到自己创建的帖子。管理员可以看到所有帖子。</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>在这里匹配"*"是不起作用的。如果可能的话,我希望保持这段代码的整洁,而不是为管理员情况重复查询(减去用户匹配器)。</p>
<p>如果有可能,最干净的方法是什么?</p>
Michael Coxon的回答是完美的。或者,您可以通过多个
逻辑运算符的组合来实现类似的结果。尝试这样做:
const userMatcher = user.role === "admin" ? true : { userId: user.id }; const { data: post } = await supabase .from("posts") .select("*") .or(`userId.eq.${userMatcher}`, "id.eq." + id) .single();对于管理员用户:user.role === "admin",因此条件userId.eq.true始终评估为true,允许管理员用户查看所有帖子。
对于其他用户:条件userId.eq.{userId: user.id}限制了选择只有userId与当前用户的ID匹配的帖子。
id.eq.${id}确保检索到指定id的帖子。
只需将查询拆分。您不需要在一行中完成所有操作。
let query = supabase .from("posts") .select("*") .eq("id", id); if(user.role === "admin"){ query = query.eq("userId", user.id) } const { data: post } = await query.single();