IdoPesok / zsa

https://zsa.vercel.app
MIT License
761 stars 23 forks source link

Unnecessary null check enforced #216

Closed muezz closed 1 day ago

muezz commented 6 days ago

I am in the process of replacing trpc in my codebase with zsa. So far it has been great but I am noticing a trend.

Whenever I have to use a server action in a server component, I have to do an unnecessary null check to satisfy the typescript overlords.

Here is the action:

export const getAuthenticatedUser = createServerAction().handler(async () => {
  const sp = createClient();
  const {
    data: { user },
    error,
  } = await sp.auth.getUser();
  if (error) throw error;
  console.log(error);
  if (!user) throw Error("User not found");
  return user;
});

export const getUser = createServerAction().handler(async () => {
  const sp = createClient();
  const [authUser, authUserErr] = await getAuthenticatedUser();
  if (authUserErr) throw Error(authUserErr.message);
  // when using the above action inside here, why do I have to perform a null check? 
  // Unless I am misunderstanding something, there is absolutely no possibility of this being null.
  if (!authUser) throw Error("User not found");

  const supabaseClient = await sp
    .from("users")
    .select("*")
    .eq("id", authUser.id)
    .single();
  if (supabaseClient.error) throw supabaseClient.error;
  return supabaseClient.data;
});

Same applies to a server component as well. I hope you get the idea.

Am I misunderstanding something? If not, is there a way to get around this because it is very hectic to keep writing that condition.

In 90% of the cases, I end up rethrowing that error because I expect the user to end up in error.tsx. Even the other condition is not necessary for me. I'd rather just get the value if it is successful but that may be an anti-pattern for the package.

IdoPesok commented 2 days ago

Hi, I suggest to check out shape errors to be able to throw in the 90% of the cases. You can put it in a procedure so it will be inherited by all child actions. For the cases you don't want to throw, you can return a custom error class to check for. With regards to checking for error, it is possible to make a wrapper function that unwraps the zsa response for you.

muezz commented 1 day ago

Looks interesting. I will look into it. Thanks.