Skip to content

Instantly share code, notes, and snippets.

@brentjanderson
Last active April 16, 2021 22:25
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Running graphql-codegen on Redwood

I'm assuming you're using Apollo. This can be changed

  1. Install a few dependencies: yarn add -WD @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo @graphql-codegen/typescript-resolvers npm-run-all ts-node

  2. In my setup, I also threw in npm-run-all and made some edits to my root package.json "scripts": yarn add -WD npm-run-all

     "dev": "npm-run-all --parallel dev:**",
     "dev:rw": "rw dev",
     "dev:graphql-codegen:watch": "sleep 10 && graphql-codegen --watch ", // Sleep 10 so that redwood has ample time to boot up before we start generating types. Tune to your liking.
     // If graphql-codegen can hook into redwood's lifecycles then the sleep 10 would not be required

    If you don't use npm-run-all, you will need to manually run yarn graphql-codegen --watch after starting yarn rw dev in a separate console.

  3. Add codegen.yml verbatim to your project

  4. Anytime you scaffold new code, graphql-codegen will complain because the default redwood scaffold templates generate duplicate operation names.

    e.g. if you have a model Foo and you scaffold your frontend, you will get FooCell and EditFooCell with the same query named FIND_FOO_BY_ID.

    A quick fix is to either:

    1. Rename one query (I change the one in EditFooCell to be FIND_FOO_BY_ID_FOR_EDIT)
    2. Delete one and import it from the other instead.

    In any case, the errors generated by graphql-codegen tend to be helpful in pointing out where the issue is and how to correct it. I haven't had issues apart from duplicate query/mutation names generated from scaffolding.

Some considerations

I have not used this approach in production yet, so it may be desirable to create a root @types directory and have the generated files go there.

schema: http://localhost:8910/api/graphql
watch:
- ./{web,api}/src/**/!(*.d).{ts,tsx,js.jsx}
config:
strict: true
scalars:
DateTime: string
Date: string
JSON: Record<string, unknown>
JSONObject: Record<string, unknown>
Time: string
generates:
./api/src/generated-graphql-types.ts:
plugins:
- typescript
- typescript-resolvers
./web/src/generated-graphql-types.tsx:
require:
- ts-node/register
documents:
- ./web/src/**/!(*.d).{ts,tsx,js,jsx}
plugins:
- typescript
- typescript-operations
# - typescript-react-apollo # Commented out because it generates unused types. Could be useful to consolidate query info in one file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment