2.2.5 • Published 1 year ago

json-to-graphql-query v2.2.5

Weekly downloads
10,915
License
MIT
Repository
github
Last release
1 year ago

json-to-graphql-query

This is a simple module that takes a JavaScript object and turns it into a GraphQL query to be sent to a GraphQL server.

Mainly useful for applications that need to generate graphql queries dynamically.

New Maintainer!

Huge thanks to @vkolgi for agreeing to take over maintenance of this library! I look forward to following its continued development. - @dupski

Installation

npm install json-to-graphql-query

Usage

const query = jsonToGraphQLQuery(queryObject: object, options?: object);

Supported Options:

  • pretty - boolean - optional - set to true to enable pretty-printed output
  • ignoreFields - string[] - optional - you can pass an array of object key names that you want removed from the query
  • includeFalsyKeys - boolean - optional - disable the default behaviour if excluding keys with a falsy value

Features

  • Converts a JavaScript object to a GraphQL Query string
  • Full support for nested query / mutation nodes and arguments
  • Optionally strip specific object keys using the ignoreFields option
  • Support for input arguments via __args
  • Support for query aliases via __aliasFor
  • Support for Enum values via EnumType
  • Support for variables via __variables
  • Support for simple directives (such as @client) via __directives
  • Support for one or more inline fragments via __on.__typeName
  • Support for full fragments via __all_on
  • Support for named queries/mutations via __name

Recent Changes

See the CHANGELOG

