Skip to content

Code Generation with GraphQL

One of the major benefits of using our GraphQL API is that you should not need to write your own code to interact with it. You should only need to write .graphql files that reflect exactly what data you want to query or mutate, run the GraphQL code generation tool in your language, then use as if our service was part of your own application, complete with strongly typed functions, enums, interfaces/structs/classes, etc…

The following provides examples in popular languages of how to do this.

The following example uses Bun as the bundler & runtime environment.

  1. Start a new project and install dependencies

    #!/bin/bash
    mkdir example && cd example
    bun init
    # Runtime dependencies
    bun add @apollo/client
    # Development dependencies
    bun add @graphql-codegen/cli @graphql-codegen/near-operation-file-preset --dev
  2. Setup codegen configuration

    We will create a codegen file with some configuration for how we want to generate the code.

    ./codegen.ts
    import type { CodegenConfig } from "@graphql-codegen/cli";
    const config: CodegenConfig = {
    overwrite: true,
    schema: "https://api.helioadditive.com/graphql"
    documents: "./**/*.graphql",
    generates: {
    "types.generated.ts": {
    plugins: ["typescript"],
    config: {
    useInterface: true,
    useTypeImports: false,
    declarationKind: {
    input: "interface",
    },
    },
    },
    ".": {
    preset: "near-operation-file",
    presetConfig: {
    extension: ".generated.ts",
    baseTypesPath: "types.generated.ts",
    },
    plugins: ["typescript-operations", "typed-document-node"],
    config: {
    useTypeImports: false,
    declarationKind: {
    input: "interface",
    },
    },
    },
    },
    };
    export default config;
  3. Create a graphql file to query data

    You choose what data you want to fetch

    ./queries/Materials.graphql
    query ListMaterials($page: Int, $pageSize: Int, $filters: [MaterialFilter!]) {
    materials(page: $page, pageSize: $pageSize, filters: $filters) {
    pages
    pageInfo {
    hasPreviousPage
    hasNextPage
    }
    objects {
    ... on Material {
    id
    name
    brand {
    id
    name
    }
    }
    }
    }
    }
  4. Autogenerate files

    Add a new script to your package.json to run the codegen tool.

    ./package.json
    {
    "name": "example",
    "version": "0.1.0",
    "scripts": {
    ...
    "codegen": "graphql-codegen --config codegen.ts"
    },

    And then run it:

    Terminal window
    bun run codegen
  5. Create a client

    Apollo provides a lot of tooling for GraphQL in TypeScript. We simply leverage their client & configure it as needed.

    ./ApolloClient.ts
    import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
    export const apolloClient = new ApolloClient({
    uri: "https://api.helioadditive.com/graphql",
    cache: new InMemoryCache(),
    link: new HttpLink({
    uri: "https://api.helioadditive.com/graphql",
    headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer <pat-token>" // The users PAT token should be dynamically inserted here
    },
    credentials: "include",
    fetchOptions: { cache: "no-store" },
    }),
    });
  6. Utilize the generated code

    In any application code, you now need only import the client and pass the automatic generated Document from a .generated.ts document.

    ./main.ts
    import { apolloClient } from "@/ApolloClient";
    import { MaterialsDocument } from "./queries/Materials.generated";
    // Construct a query
    const query = await apolloClient.query({
    query: MaterialsDocument,
    variables: {
    pageSize: 20,
    page: 1
    },
    fetchPolicy: "no-cache",
    });
    // The following is all strongly typed
    for (const material of materials.data.materials.objects) {
    console.log(`Material ID: ${material.id}, Name: ${material.name}`);
    }