Vallo
Vallo

Reputation: 1967

Supabase select and join a 1-1 relation with Typescript support

I have the following select query:

return supabase
    .from("Content")
    .select(`*, Users (userId, firstname)`)
    .eq("Users.userId", "Content.userId")
    .eq("contentId", contentId)
    .limit(1)
    .single();

the response object has this structure:

{
  contentId: string;
  content: json;
  Users:
    | ({
        userId: string;
      } & {
        firstname: string | null;
      })
    | ({
        userId: string;
      } & {
        firstname: string | null;
      })[]
    | null
    | undefined;
};

I know for a fact that Users join will always return a single element, can I avoid the typescript definition to be an element or an array? I want it to just be an element (or null, or undefined).

Upvotes: 8

Views: 2603

Answers (1)

Vallo
Vallo

Reputation: 1967

Turns out you can specify the Typescript type in the select statement:

type ReturnType = Content["Row"] & {
  User: Users;
};

 return supabase
    .from("Content")
    .select(
      `*,
      User:Users(*)`
    )
    .eq("short_id", shortId)
    .returns<ReturnType>()
    .single();

Upvotes: 18

Related Questions