Code Generation
Overview
Code generation tools untuk frontend development, khususnya untuk generate TypeScript code dari OpenAPI specification. Menggunakan Kubb sebagai main code generator dengan custom filtering dan configuration.
Komponen
Filter OpenAPI
Script untuk filtering OpenAPI specification sebelum di-generate. Berguna untuk:
- Memilih endpoint tertentu yang akan di-generate
- Menghapus schema yang tidak diperlukan
- Optimasi ukuran generated code
- Custom transformation OpenAPI spec
File: filter-openapi.mjs
// Contoh filtering endpoint tertentu
const filteredPaths = Object.keys(openapi.paths).filter(path =>
path.startsWith('/api/v1')
);
Kubb Configuration
Konfigurasi lengkap untuk Kubb code generator:
- Generate TypeScript types dari OpenAPI schemas
- Generate React Query hooks untuk API calls
- Kustomisasi output directory dan file naming
- Plugin configuration untuk berbagai format output
File: kubb.config.ts
import { defineConfig } from '@kubb/core'
import { pluginOas } from '@kubb/plugin-oas'
import { pluginReactQuery } from '@kubb/plugin-react-query'
export default defineConfig({
input: {
path: './openapi.json',
},
output: {
path: './src/gen',
clean: true,
},
plugins: [
pluginOas(),
pluginReactQuery({
output: {
path: './hooks',
},
}),
],
})
Workflow
1. Download OpenAPI Spec
# Download dari remote server
curl https://api.example.com/openapi.json -o openapi.json
2. Filter Specification (Optional)
# Jalankan filter script
node filter-openapi.mjs
3. Generate Code
# Generate types dan hooks
npx kubb generate
4. Import Generated Code
// Import types
import type { User, UserResponse } from '@/gen/types'
// Import hooks
import { useGetUsers, useCreateUser } from '@/gen/hooks'
// Gunakan di component
function UserList() {
const { data, isLoading } = useGetUsers()
if (isLoading) return <div>Loading...</div>
return (
<ul>
{data?.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)
}
Benefits
Type Safety
- Automatic TypeScript types dari OpenAPI schema
- IntelliSense support di IDE
- Compile-time error detection
- Consistent types antara backend dan frontend
Development Speed
- No manual API client writing
- Auto-generated React Query hooks
- Ready-to-use CRUD operations
- Consistent naming convention
Maintainability
- Single source of truth (OpenAPI spec)
- Easy to update saat API changes
- Automated regeneration
- Reduced human error
Best Practices
1. Version Control
# Jangan commit generated code
echo "src/gen/" >> .gitignore
# Commit configuration files
git add kubb.config.ts filter-openapi.mjs
2. CI/CD Integration
# .github/workflows/generate-api.yml
name: Generate API Client
on:
push:
branches: [main]
jobs:
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
- name: Install dependencies
run: npm install
- name: Generate API client
run: npm run generate:api
3. Pre-commit Hook
// package.json
{
"scripts": {
"generate:api": "node filter-openapi.mjs && npx kubb generate",
"prepare": "husky install"
},
"husky": {
"hooks": {
"pre-commit": "npm run generate:api"
}
}
}
4. Documentation
/**
* Generated API hooks dari OpenAPI specification
*
* @see {@link https://api.example.com/docs} API Documentation
* @generated Last generated: 2025-11-05
*/
export * from './hooks'
export * from './types'
Troubleshooting
Generate Failed
Problem: Kubb generate error atau crash
Solution:
# Clear cache
rm -rf node_modules/.cache
# Reinstall dependencies
npm install
# Try generate again
npx kubb generate
Type Mismatch
Problem: Generated types tidak match dengan API response
Solution:
# Update OpenAPI spec
curl https://api.example.com/openapi.json -o openapi.json
# Regenerate
npm run generate:api
Missing Endpoints
Problem: Beberapa endpoint tidak ter-generate
Solution:
// Check filter-openapi.mjs
// Pastikan endpoint tidak ter-filter
// Atau disable filtering sementara
// const filteredPaths = openapi.paths; // Include all
Related Topics
- React Query Documentation
- OpenAPI Specification
- TypeScript Handbook
- Custom Hooks - Hooks yang menggunakan generated code
Technology Stack: Kubb, OpenAPI, TypeScript, React Query
Use Case: API client generation, Type safety, Development automation
Last Updated: November 2025