npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

graphql-recursive-query-gen

v1.0.7

Published

A CLI tool that automatically generates GraphQL query/mutation files from GraphQL schemas

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

  • 🚀 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-gen

Local Installation

npm install graphql-recursive-query-gen

Using 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 saved
  • schemaPath: Path to schema source, can be:
    • A single .graphqls file
    • A directory containing .graphqls files
    • A glob pattern (e.g., **/*.graphqls)
    • An HTTP/HTTPS endpoint URL
  • withFragment: true or false - whether to generate fragment files
  • namePostfix: (Optional) Suffix to add to generated operation names
  • maxDepth: (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 postfix

Test 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 results

Sample Schemas

  1. 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)
  2. 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.js

This will create a simple schema, generate files, display the output, and clean up automatically.

Manual Testing

  1. Run the example script:

    cd examples
    ./run-example.sh
  2. Test with sample schema:

    node generate-graphql-files.cjs ./output examples/sample-schema.graphqls false
  3. Test with npm link:

    npm link
    gql-gen ./output examples/sample-schema.graphqls true
  4. Test 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 false

Generate from a directory

gql-gen ./generated ./schemas true

Generate from a glob pattern

gql-gen ./generated "src/**/*.graphqls" true

Generate from a remote endpoint

gql-gen ./generated https://api.example.com/graphql false

Generate with custom postfix

gql-gen ./generated ./schema.graphqls true "V2"

Generate with custom depth limit

gql-gen ./generated ./schema.graphqls false "" 3

Using 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.graphql

Fragment 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.graphql

Downloaded Schema (for remote endpoints)

When using a remote endpoint, the schema is downloaded and saved:

generated/
└── schema.graphqls

Generated 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 (.graphqls files)

Dependencies

  • graphql: GraphQL JavaScript implementation
  • globby: File system pattern matching
  • node-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.