Simple Query

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
    query: {
        Posts: {
            id: true,
            title: true,
            post_date: true
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts {
        id
        title
        post_date
    }
}

Query with arguments

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
    query: {
        Posts: {
            __args: {
                where: { id: 2 }
                orderBy: 'post_date'
            },
            id: true,
            title: true,
            post_date: true
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts (where: {id: 2}, orderBy: "post_date") {
        id
        title
        post_date
    }
}

Query with nested objects

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
    query: {
        Posts: {
            id: true,
            title: true,
            comments: {
                id: true,
                comment: true,
                user: true
            }
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts {
        id
        title
        comments {
            id
            comment
            user
        }
    }
}

Query with disabled fields

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
    query: {
        Posts: {
            id: true,
            title: false,
            comments: {
                id: true,
                comment: false,
                user: true
            }
        },
        User: false
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts {
        id
        comments {
            id
            user
        }
    }
}

NOTE: You can tell jsonToGraphQLQuery() not to exclude keys with a falsy value by setting the includeFalsyKeys option.

Using aliases

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
    query: {
        allPosts: {
            __aliasFor: 'Posts',
            id: true,
            comments: {
                id: true,
                comment: true
            }
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    allPosts: Posts {
        id
        comments {
            id
            comment
        }
    }
}

Query with Enum Values

import { jsonToGraphQLQuery, EnumType } from 'json-to-graphql-query';

const query = {
    query: {
        Posts: {
            __args: {
                orderBy: 'post_date',
                status: new EnumType('PUBLISHED')
            },
            title: true,
            body: true
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts (orderBy: "post_date", status: PUBLISHED) {
        title
        body
    }
}

Query with variables

import { jsonToGraphQLQuery, VariableType } from 'json-to-graphql-query';

const query = {
    query: {
        __variables: {
            variable1: 'String!',
            variableWithDefault: 'String = "default_value"'
        },
        Posts: {
            __args: {
                arg1: 20,
                arg2: new VariableType('variable1')
            },
            id: true,
            title: true
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query ($variable1: String!, $variableWithDefault: String = "default_value") {
    Posts (arg1: 20, arg2: $variable1) {
        id
        title
    }
}

Query with Directives

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
    query: {
        __directives: {
            client: true
        }
        Posts: {
            id: true,
            title: true,
            post_date: true
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts @client {
        id
        title
        post_date
    }
}

Ignoring fields in the query object

We sometimes want to ignore specific fields in the initial object, for instance __typename in Apollo queries. You can specify these fields using the ignoreFields option:

import { jsonToGraphQLQuery, VariableType } from 'json-to-graphql-query';

const query = {
    query: {
        Posts: {
            shouldBeIgnored: {
                variable1: 'a value'
            },
            id: true,
            title: true,
            post_date: true
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, {
    pretty: true,
    ignoreFields: ['shouldBeIgnored']
});

Resulting graphql_query

query {
    Posts {
        id
        title
        post_date
    }
}

Query with Inline Fragments

Full inline fragments

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
    query: {
        Posts: {
            title: true,
            __all_on: [
                "ConfigurablePost",
                "PageInfo"
            ]
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts {
        title
        ...ConfigurablePost
        ...PageInfo
    }
}

Partial inline fragments

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
    query: {
        Posts: {
            title: true,
            __on: {
                __typeName: "ConfigurablePost",
                id: true
            }
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts {
        title
        ... on ConfigurablePost {
            id
        }
    }
}

Query with multiple Inline Fragments

import { jsonToGraphQLQuery } from 'json-to-graphql-query';

const query = {
            query: {
                Posts: {
                    __on: [
                    {
                        __typeName: "ConfigurablePost",
                        id: true
                    },
                    {
                        __typeName: "UnconfigurablePost",
                        name: true
                    }]
                }
            }
        };
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query {
    Posts {
        title
        ... on ConfigurablePost {
            id
        }
        ... on UnconfigurablePost {
            name
        }
    }
}

Query with name

import { jsonToGraphQLQuery, VariableType } from 'json-to-graphql-query';

const query = {
    query: {
        __name: 'NewName',
        __variables: {
            variable1: 'String!',
            variableWithDefault: 'String = "default_value"'
        },
        Posts: {
            __args: {
                arg1: 20,
                arg2: new VariableType('variable1')
            },
            id: true,
            title: true
        }
    }
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });

Resulting graphql_query

query NewName ($variable1: String!, $variableWithDefault: String = "default_value") {
    Posts (arg1: 20, arg2: $variable1) {
        id
        title
    }
}

Mutation example

import { jsonToGraphQLQuery, VariableType } from 'json-to-graphql-query';

const mutation = {
    mutation: {
        delete_post: {
            __args: { id: 1234 },
            id: true,
        }
    }
};
const graphql_query = jsonToGraphQLQuery(mutation, { pretty: true });

Resulting graphql_query

mutation {
    delete_post (id: 1234) {
            id
    }
}

TO-DO List

  • Probably some other things!...

Pull requests welcome!

License

MIT

@balancer-labs/sdk@kaviar/x-ui@skulpture/lynkfaros-canonical-reportsgally-admin-shared@infinitebrahmanuniverse/nolb-json-tgraphcms-js@everything-registry/sub-chunk-1986graphql-group-resolvegraphql-snapshotgithub-gql-paginatorgraphql-query-to-jsongraphql-query-vars-cleanergql-agentgql-paginatorhecovote.jsheylala2021vni-link-files-api@betacodd/checkpoint-test@appkitio/appkit-db-builder@auroblocks/chimp-sdk@cedric_showsourcing/showsourcing-frontend-api@bluelibs/x-ui-collections-bundle@beepsoft/hamster@brunolemos/devhub-core@boardroom/base@arrowsphere/api-client@autoinvent/magql-query@crystallize/import-utilities@crystallize/js-api-client@dab-labs/dab.js@colligence/balancer-sdk@colligence/sdk@cromwell/admin-panel@dosvit/server-toolkit@dosvit/api-gateway@defiverse/balancer-sdk@elastic-suite/gally-admin-shared@hongochai/snapshot.js@harmonyjs/query@hostlink/light@hostlink/nuxt-light@foundationjs/query@halodao/balancer-sdk@halodao/dapp-kit@halborn-labs/snapshot.js@jelly-verse/sdk@xclabs/xave-dapp-kitdrepute-privateesp-common-uifaros-js-clientnft-did-resolvermsnapshot.jsra-strapi-v4-graphqlquasar-ui-json-logic-formsafe-did-resolverreplit-graphql-apirev-api-clientrep3-strategiesrep3-strategyrocketblocks-reactshowsourcing-api-libshopify-ormtest-vite-ui-kittypegraphunigraph-dev-commonstar-automated-teststrategies-testskytale-liquidity-poolssnapshot-sdksnapshot-whale.jssnapshot-js-cwssblocks.jstreeormuser-interactions-handlervue-blocklinkwayfair@aacassandra/graphql-query-to-json@adobe/commerce-cif-graphql@adobe/commerce-cif-magento-graphql@0xcryptodev/sdk@0xcryptodev/sdk-tenet@antiyro/checkpoint_2.0@alorel-personal/build-tools@leafwell/client-store@leafwell/content-blog@kolektivo-labs/refi-sdk@kolektivo-labs/sdk@lenne.tech/nest-server@iguana-dex/sdk@ilink-dev/common@mathsgod/vue-gql@prophouse/offchain-strategies@pulsex/snapshot.js@reactive-resource/reactive-resource-apollo-connector@reinis_frp/snapshot.js@premia/v3-sdk@momentranks/snapshot.js@morethingsdigital/statamic-api@metlo/testing
2.2.5

1 year ago

2.2.4

2 years ago

2.2.3

2 years ago

2.2.0

2 years ago

2.2.2

2 years ago

2.1.0

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

4 years ago

1.9.0

6 years ago

1.8.0

6 years ago

1.7.0

6 years ago

1.6.0

6 years ago

1.5.0

6 years ago

1.4.0

6 years ago

1.3.0

6 years ago

1.2.0

6 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.0

6 years ago

0.2.0

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago