Using GraphQL Code Generator with ChatBotKit's GraphQL API
Setting up GraphQL Code Generator with ChatBotKit's GraphQL API is straightforward and will dramatically improve your development experience by providing type-safe client code generation. This comprehensive tutorial will walk you through the entire process, including the crucial authentication setup required for ChatBotKit's protected endpoint.
Prerequisites
Before getting started, ensure you have:
- Node.js installed
- A ChatBotKit account with an API key
- Basic familiarity with TypeScript and GraphQL
Installation
First, install the necessary dependencies. GraphQL Code Generator has evolved significantly, and the modern approach uses the client preset for optimal type safety.
npm install graphql npm install -D typescript @graphql-codegen/cli @graphql-codegen/client-preset
The packages serve different purposes:
graphql
: The core GraphQL library@graphql-codegen/cli
: The command-line interface for code generation@graphql-codegen/client-preset
: The modern preset that generates type-safe operations
Configuration Setup
GraphQL Code Generator now uses a TypeScript configuration file instead of YAML, providing better type safety and IDE support.
Create Configuration File
Create a codegen.ts
file in your project root:
import { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: [ { 'https://api.chatbotkit.com/v1/graphql': { headers: { 'Authorization': `Bearer ${process.env.CHATBOTKIT_API_KEY}`, }, }, }, ], documents: ['src/**/*.{ts,tsx}', 'src/**/*.graphql'], generates: { './src/gql/': { preset: 'client', config: { useTypeImports: true, }, }, }, ignoreNoDocuments: true, } export default config
Important: ChatBotKit's GraphQL endpoint requires authentication headers to access the schema definitions This is intentionally designed this way because some customers may have custom GraphQL extensions that require proper authorization to access.
Environment Variables Setup
Create a .env
file in your project root to store your API credentials securely:
CHATBOTKIT_API_KEY=your_chatbotkit_api_key_here
This approach keeps sensitive credentials out of your source code while allowing the code generator to access them during the introspection process.
Package.json Scripts
Add the necessary scripts to your package.json
:
{ "scripts": { "codegen": "graphql-codegen -r dotenv/config", "codegen:watch": "graphql-codegen -r dotenv/config --watch", "predev": "npm run codegen", "dev": "your-dev-command" } }
The -r dotenv/config
flag preloads environment variables before running the code generator, ensuring your API key is available during schema introspection.
Writing GraphQL Operations
Before running the code generator, you need to define some GraphQL operations. Create your queries, mutations, or subscriptions in your TypeScript files or separate .graphql
files.
Example query in src/queries/chatbots.ts
:
import { graphql } from '../gql' export const GET_BOTS = graphql(` query GetChatbots { bots { id name description createdAt updatedAt } } `)
Running Code Generation
Execute the code generation process:
npm run codegen
The generator will:
- Connect to ChatBotKit's GraphQL endpoint using your Bearer token
- Introspect the schema to understand all available types and operations
- Analyze your GraphQL operations in the specified document files
- Generate type-safe TypeScript definitions in the
./src/gql/
directory
Generated Output
The client preset generates several important files:
./src/gql/graphql.ts
: Contains all GraphQL types and operation result types./src/gql/gql.ts
: Provides thegraphql
function for defining operations./src/gql/index.ts
: Main export file with utilities
Using Generated Types
After generation, you can use the type-safe operations in your application:
import { useQuery, useMutation } from '@apollo/client' import { GET_CHATBOTS } from './queries/chatbots' function ChatbotList() { const { data, loading, error } = useQuery(GET_CHATBOTS) if (loading) return <div>Loading...</div> if (error) return <div>Error: {error.message}</div> return ( <div> {data?.chatbots.map(chatbot => ( <div key={chatbot.id}> <h3>{chatbot.name}</h3> <p>{chatbot.description}</p> </div> ))} </div> ) }
Troubleshooting Common Issues
Authentication Failures
If you encounter authentication errors during schema introspection:
- Verify your API key is correct and has the necessary permissions
- Ensure the environment variable is properly loaded
- Check that the Authorization header format matches ChatBotKit's requirements
Missing Types
If generated types seem incomplete:
- Ensure all your GraphQL operations are in files matching the
documents
pattern - Verify that your operations are using the
graphql
function from the generated code - Check that the schema introspection was successful
Build Errors
If you encounter TypeScript errors after generation:
- Run
npm run codegen
to ensure you have the latest generated types - Check that your GraphQL operations match the schema exactly
- Verify that all required fields are included in your queries
Best Practices
- Version Control: Include generated files in version control to ensure consistency across team members and deployments.
- Environment Management: Use environment variables for API keys and endpoint URLs to support different environments (development, staging, production).
- Operation Organization: Group related GraphQL operations in logical files and folders for better maintainability.
- Type Safety: Take advantage of the generated types throughout your application to catch errors at compile time rather than runtime.
- Regular Updates: Run code generation regularly, especially after schema changes, to keep your types in sync with the API.
Conclusion
GraphQL Code Generator with ChatBotKit's API provides a robust foundation for building type-safe applications that can efficiently query and manipulate your chatbot resources. The authentication setup ensures secure access to the schema while enabling powerful development-time features like autocompletion and compile-time type checking.