I have a react app based on create react app and TypeScript. I want to replace redux with Apollo graphql client. I define queries in .graphql files and/or gql-Tag using string templates. I want the result/data from apollo’s Query component to be strongly typed, how can I do that? Without writing interfaced and types myself, I want them to be generated 😬
1 Answer
There is a very good tool for that called Apollo codegen, it's part of apollo-cli.
Have a look into their documentation: https://github.com/apollographql/apollo-cli#apollo-codegengenerate-output
An example to generate the TypeScript definitions would be:
- Download the schema of your server:
apollo schema:download .schema/graphql.json --endpoint=http://localhost:4000/
- Generate the types for your queries:
apollo codegen:generate --schema=.schema/graphql.json --addTypename --target=typescript --queries=src/**/*.{tsx,ts} --outputFlat=src/queries
2 Comments
Thomas
I actually didn't get apollo codegen to work.. Documentation is very outdated, and I ended up debugging apollo codegen, but gave up in the end.. Found another library: graphql-code-generator which worked at last :-) I'm using ApolloClient and that is really great! But couldn't figure out apollo-cli. Actually graphql-code-generator has a template for Apollo too :-)
Marco Daniel
Okay, that’s great! I’ll also have a look into that ‘graphql-code-generator’ :)