javascriptpostgresqlsupabasesupabase-database

Supabase - equal any value


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?


Solution

  • 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();