skip to Main Content

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


  1. Just split up your query. You don’t need to do it all 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();
    
    Login or Signup to reply.
  2. Michael Coxon‘s answer is perfect.

    Alternatively, You can achieve the similar result via 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 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search