MichalLytek / typegraphql-prisma

Prisma generator to emit TypeGraphQL types and CRUD resolvers from your Prisma schema
https://prisma.typegraphql.com
MIT License
891 stars 113 forks source link

Relations in the typing #392

Closed highruned closed 1 year ago

highruned commented 1 year ago

Is your feature request related to a problem? Please describe. Currently, if you import a type, it doesn't include relations. They are in the generated client code (eg. Prisma__OrderClient) but not the type. I need it so that 1) I can get -some- proper typing on my code, even if they're optional 2) other devs can see what could exist on the data and what types they are.

Describe the solution you'd like Simplest solution is add them as optionals, or to generate "type OrderWithRelations"

So from this schema:

model Order {
  Id                      String                    @id(map: "Order_Id_PK") @db.UniqueIdentifier
  UserId                  String?                   @db.UniqueIdentifier
  User                    User?                     @relation(fields: [UserId], references: [Id], map: "Order_UserId_FK")
  CommentsOnOrders        CommentsOnOrders[]
  RecordUpdatesOnOrders   RecordUpdatesOnOrders[]
}

Currently we get this:

export type Order = {
  Id: string
  UserId: string | null
}

We need this:

export type Order = {
  Id: string
  UserId: string | null
  User?: User
  CommentsOnOrders?: CommentsOnOrders[]
  RecordUpdatesOnOrders?: RecordUpdatesOnOrders[]
}

or this (notice not optional so it matches schema):

export type OrderWithRelations = {
  Id: string
  UserId: string | null
  User?: User
  CommentsOnOrders: CommentsOnOrders[]
  RecordUpdatesOnOrders: RecordUpdatesOnOrders[]
}

Describe alternatives you've considered Redefining types for every model, recomposing them based on schema, which is pretty much madness.

Additional context I've abstracted the CRUD calls so that it generates the create/update query based on the diff of the object. So other developers don't need to know anything special. They simply do order.something = something and it just works. But without types, this is not fun.

Appreciate your consideration 🙏

MichalLytek commented 1 year ago

Object Types contains TS side of relations (optional fields). For registering them in GraphQL schema, you need to import relation resolvers for given entity. Relations in SQL databases does not happen automagically, so you need the glue code for that.

highruned commented 1 year ago

Hey Michal, sorry how do I get access to the types in the same way they appear in the Prisma schema?

If I use type Order I get this:

image

If i use type Prisma.OrderCreateInput

image
MichalLytek commented 1 year ago

Why don't you use GraphQL Codegen to make your graphql queries type-safe?

highruned commented 1 year ago

Why don't you use GraphQL Codegen to make your graphql queries type-safe?

Ah good idea, that worked, thanks!