The Guild LogoThe Guild Monogram
GraphQL Mesh

GraphQL Mesh

Query anything, run anywhere.

Contact Us

Generating fully type safe SDK#

You can use GraphQL Mesh as a completely type-safe SDK in your existing TypeScript project.

Instead of using GraphQL operations as string with execute - you can use GraphQL Mesh and generate a ready-to-use TypeScript SDK to fetch your data. It will make sure to have type-safety and auto-complete for variables and returned data.

 

Getting started#

1. Create or move your GraphQL operations to .graphql files#

Create your own GraphQL operations in a .graphql file for your SDK, for example:

query myQuery($someVar: String!) { getSomething(var: $someVar) { fieldA fieldB } }

 

2. Update your .meshrc.yml configuration#

Now, update your .meshrc.yml to include this GraphQL document, as follows:

sources: #... documents: - ./src/**/*.graphql sdk: generateOperations: selectionSetDepth: 2 # This is the maximum level of selection set

 

3. Build your SDK with Mesh artifacts#

This will generate an SDK inside your Mesh artifacts under .mesh directory;

yarn mesh build

 

4. Use the generated SDK in the code#

Now, instead of using execute manually, you can use the generated getSdk method with your GraphQL Mesh client, and use the functions that are generated based on your operations:

import { getMeshSDK } from './.mesh' async function test() { // Load mesh config and get the sdkClient from it const sdk = getMeshSDK() // Execute `myQuery` and get a type-safe result // Variables and result are typed: { getSomething: { fieldA: string, fieldB: number }, errors?: GraphQLError[] } const { getSomething } = await sdk.myQuery({ someVar: 'foo' }) }

You can find an example for that here

 


 

Configuring SDK Generation#

GraphQL Mesh CLI uses GraphQL Code Generator and its Generic SDK plugin to generate a fully typed SDK from your unified schema. It is possible to configure it to get more customized experience.

See 'Configure GraphQL Code Generator' section to learn more

 


 

Example with Next.js#

Watch Episode #15 of graphql.wtf for a quick introduction to using GraphQL Mesh with Next.js:

Content

Getting startedCreate or move your GraphQL operations to .graphql filesUpdate your .meshrc.yml configurationBuild your SDK with Mesh artifactsUse the generated SDK in the codeConfiguring SDK GenerationExample with Next.js
Edit on GitHub