graphql-code-generator icon indicating copy to clipboard operation
graphql-code-generator copied to clipboard

Ability to merge mapped types

Open dac09 opened this issue 3 years ago • 0 comments

Context When using typestrict-resolvers plugin, and using the mappers property to map Prisma types

Let's say codegen generates the following:

import { Post as PrismaPost } from '@prisma/client';

// This shows all the fields inside post
export type Post = {
  __typename?: 'Post';
  body: Scalars['String'];
  id: Scalars['Int'];
  createdAt: Scalars['DateTime'];
  title: Scalars['String'];
}

// And we have the Prisma type, which we map
export type ResolversTypes = {
  Post: ResolverTypeWrapper<PrismaPost>;
  //...
}

There are two cases I'd like to support:

1. Return a subset of the fields Let's say I modify my SDL to only return a subset of the fields in Post. In this case, I never want to return the createdAt property.

export const schema = gql`
  type Post {
    id: Int!
    title: String!
    body: String!
-    createdAt: DateTime
  }

The Resolver types will error out if I do not return createdAt in the resolver.

What's happening here is that SDL type gets updated, but the Prisma type doesn't (obviously, because we are mapping it, and the field still exists in the DB). What I'd ideally be able to do is "pick" all the fields that are common in both the Prisma and the SDL Post type.

2. Return extra fields In the opposite case, I'd like to return extra properties from my GraphQL API, that does not exist in the database/Prisma model. e.g.

export const schema = gql`
  type Post {
    id: Int!
    title: String!
    body: String!
+  sdlOnlyProperty: String!
  }

The generated types will lack some of the type safety, because the mapped Post type from Prisma does not contain sdlOnlyProperty.

Describe the solution you'd like One way to achieve this, could be to give us the ability to construct the result type ourselves.

Currently ResolverTypeWrapper only takes T as param, where T is the mapped type. Would it be possible for this generic to take both TMapped and TSdl?

Describe alternatives you've considered Would it make sense to have a configuration property that does the "type merging" for you?

dac09 avatar Jul 06 '22 20:07 dac09