Graphql-code-generator: Making non-scalar types optional or omit while generating resolver types??

Created on 15 Mar 2020  路  3Comments  路  Source: dotansimha/graphql-code-generator

Hey, coolest folks in graphql world,

Let's say I have this schema:

type User {
  id: ID!
  name: String!
  age: Int!
  posts: [Post!]!
}

type Query {
  user: User!
  users: [User!]!
}

and this resolver(s):

import { Resolvers } from 'types/resolver'

const resolvers: Resolvers = {
  User: {
    // this will resolve posts for particular user
    posts: ({ id }, args, { prisma }) => prisma.user({ id }).posts()
  },
  Query: {
    user: (parent, { id }, { prisma }) => {
      // this will resolve single user but with only scalar fields i.e:
      /*
        id: String!
        name: String!
        age: Int! 
      */
      return prisma.user({ id });
    }
  }
}

now to gotcha is in Query -> user resolver, generated resolver expects Query -> user to resolver posts too but since I am using Prisma and Prisma will only send scalar fields, so it shows an error,

so is it possible to make non-scalar types options while generating resolver types??
(hope you got it, sorry for my bad English)

Most helpful comment

Exactly as @ardatan said, you can use mappers to map your GraphQL types into a your model (prisma) types and codegen will use it as return/parent value where needed.

All 3 comments

If you have a different return type in resolvers, you can use mappers
https://graphql-code-generator.com/docs/plugins/typescript-resolvers#mappers-object

Exactly as @ardatan said, you can use mappers to map your GraphQL types into a your model (prisma) types and codegen will use it as return/parent value where needed.

sidenote:
If someone is using Prisma and generating prisma-client then I would recommend importing Mapper types directly from generated code.

for example:

generates:
  ./packages/api/src/types/resolvers.ts:
    plugins:
      - typescript
      - typescript-resolvers
      mappers:
        User: ./generated/prisma-client/index#User
        Post: ./generated/prisma-client/index#Post

so that you don't have to maintain two separate files,

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mdaouas picture mdaouas  路  3Comments

leonardfactory picture leonardfactory  路  3Comments

edorivai picture edorivai  路  3Comments

mszczepanczyk picture mszczepanczyk  路  3Comments

fvisticot picture fvisticot  路  3Comments