Not as much a feature request, but I ran into a moderately difficult problem to debug, and just want to leave my solution here for future googlers.
To start off, these are the versions I'm working with:
gatsby: 2.1.18
graphql-codegen: 1.0.6
My goal is to generate TypeScript typings for the Gatsby queries I'm defining. An example query:
import { graphql } from 'gatsby';
export const query = graphql`
query HomeAvatars {
jane: file(relativePath: { eq: "jane.jpg" }) {
childImageSharp {
fluid(maxWidth: 250) {
...GatsbyImageSharpFluid
}
}
}
john: file(relativePath: { eq: "john.jpg" }) {
childImageSharp {
fluid(maxWidth: 250) {
...GatsbyImageSharpFluid
}
}
}
}
`;
I'd then run the typescript and typescript-operations plugins against my local gatsby server:
schema: http://localhost:8000/___graphql
documents:
- ./src/**/*.{ts,tsx}
generates:
./src/graphqlTypes.ts:
plugins:
- typescript
- typescript-operations
This results in the following error output:
$ /<redacted>/node_modules/.bin/graphql-codegen
✔ Parse configuration
❯ Generate outputs
❯ Generate ./src/graphqlTypes.ts
✔ Load GraphQL schemas
✔ Load GraphQL documents
✖ Generate
→ Cannot read property 'onType' of undefined
Found 1 error
✖ ./src/graphqlTypes.ts
TypeError: Cannot read property 'onType' of undefined
The cause of this error is that I'm referencing the GatsbyImageSharpFluid fragment in my query, but graphql-codegen isn't aware of this fragment. I guess there's an opportunity to improve the error message here.
Gatsby implements a mechanism of ingesting fragments, and the fragment in question here is defined in the gatsby-transformer-sharp package:
gatsby-transformer-sharp/src/fragments.js
export const gatsbyImageSharpFluid = graphql`
fragment GatsbyImageSharpFluid on ImageSharpFluid {
base64
aspectRatio
src
srcSet
sizes
}
`
So if we can get graphql-codegen to ingest this file, we should be good to go.
schema: http://localhost:8000/___graphql
documents:
- ./src/**/*.{ts,tsx}
+ - ./node_modules/gatsby-*/**/*.js
generates:
./src/graphqlTypes.ts:
plugins:
- typescript
- typescript-operations
Success :tada:
$ /<redacted>/node_modules/.bin/graphql-codegen
✔ Parse configuration
✔ Generate outputs
Hi @edorivai !
Thank you for reporting it. We should definitely document how to use it with Gatsby fragments, and make the error message better.
Fixed in https://github.com/dotansimha/graphql-code-generator/commit/72ddabcfae838313d10d8e50f392e3c741188460 .
Thanks @edorivai
Fixed in 1.0.7 :)
Now it will show a better error, and we added docs for Gatsby integration.
Most helpful comment
Fixed in https://github.com/dotansimha/graphql-code-generator/commit/72ddabcfae838313d10d8e50f392e3c741188460 .
Thanks @edorivai