Typescript codegen
#
What is codegen?Codegen is a way to generate types from a graphQL schema. Typescript is the most common types that would be generated in javascript, and is what kind of codegen that Finch GraphQL supports. The code generator we support is GraphQL Code Generator and in this page we will go over how to get this setup in your project while using Finch GraphQL.
#
SetupGraphQL Code generator has some good documentation on how to get the library setup. Once you have the cli setup you can skip ahead to getting this to work with Finch GraphQL.
#
Working with SchemasTo load in the schema from Finch it is best to use the schemas source files, if it is in the same repo. For example you may want to store all of schema files in a directory like ./src/typeDefs/schemas
. In this example there is a index.ts
file in the root of typeDefs to export out the array of schemas from the schema folder.
This makes it so the schemas are consumable by the FinchApi typeDefs option and we can also point codegen towards the schema files. Also in this example the schema files looks something like this.
Now you are setup to point your GraphQL Code Generator config towards these schema files, we would also recommend storing your GraphQL documents that consume the API somewhere close to these schema files as well.
This should generate a file with all the types of the GraphQL queries. Now you should be able to pass the types generated from these queries into queryApi and useQuery hooks.
#
Generating custom hooksFinch GraphQL has a module for GraphQL Code Generator that will take these types and generate custom hooks that are hooked into Finch GraphQL. To install the module.
The update your configuration to look something like this
typescript-document-nodes are now generated by finch-graphql-codegen
This should run and now your generated file should contain hooks that make it so you do not need to import so many types.