I am new to using GraphQl but I am quite accustomed to using other API mediums such as REST and gRPC. I am creating an E-commerce Shopify storefront with Next.js and Shopfy's API is all in GraphQL. When I create my query and request it, I get my desired response however, when I try and do anything with the data, TypeScript gets upset as it does not know the type of the returned data. I want to be able to type the returned data.
I thought about just creating an interface for the returned type but that seemed to be very unproductive, especially as my project scales.
I read about using codegen which, I think, generates the types and interfaces based on the created queries. Shopify has a GitHub repo for this here but I've tried using their example code and the codegen is unable to find or get access to the graphQL schema on Shopifys backend. (I could be wrong about this but the codegen error code is capped at 20 or so characters so I don't know what is going wrong).
Generating the types for GraphQL responses is possible but everywhere I look, I feel like I am doing something wrong.
Try this:
// Install dependencies
// npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-resolvers
On codegen root file:
import type { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
overwrite: true,
generates: {
'graphql/generated/storefront.ts': {
schema: 'https://shopify.dev/storefront-graphql-direct-proxy/2024-10',
documents: 'graphql/storefront/**/*.graphql', // if you want to use .ts files, just check the graphql-codegen docs
plugins: [
'typescript',
'typescript-resolvers',
'typescript-operations',
],
config: {
nonOptionalTypename: true,
legacyMode: false,
pureMagicComment: true,
dedupeFragments: true,
},
},
},
};
export default config;