graphql-recursive-query-gen
v1.0.7
Published
A CLI tool that automatically generates GraphQL query/mutation files from GraphQL schemas
Maintainers
Readme
graphql-recursive-query-gen
A powerful CLI tool that automatically generates GraphQL query, mutation, and subscription files from GraphQL schemas. It supports multiple schema sources including local files, directories, glob patterns, and remote endpoints.
Table of Contents
- Features
- Installation
- Usage
- Output Structure
- Generated File Examples
- Testing
- Advanced Features
- Requirements
- Contributing
- License
Features
- 🚀 Generate query/mutation/subscription files from GraphQL schemas
- 📡 Full subscription type support
- 📁 Support for multiple schema files (merge schemas)
- 🌐 Download schemas from remote GraphQL endpoints
- 🎯 Fragment generation support
- 🔍 Glob pattern support for schema discovery
- 📝 Customizable naming with postfix option
Installation
Global Installation
npm install -g graphql-recursive-query-genLocal Installation
npm install graphql-recursive-query-genUsing npx (without installation)
npx graphql-recursive-query-gen <outputDir> <schemaPath> <withFragment> [namePostfix] [maxDepth]Usage
Basic Command
# With global installation
gql-gen <outputDir> <schemaPath> <withFragment> [namePostfix] [maxDepth]
# With local installation
npx gql-gen <outputDir> <schemaPath> <withFragment> [namePostfix] [maxDepth]
# Using package.json scripts
"scripts": {
"generate": "gql-gen ./generated ./schema.graphqls true"
}Parameters
outputDir: Directory where generated files will be savedschemaPath: Path to schema source, can be:- A single
.graphqlsfile - A directory containing
.graphqlsfiles - A glob pattern (e.g.,
**/*.graphqls) - An HTTP/HTTPS endpoint URL
- A single
withFragment:trueorfalse- whether to generate fragment filesnamePostfix: (Optional) Suffix to add to generated operation namesmaxDepth: (Optional) Maximum nesting depth for query generation (default: 5)
Testing
Local Testing
The project includes a comprehensive test suite with sample schemas. To run the tests:
# Run all tests
npm test
# Or run specific tests
npm run test:basic # Test without fragments
npm run test:fragments # Test with fragments
npm run test:postfix # Test with custom postfixTest Structure
examples/
├── sample-schema.graphqls # Blog application schema
├── ecommerce-schema.graphqls # E-commerce schema with advanced features
└── multi-schema/ # Multiple schema files for testing
├── auth.graphqls # Authentication extensions
└── subscription.graphqls # Subscription types
test-output/ # Generated test outputs
├── basic/ # Basic generation results
├── fragments/ # Fragment generation results
├── postfix/ # Custom postfix results
└── multi-schema/ # Multi-schema merge resultsSample Schemas
Blog Schema (
examples/sample-schema.graphqls):- User management (CRUD operations)
- Post management with comments
- Social features (likes, followers)
- Real-time subscriptions (post created, comment added)
E-commerce Schema (
examples/ecommerce-schema.graphqls):- Product catalog with categories
- Shopping cart operations
- Order management
- Advanced features: unions, interfaces, custom scalars, enums
Quick Test
For a quick verification that everything is working:
# Make test scripts executable (first time only)
chmod +x test-local.sh quick-test.js examples/run-example.sh
# Run quick test
node quick-test.jsThis will create a simple schema, generate files, display the output, and clean up automatically.
Manual Testing
Run the example script:
cd examples ./run-example.shTest with sample schema:
node generate-graphql-files.cjs ./output examples/sample-schema.graphqls falseTest with npm link:
npm link gql-gen ./output examples/sample-schema.graphqls trueTest with remote endpoint:
# Replace with your GraphQL endpoint gql-gen ./output https://api.example.com/graphql false
Examples
Generate from a single schema file
gql-gen ./generated ./schema.graphqls falseGenerate from a directory
gql-gen ./generated ./schemas trueGenerate from a glob pattern
gql-gen ./generated "src/**/*.graphqls" trueGenerate from a remote endpoint
gql-gen ./generated https://api.example.com/graphql falseGenerate with custom postfix
gql-gen ./generated ./schema.graphqls true "V2"Generate with custom depth limit
gql-gen ./generated ./schema.graphqls false "" 3Using in npm scripts
{
"scripts": {
"generate:graphql": "gql-gen ./src/graphql ./schemas/*.graphqls true",
"generate:graphql:prod": "gql-gen ./src/graphql https://api.production.com/graphql false PROD"
}
}Programmatic usage with child_process
const { exec } = require('child_process');
exec('npx gql-gen ./output ./schema.graphqls true', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error}`);
return;
}
console.log('GraphQL files generated successfully');
});Output Structure
The tool generates the following files:
Query/Mutation/Subscription Files
For each query, mutation, and subscription field in your schema, a separate GraphQL file is created:
generated/
├── GetUser-query.graphql
├── GetUsers-query.graphql
├── CreateUser-mutation.graphql
├── UpdateUser-mutation.graphql
├── PostCreated-subscription.graphql
└── CommentAdded-subscription.graphqlFragment Files (when withFragment is true)
For each type in your schema, a fragment file is created:
generated/
├── User-fragment.graphql
├── Post-fragment.graphql
└── Comment-fragment.graphqlDownloaded Schema (for remote endpoints)
When using a remote endpoint, the schema is downloaded and saved:
generated/
└── schema.graphqlsGenerated File Examples
Query File Example
query GetUserV2(
$id: ID!
) {
getUser(
id: $id
) {
id
name
email
posts {
id
title
content
}
}
}Fragment File Example
fragment UserV2Fragment on User {
id
name
email
posts { ...PostV2Fragment }
}Subscription File Example
subscription PostCreated(
$userId: ID
) {
postCreated(
userId: $userId
) {
id
title
content
author {
id
username
}
}
}Advanced Features
Schema Merging
When multiple schema files are provided (via directory or glob pattern), the tool automatically merges them into a single schema before generation. This is useful for modular schema architectures.
Circular Reference Handling
Set withFragment to false if your schema contains circular references to avoid infinite loops in generated queries.
Depth Control
Control the maximum nesting depth of generated queries using the maxDepth parameter. This prevents excessively deep queries and improves performance:
- Default depth: 5 levels
- Prevents empty object generation when depth limit is reached
- Useful for deeply nested schemas or performance optimization
Custom Type Handling
The tool intelligently handles:
- Scalar types
- Enum types
- Input types
- Object types
- List types
- Non-null types
Requirements
- Node.js >= 18.0.0
- GraphQL schema in SDL format (
.graphqlsfiles)
Dependencies
graphql: GraphQL JavaScript implementationglobby: File system pattern matchingnode-fetch: HTTP client for downloading remote schemas
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
Support
If you encounter any issues or have questions, please file an issue on the GitHub repository.
Important Note
Make sure to add the shebang line #!/usr/bin/env node at the beginning of generate-graphql-files.cjs file for the CLI to work properly.
