Bart Kooijman

Autogenerate TypeScript Models

Bart Kooijman

Bart Kooijman / 2019-09-08

2 min read

Working with GraphQL in Sitecore JSS is great, it's awesome. But there is always room for improvement. While building your frontend components, you will end up spending time of mapping your props to the GraphTypes and the structure of your query. Isn't there a way to autogenerate this? Spoilers.. there is!

Setup

We will use the GraphQL Code Generator CLI tool.

  1. Install the packages:
npm install @graphql-codegen/add @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations
  1. Create a codegen.yml file in the root of the project, with the following setup:
schema: http://REACT_APP_SITECORE_API_HOST/api/REACT_APP_NAME?sc_apikey=REACT_APP_SITECORE_API_KEY
config:
  skipTypename: true
documents:
  - [
      sitecore/definitions/components/*.graphql,
      '!*sitecore\definitions\components\GraphQL-IntegratedDemo.sitecore.graphql'
    ]
  - [
      src/**/*.graphql,
      '!*.src/jsscomponents/jsscomponents/GraphQL-ConnectedDemo/query.graphql'
    ]
generates:
  ./src/models/Types.ts:
    plugins:
      - add: '/* tslint:disable */'
      - add:
          content:
            - ''
            - '// This file is generated. Do not change this file manually.'
      - typescript
      - typescript-operations

Luckily the documentation of the configuration is excellent. In this setup I have excluded the demo queries, which are part of the starter JSS project.

  1. Keep your schema as small as possible. Otherwise you will end up by generating hundreds of types. You can check how many types your schema contains by opening the url:
http://REACT_APP_SITECORE_API_HOST/api/REACT_APP_NAME/stats?sc_apikey=REACT_APP_SITECORE_API_KEY

Here you can see the stats, for example:

Schema providers: 3
# of types: 96
# of scalars: 21
# of interfaces: 21
# of concrete: 52

These stats are a good starting point for optimizing the size of your schema. You can configure this in your JSS config under the templates node, in which you declare which templates must be included in the schema:

<paths hint="list:AddIncludedPath">
    <templates>/sitecore/templates/Project/my-jss-airport-project/planes</templates>
</paths>

As an alternative you can also create your own fieldfilter to keep you schema lean and clean. Let's go to the final step.

  1. Add the script to your package.json
"generate:typescript": "graphql-codegen"

and run it:

npm run generate:typescript

You should have a Types.ts file in a models folder now!

Last week my setup for generating code based on your GraphQL schema also has been merged in the React JSS Typescript Starter Template. This template is created by Gary Wenneker and Serge van den Oever. Try it out!