P粉5133162212023-08-16 16:57:09
Michael Coxon
's answer is perfect.
Alternatively, you can achieve similar results through a combination of multiple logical operators
.
Try this:
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();
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.
P粉6708387352023-08-16 09:09:46
Just split the query. You don't need to do everything in one line.
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();