v0
Guides
Programmatic Usage / SDK
⚠️
This is the documentation for the old GraphQL Mesh version v0. We recommend upgrading to the latest GraphQL Mesh version v1.

Migrate to GraphQL Mesh v1

Programmatic usage of Mesh / SDK

You can use GraphQL Mesh as a completely type-safe SDK in your existing TypeScript project, or for programmatically executing queries.

Executing queries programmatically

Mesh’s execute function could be used to directly carry out a query:

import { execute } from './.mesh'
 
const exampleDocument = /* GraphQL */ `
  query myQuery($someVar: String!) {
    foo(someArg: $someVar) {
      bar
    }
  }
`
 
const exampleVariables = {
  someArg: 'SOME_VALUE'
}
 
const result = await execute(document, variables)

Generating fully type safe SDK

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:

.meshrc.yaml
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:

test.ts
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: