跳转到内容

Code Generation

Our API uses GraphQL, which enables automatic code generation to work with our services as if it were part of your application itself. Below are examples for different programming languages.

1. Start a new project and install dependencies

Section titled “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

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;

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
}
}
}
}
}

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
./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}`);
}