Getting started with GraphQL-Sdk-Generator

GraphQL SDK generator translates GraphQL Schema to Javascript, Typescript code enabling you to get smooth auto completion and validation for your GraphQL Schema,

Installation

First install the required package from npm(we will use Apollo space x as a sample example). GraphQL SDK Generator is a standalone package. Once you generate the code, you don't need the package anymore, so it is recommended to install it globally.

npm i -g graphql-sdk-generator

Then will create a config.json file with the following contents.

config.json
{
  "url": "https://spacex-production.up.railway.app/", 
  "sdkName": "SpaceX", 
  "fileType": "ts",
  "debug": true
}

Then run the graphql-sdk-generator command to generate the client inside a directory by passing path of config file using -c

graphql-sdk-generator -c config.json 

Once the code is generated, you need to install additional dependencies to run the generated code. These dependencies are necessary for making requests using the generated SDK

npm i @graphql-typed-document-node/core graphql-request

Using the client

The generated client exposes a getSdk function. To use it, initialize a GraphQLClient, pass custom headers if necessary, and pass the client to getSdk to send requests.

import { GraphQLClient } from "graphql-request";
import { getSdk } from "../graphqlSDKGenerator/graphqlSDKGenerator";

const initializeSDK = () => {
  // we can set custom headers
  const client = new GraphQLClient(
    "https://spacex-production.up.railway.app/",
    {
      headers: {},
    }
  );

  return getSdk(client);
};

const main = async () => {
  const sdkInstance = initializeSDK();
  const companies = await sdkInstance.companyQuery();
  
  // we get autocomplete here both for the arguments && output.
  const user = await sdkInstance.insert_usersMutation({
    objects: { id: 1, name: "test", rocket: "spacex" },
  });

  console.log(companies, user);
};

main();

Node.js version Compatibility

GraphQL SDK generator will only work for Node.js 18+ and is not tested for below versions.

Handling errors

All the errors generated by client is handled by a custom error handler which you add in your codebase by seeing this example here.

Unsupported features

Currently we don't support the following features (some features are planned in future)

  1. Custom naming for mutations, queries, variables

  2. Allow to create multiple clients in one folder

  3. We cannot pass a custom fetch client as the script is highly dependent on graphql-request

  4. Batching requests

Read more

Usage

Config file reference

Examples

Comparisons

Last updated