graphql-let icon indicating copy to clipboard operation
graphql-let copied to clipboard

How to import enum from graphql schema to resolvers

Open michalkvasnicak opened this issue 3 years ago • 4 comments

Using next.js example https://github.com/vercel/next.js/tree/canary/examples/with-typescript-graphql when I try to do the following:

# lib/type-defs.graphqls

type Query {
  viewer: User!
}

# introduced Test enum
enum Test {
  VALUE_1
  VALUE_2
}
# lib/user.graphqls

type User {
  id: ID!
  name: String!
  status: String!
  val: Test! # used Test enum 
}

then when I try to import Test enum in lib/resolvers.ts

import { QueryResolvers, Test } from './type-defs.graphqls'
import { ResolverContext } from './apollo'

const Query: Required<QueryResolvers<ResolverContext>> = {
  viewer(_parent, _args, _context, _info) {
    return { id: String(1), name: 'John Smith', status: 'cached', val: Test.Value_1 }
  },
}

export default { Query }

I receive webpack error:

image

Is there any example how to import enums from GraphQL schema to typescript code so I can have them defined only in schema and use generated typescript files in my project?

michalkvasnicak avatar Sep 29 '20 09:09 michalkvasnicak

I tried to change webpack configuration to use babel loaders on graphqls files too but it didn't help.

image

michalkvasnicak avatar Sep 29 '20 09:09 michalkvasnicak

@piglovesyou I tried to change schemaLoader.js to be similar to loader.js:

  • return content of a generated tsx file from processGraphQLCodegenSchemaLoader()
  • set up this.resourcePath to the path of the generated tsx file
  • return tsxContent in callback()

it seems to work OK but after yarn build it has problem to construct the schema because typeDefs are missing? Not sure what's happening.

michalkvasnicak avatar Sep 29 '20 14:09 michalkvasnicak

Hi @michalkvasnicak, thank you for pointing it out. So true. ResolverTypes support in graphql-let was originally designed just to get TypeScript types, but it turns out it's not enough. It was because I thought many users would run graphql-tag/loader after 'graphql-let/schema/loader'. But, at least in the Next.js example, it doesn't anymore.

As you said, perhaps we should do the same as .graphql loader. Your third try can be close to a PR we want. I mentioned "ResolverTypes support is experimental" in the docs, so I think we can change the behavior.

piglovesyou avatar Sep 30 '20 07:09 piglovesyou

  • [ ] Let graphql-let/schema/loader return transformed source
  • [ ] Modify the docs
  • [ ] Mention the breaking change in the release note

piglovesyou avatar Sep 30 '20 07:09 piglovesyou