gql-ts-gen v1.0.1
GraphQL TypeScript Generator (gql-ts-gen)
A powerful CLI tool to generate TypeScript types, resolvers, mutators, and implementation stubs from GraphQL schemas.
Features
- Complete Code Generation: Generate all necessary TypeScript files from your GraphQL schema in one command
- Type-Safe Development: Enjoy fully typed GraphQL resolvers and mutators
- Custom Implementation Support: Generated implementations preserve custom logic during schema changes
- Automatic Updates: Regenerate code when schema changes while preserving custom implementations
- Schema-First Development: Start with your GraphQL schema and let the tool handle the rest
Installation
Global Installation
# Install globally
npm install -g gql-ts-gen
# Or with a shorter command if installing from local repository:
npm install -g .
After installation, you can use the tool globally with:
# Full command
gql-ts-gen --schema "./schema/**/*.gql" --output "./src/generated"
# Or using the shorter alias
gtgen --schema "./schema/**/*.gql" --output "./src/generated"
Project Installation
# Install as a dev dependency in your project
npm install --save-dev gql-ts-gen
# Add to your package.json scripts
"scripts": {
"generate:all": "gql-ts-gen generate --schema ./schema --output ./src/generated"
}
# Run using npm
npm run generate:all
Using with npx
# Run directly with npx without installing
npx gql-ts-gen generate --schema ./schema --output ./src/generated
Quick Start
- Initialize your project structure:
mkdir -p schema
- Define your GraphQL schema:
Create .gql
files in the ./schema
directory:
# schema/types.gql
type User {
id: ID!
name: String!
email: String!
}
# schema/queries.gql
type Query {
user(id: ID!): User
users: [User!]!
}
# schema/mutations.gql
type Mutation {
createUser(name: String!, email: String!): User!
updateUser(id: ID!, name: String, email: String): User
deleteUser(id: ID!): Boolean!
}
- Configure your context:
Create a context file for your GraphQL resolvers:
// src/context.ts
export interface Context {
userId?: string;
isAuthenticated: boolean;
// Add your custom context properties here
}
export const createContext = (options?: Partial<Context>): Context => {
return {
isAuthenticated: false,
...options
};
};
Set up your tsconfig.json
to map the @gql-ts-gen/context
path:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@gql-ts-gen/context": ["./src/context"]
}
}
}
- Generate all the code:
gql-ts-gen generate
- Implement your custom logic:
Edit the generated implementation files in src/generated/implementations
directory.
- Use the generated code in your application:
import { resolvers } from './src/generated/resolvers';
import { typeDefs } from './src/generated/schema.gql';
import { ApolloServer } from '@apollo/server';
import { createContext } from '@gql-ts-gen/context';
const server = new ApolloServer({
typeDefs,
resolvers,
});
// Start your server with your context
const { url } = await startStandaloneServer(server, {
context: async () => createContext({
isAuthenticated: true,
userId: 'user-123'
})
});
Directory Structure
After setup, your project will have the following structure:
your-project/
├── schema/ # GraphQL schema files (.gql)
│ ├── types.gql
│ ├── queries.gql
│ ├── mutations.gql
│ └── ...
├── src/
│ ├── context.ts # Your custom Context implementation
│ ├── generated/ # Generated files (do not edit directly)
│ │ ├── graphql.ts # Generated TypeScript types
│ │ ├── schema.gql # Merged schema
│ │ ├── types.ts # Generated types
│ │ ├── resolvers/ # Generated resolver stubs
│ │ ├── mutators/ # Generated mutator stubs
│ │ └── implementations/ # Implementation files that you can edit
│ │ ├── resolvers/ # Custom resolver implementations
│ │ └── mutators/ # Custom mutator implementations
│ └── ...
├── tsconfig.json # TypeScript configuration with path mapping
├── package.json
└── ...
Command Line Options
gql-ts-gen generate [options]
Options:
--schema <glob>
: GraphQL schema files glob pattern (default:./schema/**/*.gql
)--output <dir>
: Output directory for generated files (default:./src/generated
)--force
: Force overwrite of existing files (default:false
)--skip-codegen
: Skip running GraphQL codegen (default:false
)--skip-obsolete-check
: Skip marking obsolete implementation files (default:false
)--context <path>
: Path to a custom Context interface file--context-name <name>
: Name of the Context interface (default:Context
)
Context Configuration
Default Approach
When no --context
path is specified, the tool uses @gql-ts-gen/context
as an import alias in all generated files. You must:
- Create your own Context interface implementation
- Configure your tsconfig.json with the path mapping:
"paths": { "@gql-ts-gen/context": ["./path/to/your/context"] }
Custom Context Approach
For more advanced applications, you can specify your own Context interface:
# Generate code with a custom Context interface
gql-ts-gen generate --context ./src/context/MyContext.ts --context-name MyContext
# Using an alias path
gql-ts-gen generate --context @/contexts/MyContext --context-name MyContext
This will: 1. Use your custom Context interface in the generated code 2. Configure all generated files to import your Context directly from the provided path 3. Support both relative paths (./path/to/context) and alias paths (@/path/to/context)
Example of a custom Context file (./src/context/MyContext.ts
):
export interface MyContext {
userId: string;
isAuthenticated: boolean;
dataSources: {
users: UserDataSource;
products: ProductDataSource;
};
services: {
auth: AuthService;
logger: LoggerService;
};
}
Using as a Module
You can also use individual components of the package by importing them directly:
// Import the entire package
import graphqlGen from 'gql-ts-gen';
// Or import specific features
import { generateTypes } from 'gql-ts-gen/types';
import { generateResolvers } from 'gql-ts-gen/resolvers';
import { generateMutators } from 'gql-ts-gen/mutators';
import { generateImplementations } from 'gql-ts-gen/implementations';
// Example usage:
generateTypes({
schema: './schema/**/*.gql',
output: './src/generated'
});
Schema Changes and Code Regeneration
One of the key features of this tool is that it preserves your custom implementations when you regenerate code after schema changes:
- Adding new fields or mutations: New stubs will be generated, existing implementations will be preserved
- Removing fields or mutations: Existing implementations will remain available for reference
- Modifying field types: Implementations will be preserved, but you may need to update your code to match the new types
Obsolete Implementation Marking
When you remove fields or mutations from your GraphQL schema, the implementation files for those removed definitions will be automatically marked as obsolete:
- A clear comment
This file is unused.
will be added at the top of the file - The original code will be preserved but commented out
- Additional information is provided indicating why the file is marked as obsolete
This feature helps you identify implementations that are no longer needed, allowing you to:
- Easily see which files are obsolete when browsing your codebase
- Safely delete obsolete files at your convenience
- Preserve the implementation code for reference or future use
You can disable this feature by using the --skip-obsolete-check
flag:
gql-ts-gen generate --skip-obsolete-check
Advanced Usage
Custom Templates
You can customize code generation by providing your own templates:
- Create a
templates
directory in your project - Add template files (e.g.,
resolver.ts.template
,mutator.ts.template
,implementation.ts.template
) - Run the generator with your custom templates
Integration with GraphQL Code Generator
This tool is built on top of GraphQL Code Generator and extends its functionality. You can use a custom codegen.ts
configuration file to customize the generated types.
License
MIT License - see LICENSE file for details.
Acknowledgements
This project was built with: