FroggyPanda / better-supabase-types

73 stars 13 forks source link

Optional relationship fields? #28

Closed khelenek closed 9 months ago

khelenek commented 10 months ago

Would it make sense to create optional fields for one-to-many and many-to-one fields?

type Book { name: string, author_id: number, author?: Author }

type Author { name: string, books?: Book[] }

to support the supabase.from('author').select(', books()') use case?

I'll make a PR if it would be added.

FroggyPanda commented 10 months ago

Could you go more in-depth into the supabase.from('author').select(', books()').

And if I am understanding this correctly, I think the type you would want would be something like this:

type Book = {
  name: string;
  author_id: number;
};

type Author = {
  id: number;
  name: string;
};

The reason I removed the arrays from both types is because of my understanding of tables that have foreign keys is that you use the ID from the "parent" table to establish the relationship of the "children" and don't have arrays of the children.

khelenek commented 9 months ago

Sorry, I didn't use code brackets around my sample so it didn't print correctly. In our project we might do supabase.from('authors').select('*, books(*)) which returns an Author with a books array. I ended up just creating another quick processing layer that adds any child array types as optional fields. Other option is to just write explicit types for these, which has the value of the arrays being not optional. You can close this.