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 🙏

© 2024 – Pkg Stats / Ryan Hefner

graphql-query-crafter

v1.0.2

Published

A flexible and chainable API for building GraphQL queries and mutations in JavaScript/TypeScript.

Downloads

172

Readme

GraphQL Query Crafter

graphql-query-crafter is a flexible and chainable API for building GraphQL queries and mutations in JavaScript/TypeScript. This package allows you to dynamically construct complex GraphQL queries and mutations with support for nested fields, arguments, aliases, and more.

Features

  • Chainable API: Build queries and mutations using a fluent, chainable API.
  • Support for Nested Fields: Easily create nested structures in your queries and mutations.
  • Arguments and Aliases: Add arguments and aliases to fields with minimal effort.
  • TypeScript Support: Fully typed for enhanced development experience in TypeScript.

Installation

You can install graphql-query-crafter via NPM:

npm install graphql-query-crafter

Or with Yarn:

yarn add graphql-query-crafter

Usage

Basic Query Example

Here’s a simple example of how to use the GraphQLQueryCrafter to create a basic query:

import { GraphQLQueryCrafter } from 'graphql-query-crafter';

const builder = new GraphQLQueryCrafter();

const query = builder
  .start('query', 'getUser')
  .nestedField(
    'user',
    (userBuilder) => {
      userBuilder.field('id').field('name');
    },
    { id: 1 },
  ) // Provide an argument to specify the user ID
  .end();

console.log(query);

Output:

query getUser {
  user(id: 1) {
    id
    name
  }
}

Complex Query Example

For more advanced use cases, you can build complex queries with nested fields, arguments, and aliases:

import { GraphQLQueryCrafter } from 'graphql-query-crafter';

const builder = new GraphQLQueryCrafter();

const query = builder
  .start('query', 'getUserWithPosts')
  .nestedField(
    'user',
    (userBuilder) => {
      userBuilder
        .field('id')
        .field('name')
        .nestedField('profile', (profileBuilder) => {
          profileBuilder.field('age').field('bio');
        })
        .nestedField(
          'posts',
          (postsBuilder) => {
            postsBuilder
              .field('id')
              .field('title')
              .nestedField('comments', (commentsBuilder) => {
                commentsBuilder.field('id').field('content').field('author');
              });
          },
          { first: 5 },
        );
    },
    { id: 1 },
  )
  .end();

console.log(query);

Output:

query getUserWithPosts {
  user(id: 1) {
    id
    name
    profile {
      age
      bio
    }
    posts(first: 5) {
      id
      title
      comments {
        id
        content
        author
      }
    }
  }
}

Complex Mutation Example

You can also use GraphQLQueryCrafter to construct complex mutations. Here’s an example:

import { GraphQLQueryCrafter } from 'graphql-query-crafter';

const builder = new GraphQLQueryCrafter();

const mutation = builder
  .start('mutation', 'createUserWithPost')
  .nestedField(
    'createUser',
    (userBuilder) => {
      userBuilder
        .field('id')
        .field('name')
        .nestedField('profile', (profileBuilder) => {
          profileBuilder.field('age').field('bio');
        })
        .nestedField(
          'posts',
          (postsBuilder) => {
            postsBuilder
              .field('id')
              .field('title')
              .field('content')
              .nestedField('comments', (commentsBuilder) => {
                commentsBuilder.field('id').field('content').field('author');
              });
          },
          {
            input: {
              title: 'My First Post',
              content: 'This is the content of my first post.',
            },
          },
        );
    },
    {
      input: {
        name: 'John Doe',
        profile: { age: 30, bio: 'Software Developer' },
      },
    },
  )
  .end();

console.log(mutation);

Output:

mutation createUserWithPost {
  createUser(input: { "name": "John Doe", "profile": { "age": 30, "bio": "Software Developer" } }) {
    id
    name
    profile {
      age
      bio
    }
    posts(input: { "title": "My First Post", "content": "This is the content of my first post." }) {
      id
      title
      content
      comments {
        id
        content
        author
      }
    }
  }
}

Explanation

  • Chainable API: The methods start, field, nestedField, and end can be chained together to build complex queries and mutations.
  • Nested Fields: Easily handle nested structures within your GraphQL queries and mutations.
  • Arguments and Aliases: Pass arguments to fields and create aliases with minimal effort.

API Reference

start(type: 'query' | 'mutation', name?: string)

  • type: Specifies whether to start a query or mutation.
  • name: (Optional) The name of the query or mutation.

field(name: string, args?: Record<string, any>, alias?: string)

  • name: The field name.
  • args: (Optional) A record of arguments to pass to the field.
  • alias: (Optional) An alias for the field.

nestedField(name: string, subFields: (builder: GraphQLQueryCrafter) => void, args?: Record<string, any>, alias?: string)

  • name: The name of the nested field.
  • subFields: A callback function to define the nested fields.
  • args: (Optional) A record of arguments to pass to the nested field.
  • alias: (Optional) An alias for the nested field.

end()

  • Finalizes the query or mutation and returns it as a string.

Contributing

Contributions are welcome! If you have ideas for new features or improvements, feel free to open an issue or submit a pull request.

Steps to Contribute

  1. Fork the repository.
  2. Create a new branch for your feature or fix.
  3. Implement your changes and add tests.
  4. Ensure all tests pass (npm test).
  5. Submit a pull request.

License

This package is licensed under the MIT License. See the LICENSE file for more details.

Author

Created and maintained by Dipak Ahirav.

Support

If you encounter any issues or have questions about using graphql-query-crafter, feel free to open an issue on GitHub.

Links

Changelog

All notable changes to this project will be documented in the CHANGELOG.md.


Conclusion

The graphql-query-crafter package provides a flexible, powerful way to dynamically build GraphQL queries and mutations in your JavaScript/TypeScript applications. Its chainable API and support for complex nested structures make it an invaluable tool for developers working with GraphQL. Try it out today and simplify your GraphQL query construction!

Happy coding!