GraphQL Query Builder

Generate GraphQL queries using plain JavaScript Objects (JSON)

README

GraphQL Query Builder


A simple helper function to generate GraphQL queries using plain JavaScript Objects (JSON).

downloads

demo

Install


npm install gql-query-builder --save or yarn add gql-query-builder

Usage


  1. ```typescript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query(options: object)
  4. const mutation = gql.mutation(options: object)
  5. const subscription = gql.subscription(options: object)
  6. ```

You can also import query or mutation or subscription individually:

  1. ```typescript
  2. import  { query, mutation, subscription } from 'gql-query-builder'

  3. query(options: object)
  4. mutation(options: object)
  5. subscription(options: object)
  6. ```

Options


options is { operation, fields, variables } or an array of options

Name Description Type Required Example
operation Name of operation to be executed on server String | Object Yes getThoughts, createThought

{ name: 'getUser', alias: 'getAdminUser' }
fields Selection of fields Array No ['id', 'name', 'thought']

['id', 'name', 'thought', { user: ['id', 'email'] }]
variables Variables sent to the operation Object No { key: value } eg: { id: 1 }

{ key: { value: value, required: true, type: GQL type, list: true, name: argument name } eg:

{

email: { value: "user@example.com", required: true },

password: { value: "123456", required: true },

secondaryEmails: { value: [], required: false, type: 'String', list: true, name: secondaryEmail }

}


Adapter


An optional second argument adapter is a typescript/javascript class that implements src/adapters/IQueryAdapter or src/adapters/IMutationAdapter.

If adapter is undefined then src/adapters/DefaultQueryAdapter or src/adapters/DefaultMutationAdapter is used.

  1. ```
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query(options: object, adapter?: MyCustomQueryAdapter,config?: object)
  4. const mutation = gql.mutation(options: object, adapter?: MyCustomQueryAdapter)
  5. const subscription = gql.subscription(options: object, adapter?: MyCustomSubscriptionAdapter)
  6. ```

Config



Name Description Type Required Example
operationName Name of operation to be sent to the server String No getThoughts, createThought

Examples


1. Query2. Query (with variables)3. Query (with nested fields selection)4. Query (with required variables)5. Query (with custom argument name)6. Query (with operation name)7. Query (with empty fields)8. Query (with alias)9. Query (with adapter defined)10. Mutation11. Mutation (with required variables)12. Mutation (with custom types)13. Mutation (with adapter defined)14. Mutation (with operation name)15. Subscription16. Subscription (with adapter defined)17. Example with Axios

Query:


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query({
  4.   operation: 'thoughts',
  5.   fields: ['id', 'name', 'thought']
  6. })

  7. console.log(query)

  8. // Output
  9. query {
  10.   thoughts {
  11.     id,
  12.     name,
  13.     thought
  14.   }
  15. }
  16. ```


Query (with variables):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query({
  4.   operation: 'thought',
  5.   variables: { id: 1 },
  6.   fields: ['id', 'name', 'thought']
  7. })

  8. console.log(query)

  9. // Output
  10. query ($id: Int) {
  11.   thought (id: $id) {
  12.     id, name, thought
  13.   }
  14. }

  15. // Variables
  16. { "id": 1 }
  17. ```


Query (with nested fields selection):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql({
  4.   operation: 'orders',
  5.   fields: [
  6.     'id',
  7.     'amount',
  8.     {
  9.      user: [
  10.         'id',
  11.         'name',
  12.         'email',
  13.         {
  14.           address: [
  15.             'city',
  16.             'country'
  17.           ]
  18.         }
  19.       ]
  20.     }
  21.   ]
  22. })

  23. console.log(query)

  24. // Output
  25. query {
  26.   orders  {
  27.     id,
  28.     amount,
  29.     user {
  30.       id,
  31.       name,
  32.       email,
  33.       address {
  34.         city,
  35.         country
  36.       }
  37.     }
  38.   }
  39. }
  40. ```


Query (with required variables):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query({
  4.   operation: 'userLogin',
  5.   variables: {
  6.     email: { value: 'jon.doe@example.com', required: true },
  7.     password: { value: '123456', required: true }
  8.   },
  9.   fields: ['userId', 'token']
  10. })

  11. console.log(query)

  12. // Output
  13. query ($email: String!, $password: String!) {
  14.   userLogin (email: $email, password: $password) {
  15.     userId, token
  16.   }
  17. }

  18. // Variables
  19. {
  20.   email: "jon.doe@example.com",
  21.   password: "123456"
  22. }
  23. ```


Query (with custom argument name):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query([{
  4.   operation: "someoperation",
  5.   fields: [{
  6.     operation: "nestedoperation",
  7.     fields: ["field1"],
  8.     variables: {
  9.       id2: {
  10.         name: "id",
  11.         type: "ID",
  12.         value: 123,
  13.       },
  14.     },
  15.   }, ],
  16.   variables: {
  17.     id1: {
  18.       name: "id",
  19.       type: "ID",
  20.       value: 456,
  21.     },
  22.   },
  23. }, ]);

  24. console.log(query)

  25. // Output
  26. query($id2: ID, $id1: ID) {
  27.   someoperation(id: $id1) {
  28.     nestedoperation(id: $id2) {
  29.       field1
  30.     }
  31.   }
  32. }

  33. // Variables
  34. {
  35.   "id1": 1,
  36.   "id2": 1
  37. }
  38. ```


Query (with operation name):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query({
  4.   operation: 'userLogin',
  5.   fields: ['userId', 'token']
  6. }, null, {
  7.   operationName: 'someoperation'
  8. })

  9. console.log(query)

  10. // Output
  11. query someoperation {
  12.   userLogin {
  13.     userId
  14.     token
  15.   }
  16. }
  17. ```


Query (with empty fields):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query([{
  4.   operation: "getFilteredUsersCount",
  5. },
  6.   {
  7.     operation: "getAllUsersCount",
  8.     fields: []
  9.   },
  10.   operation: "getFilteredUsers",
  11.   fields: [{
  12.   count: [],
  13. }, ],
  14. ]);

  15. console.log(query)

  16. // Output
  17. query {
  18.   getFilteredUsersCount
  19.   getAllUsersCount
  20.   getFilteredUsers {
  21.     count
  22.   }
  23. }
  24. ```


Query (with alias):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query({
  4.   operation: {
  5.     name: 'thoughts',
  6.     alias: 'myThoughts',
  7.   },
  8.   fields: ['id', 'name', 'thought']
  9. })

  10. console.log(query)

  11. // Output
  12. query {
  13.   myThoughts: thoughts {
  14.     id,
  15.     name,
  16.     thought
  17.   }
  18. }
  19. ```


Query (with inline fragment):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.query({
  4.     operation: "thought",
  5.     fields: [
  6.         "id",
  7.         "name",
  8.         "thought",
  9.         {
  10.             operation: "FragmentType",
  11.             fields: ["emotion"],
  12.             fragment: true,
  13.         },
  14.     ],
  15. });

  16. console.log(query)

  17. // Output
  18. query {
  19.     thought {
  20.         id,
  21.         name,
  22.         thought,
  23.         ... on FragmentType {
  24.             emotion
  25.         }
  26.     }
  27. }
  28. ```


Query (with adapter defined):


For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

  1. ```javascript
  2. import * as gql from 'gql-query-builder'
  3. import MyQueryAdapter from 'where/adapters/live/MyQueryAdapter'

  4. const query = gql.query({
  5.   operation: 'thoughts',
  6.   fields: ['id', 'name', 'thought']
  7. }, MyQueryAdapter)

  8. console.log(query)

  9. // Output
  10. query SomethingIDidInMyAdapter {
  11.   thoughts {
  12.     id,
  13.     name,
  14.     thought
  15.   }
  16. }
  17. ```

Take a peek at DefaultQueryAdapter to get an understanding of how to make a new adapter.


Mutation:


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.mutation({
  4.   operation: 'thoughtCreate',
  5.   variables: {
  6.     name: 'Tyrion Lannister',
  7.     thought: 'I drink and I know things.'
  8.   },
  9.   fields: ['id']
  10. })

  11. console.log(query)

  12. // Output
  13. mutation ($name: String, $thought: String) {
  14.   thoughtCreate (name: $name, thought: $thought) {
  15.     id
  16.   }
  17. }

  18. // Variables
  19. {
  20.   "name": "Tyrion Lannister",
  21.   "thought": "I drink and I know things."
  22. }
  23. ```


Mutation (with required variables):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.mutation({
  4.   operation: 'userSignup',
  5.   variables: {
  6.     name: { value: 'Jon Doe' },
  7.     email: { value: 'jon.doe@example.com', required: true },
  8.     password: { value: '123456', required: true }
  9.   },
  10.   fields: ['userId']
  11. })

  12. console.log(query)

  13. // Output
  14. mutation ($name: String, $email: String!, $password: String!) {
  15.   userSignup (name: $name, email: $email, password: $password) {
  16.     userId
  17.   }
  18. }

  19. // Variables
  20. {
  21.   name: "Jon Doe",
  22.   email: "jon.doe@example.com",
  23.   password: "123456"
  24. }
  25. ```


Mutation (with custom types):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.mutation({
  4.   operation: "userPhoneNumber",
  5.   variables: {
  6.     phone: {
  7.       value: { prefix: "+91", number: "9876543210" },
  8.       type: "PhoneNumber",
  9.       required: true
  10.     }
  11.   },
  12.   fields: ["id"]
  13. })

  14. console.log(query)

  15. // Output
  16. mutation ($phone: PhoneNumber!) {
  17.   userPhoneNumber (phone: $phone) {
  18.     id
  19.   }
  20. }

  21. // Variables
  22. {
  23.   phone: {
  24.     prefix: "+91", number: "9876543210"
  25.   }
  26. }
  27. ```


Mutation (with adapter defined):


For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

  1. ```javascript
  2. import * as gql from 'gql-query-builder'
  3. import MyMutationAdapter from 'where/adapters/live/MyQueryAdapter'

  4. const query = gql.mutation({
  5.   operation: 'thoughts',
  6.   fields: ['id', 'name', 'thought']
  7. }, MyMutationAdapter)

  8. console.log(query)

  9. // Output
  10. mutation SomethingIDidInMyAdapter {
  11.   thoughts {
  12.     id,
  13.     name,
  14.     thought
  15.   }
  16. }
  17. ```


Take a peek at DefaultMutationAdapter to get an understanding of how to make a new adapter.

Mutation (with operation name):


  1. ```javascript
  2. import * as gql from 'gql-query-builder'

  3. const query = gql.mutation({
  4.   operation: 'thoughts',
  5.   fields: ['id', 'name', 'thought']
  6. }, undefined, {
  7.   operationName: 'someoperation'
  8. })

  9. console.log(query)

  10. // Output
  11. mutation someoperation {
  12.   thoughts {
  13.     id
  14.     name
  15.     thought
  16.   }
  17. }
  18. ```


Subscription:


  1. ```javascript
  2. import axios from "axios";
  3. import { subscription } from "gql-query-builder";

  4. async function saveThought() {
  5.   try {
  6.     const response = await axios.post(
  7.       "http://api.example.com/graphql",
  8.       subscription({
  9.         operation: "thoughtCreate",
  10.         variables: {
  11.           name: "Tyrion Lannister",
  12.           thought: "I drink and I know things.",
  13.         },
  14.         fields: ["id"],
  15.       })
  16.     );

  17.     console.log(response);
  18.   } catch (error) {
  19.     console.log(error);
  20.   }
  21. }
  22. ```


Subscription (with adapter defined):


For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

  1. ```javascript
  2. import * as gql from 'gql-query-builder'
  3. import MySubscriptionAdapter from 'where/adapters/live/MyQueryAdapter'

  4. const query = gql.subscription({
  5.   operation: 'thoughts',
  6.   fields: ['id', 'name', 'thought']
  7. }, MySubscriptionAdapter)

  8. console.log(query)

  9. // Output
  10. subscription SomethingIDidInMyAdapter {
  11.   thoughts {
  12.     id,
  13.     name,
  14.     thought
  15.   }
  16. }
  17. ```

Take a peek at DefaultSubscriptionAdapter to get an understanding of how to make a new adapter.


Example with Axios


Query:

  1. ```javascript
  2. import axios from "axios";
  3. import { query } from "gql-query-builder";

  4. async function getThoughts() {
  5.   try {
  6.     const response = await axios.post(
  7.       "http://api.example.com/graphql",
  8.       query({
  9.         operation: "thoughts",
  10.         fields: ["id", "name", "thought"],
  11.       })
  12.     );

  13.     console.log(response);
  14.   } catch (error) {
  15.     console.log(error);
  16.   }
  17. }
  18. ```


Mutation:

  1. ```javascript
  2. import axios from "axios";
  3. import { mutation } from "gql-query-builder";

  4. async function saveThought() {
  5.   try {
  6.     const response = await axios.post(
  7.       "http://api.example.com/graphql",
  8.       mutation({
  9.         operation: "thoughtCreate",
  10.         variables: {
  11.           name: "Tyrion Lannister",
  12.           thought: "I drink and I know things.",
  13.         },
  14.         fields: ["id"],
  15.       })
  16.     );

  17.     console.log(response);
  18.   } catch (error) {
  19.     console.log(error);
  20.   }
  21. }
  22. ```


Showcase


Following projects are using gql-query-builder

- Crate - Get monthly subscription of trendy clothes and accessories - GitHub
- Fullstack GraphQL Application - GitHub
- Would really appreciate if you add your project to this list by sending a PR

Author


- Atul Yadav - GitHub · Twitter

Contributors


**If you are interested in actively maintaining / enhancing this project, get in touch.**

- Juho Vepsäläinen - GitHub · Twitter
- Daniel Hreben - GitHub · Twitter
- Todd Baur - GitHub · Twitter
- Alireza Hariri - GitHub
- Cédric - GitHub
- Clayton Collie - GitHub
- Devon Reid - GitHub
- Harry Brundage - GitHub · Twitter
- Clément Berard - GitHub · Twitter
- Lee Rose - GitHub
- Christian Westgaard - GitHub
- [YOUR NAME HERE] - Feel free to contribute to the codebase by resolving any open issues, refactoring, adding new features, writing test cases or any other way to make the project better and helpful to the community. Feel free to fork and send pull requests.

Donate


If you liked this project, you can donate to support it ❤️

Donate via PayPal

License


Copyright (c) 2018 Atul Yadav

The MIT License ()