Skip to content

Typescript example using our API

Our API uses GraphQL, below is an example of how to leverage GraphQL’s automatic code generation to work with our services as if it were part of your application itself.

  1. Start a new project and install dependencies

    #!/bin/bash
    mkdir example && cd example
    bun init
    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. Utilize the generated code

    ./main.ts
    import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
    import { MaterialsDocument } from "./queries/Materials.generated";
    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>"
    },
    credentials: "include",
    fetchOptions: { cache: "no-store" },
    }),
    });
    const query = await apolloClient.query({
    query: MaterialsDocument,
    variables: {
    pageSize: 20,
    page: 1
    },
    fetchPolicy: "no-cache",
    });
    for (const material of materials.data.materials.objects) {
    console.log(`Material ID: ${material.id}, Name: ${material.name}`);
    }