Supabase - equivalent to infinite value
P粉741223880
P粉741223880 2023-08-15 18:53:11
0
2
415

For the authorization flow, in the middleware, I want to match any value in the .eq statement. Ordinary users can only see posts created by themselves. Administrators can see all posts.

const userMatcher = user.role === "admin" ? "*" : user.id; const { data: post } = await supabase .from("posts") .select("*") .eq("id", id) .eq("userId", userMatcher) .single(); 

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.

If possible, what is the cleanest way?

P粉741223880
P粉741223880

reply all (2)
P粉513316221

Michael Coxon's answer is perfect.

Alternatively, you can achieve similar results through a combination of multiplelogical 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 conditionuserId.eq.truealways 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粉670838735

    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();
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!