GraphQL frontend schema types

So i am pretty new to graphql and apollo, but have been using it sucessfully these last few weeks together with strapi. Something i am wondering about is, is there some way to get the grapqhl type definitions from strapi into my frontend repo? So that I could hopefully get some intelisense when writing my queries akin to how the playground does it.

I feel like most of my bugs are due to misspellings in the actual queries themselves.

Any tips or advice is welcome!

PS, using typescript, next.js and apollo client for the frontend

1 Like

One thing i found really helpful is https://github.com/dotansimha/graphql-code-generator. It fetches all the schemas from your graphql endpoint and generates one file with everything typed out.

To use it, you just need to install the @graphql-codegen/cli and @graphql-codegen/typescript packages, add a codegen.yml file to your project and run the graphql-codegen --config codegen.yml command.

// codegen.yml
overwrite: true
schema: "http://localhost:1337/graphql"
generates:
  ./src/types.d.ts:
    plugins:
      - "typescript"

One downside is that it types out every schema it finds on the endpoint and generates a pretty huge file. But that should not be that big of a deal because d.ts files do not end up in final builds.

Hope that helps.

2 Likes

This helped me the absolute most!! I was struggling to create the types and interfaces needed to make my NextJS site be typed correctly.

I’m wondering if you might be able to do this out of the box by declaring artifacts and setting generateArtifacts to true in the GraphQL plugin config: Plugins configuration - Strapi Developer Docs

I haven’t been able to generate any input using this myself however :frowning:

strapi 4.9.x

I have generated scheme and typescript types with this config:

  graphql: {
    enabled: true,
    config: {
      endpoint: '/graphql',
      shadowCRUD: true,
      playgroundAlways: false,
      depthLimit: 7,
      amountLimit: 100,
      generateArtifacts: true,
      artifacts: {
        schema: path.join(__dirname,"..","..","graphql/graphql_schema.graphql"),
        typegen: path.join(__dirname,"..","..","graphql/graphql_types.d.ts"),
      },
      apolloServer: {
        tracing: false,
      },
    },
  },