• Stars
    star
    354
  • Rank 120,042 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿ”ง Simple GraphQL Query Builder

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

import * as gql from 'gql-query-builder'

const query = gql.query(options: object)
const mutation = gql.mutation(options: object)
const subscription = gql.subscription(options: object)

You can also import query or mutation or subscription individually:

import  { query, mutation, subscription } from 'gql-query-builder'

query(options: object)
mutation(options: object)
subscription(options: object)

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: "[email protected]", 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.

import * as gql from 'gql-query-builder'

const query = gql.query(options: object, adapter?: MyCustomQueryAdapter,config?: object)
const mutation = gql.mutation(options: object, adapter?: MyCustomQueryAdapter)
const subscription = gql.subscription(options: object, adapter?: MyCustomSubscriptionAdapter)

Config

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

Examples

  1. Query
  2. 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. Mutation
  11. Mutation (with required variables)
  12. Mutation (with custom types)
  13. Mutation (with adapter defined)
  14. Mutation (with operation name)
  15. Subscription
  16. Subscription (with adapter defined)
  17. Example with Axios

Query:

import * as gql from 'gql-query-builder'

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

console.log(query)

// Output
query {
  thoughts {
    id,
    name,
    thought
  }
}

โ†‘ all examples

Query (with variables):

import * as gql from 'gql-query-builder'

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

console.log(query)

// Output
query ($id: Int) {
  thought (id: $id) {
    id, name, thought
  }
}

// Variables
{ "id": 1 }

โ†‘ all examples

Query (with nested fields selection):

import * as gql from 'gql-query-builder'

const query = gql({
  operation: 'orders',
  fields: [
    'id',
    'amount',
    {
     user: [
        'id',
        'name',
        'email',
        {
          address: [
            'city',
            'country'
          ]
        }
      ]
    }
  ]
})

console.log(query)

// Output
query {
  orders  {
    id,
    amount,
    user {
      id,
      name,
      email,
      address {
        city,
        country
      }
    }
  }
}

โ†‘ all examples

Query (with required variables):

import * as gql from 'gql-query-builder'

const query = gql.query({
  operation: 'userLogin',
  variables: {
    email: { value: '[email protected]', required: true },
    password: { value: '123456', required: true }
  },
  fields: ['userId', 'token']
})

console.log(query)

// Output
query ($email: String!, $password: String!) {
  userLogin (email: $email, password: $password) {
    userId, token
  }
}

// Variables
{
  email: "[email protected]",
  password: "123456"
}

โ†‘ all examples

Query (with custom argument name):

import * as gql from 'gql-query-builder'

const query = gql.query([{
  operation: "someoperation",
  fields: [{
    operation: "nestedoperation",
    fields: ["field1"],
    variables: {
      id2: {
        name: "id",
        type: "ID",
        value: 123,
      },
    },
  }, ],
  variables: {
    id1: {
      name: "id",
      type: "ID",
      value: 456,
    },
  },
}, ]);

console.log(query)

// Output
query($id2: ID, $id1: ID) {
  someoperation(id: $id1) {
    nestedoperation(id: $id2) {
      field1
    }
  }
}

// Variables
{
  "id1": 1,
  "id2": 1
}

โ†‘ all examples

Query (with operation name):

import * as gql from 'gql-query-builder'

const query = gql.query({
  operation: 'userLogin',
  fields: ['userId', 'token']
}, null, {
  operationName: 'someoperation'
})

console.log(query)

// Output
query someoperation {
  userLogin {
    userId
    token
  }
}

โ†‘ all examples

Query (with empty fields):

import * as gql from 'gql-query-builder'

const query = gql.query([{
  operation: "getFilteredUsersCount",
},
  {
    operation: "getAllUsersCount",
    fields: []
  },
  operation: "getFilteredUsers",
  fields: [{
  count: [],
}, ],
]);

console.log(query)

// Output
query {
  getFilteredUsersCount
  getAllUsersCount
  getFilteredUsers {
    count
  }
}

โ†‘ all examples

Query (with alias):

import * as gql from 'gql-query-builder'

const query = gql.query({
  operation: {
    name: 'thoughts',
    alias: 'myThoughts',
  },
  fields: ['id', 'name', 'thought']
})

console.log(query)

// Output
query {
  myThoughts: thoughts {
    id,
    name,
    thought
  }
}

โ†‘ all examples

Query (with inline fragment):

import * as gql from 'gql-query-builder'

const query = gql.query({
    operation: "thought",
    fields: [
        "id",
        "name",
        "thought",
        {
            operation: "FragmentType",
            fields: ["emotion"],
            fragment: true,
        },
    ],
});

console.log(query)

// Output
query {
    thought {
        id,
        name,
        thought,
        ... on FragmentType {
            emotion
        }
    }
}

โ†‘ all examples

Query (with adapter defined):

For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

import * as gql from 'gql-query-builder'
import MyQueryAdapter from 'where/adapters/live/MyQueryAdapter'

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

console.log(query)

// Output
query SomethingIDidInMyAdapter {
  thoughts {
    id,
    name,
    thought
  }
}

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

โ†‘ all examples

Mutation:

import * as gql from 'gql-query-builder'

const query = gql.mutation({
  operation: 'thoughtCreate',
  variables: {
    name: 'Tyrion Lannister',
    thought: 'I drink and I know things.'
  },
  fields: ['id']
})

console.log(query)

// Output
mutation ($name: String, $thought: String) {
  thoughtCreate (name: $name, thought: $thought) {
    id
  }
}

// Variables
{
  "name": "Tyrion Lannister",
  "thought": "I drink and I know things."
}

โ†‘ all examples

Mutation (with required variables):

import * as gql from 'gql-query-builder'

const query = gql.mutation({
  operation: 'userSignup',
  variables: {
    name: { value: 'Jon Doe' },
    email: { value: '[email protected]', required: true },
    password: { value: '123456', required: true }
  },
  fields: ['userId']
})

console.log(query)

// Output
mutation ($name: String, $email: String!, $password: String!) {
  userSignup (name: $name, email: $email, password: $password) {
    userId
  }
}

// Variables
{
  name: "Jon Doe",
  email: "[email protected]",
  password: "123456"
}

โ†‘ all examples

Mutation (with custom types):

import * as gql from 'gql-query-builder'

const query = gql.mutation({
  operation: "userPhoneNumber",
  variables: {
    phone: {
      value: { prefix: "+91", number: "9876543210" },
      type: "PhoneNumber",
      required: true
    }
  },
  fields: ["id"]
})

console.log(query)

// Output
mutation ($phone: PhoneNumber!) {
  userPhoneNumber (phone: $phone) {
    id
  }
}

// Variables
{
  phone: {
    prefix: "+91", number: "9876543210"
  }
}

โ†‘ all examples

Mutation (with adapter defined):

For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

import * as gql from 'gql-query-builder'
import MyMutationAdapter from 'where/adapters/live/MyQueryAdapter'

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

console.log(query)

// Output
mutation SomethingIDidInMyAdapter {
  thoughts {
    id,
    name,
    thought
  }
}

โ†‘ all examples

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

Mutation (with operation name):

import * as gql from 'gql-query-builder'

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

console.log(query)

// Output
mutation someoperation {
  thoughts {
    id
    name
    thought
  }
}

โ†‘ all examples

Subscription:

import axios from "axios";
import { subscription } from "gql-query-builder";

async function saveThought() {
  try {
    const response = await axios.post(
      "http://api.example.com/graphql",
      subscription({
        operation: "thoughtCreate",
        variables: {
          name: "Tyrion Lannister",
          thought: "I drink and I know things.",
        },
        fields: ["id"],
      })
    );

    console.log(response);
  } catch (error) {
    console.log(error);
  }
}

โ†‘ all examples

Subscription (with adapter defined):

For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

import * as gql from 'gql-query-builder'
import MySubscriptionAdapter from 'where/adapters/live/MyQueryAdapter'

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

console.log(query)

// Output
subscription SomethingIDidInMyAdapter {
  thoughts {
    id,
    name,
    thought
  }
}

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

โ†‘ all examples

Example with Axios

Query:

import axios from "axios";
import { query } from "gql-query-builder";

async function getThoughts() {
  try {
    const response = await axios.post(
      "http://api.example.com/graphql",
      query({
        operation: "thoughts",
        fields: ["id", "name", "thought"],
      })
    );

    console.log(response);
  } catch (error) {
    console.log(error);
  }
}

โ†‘ all examples

Mutation:

import axios from "axios";
import { mutation } from "gql-query-builder";

async function saveThought() {
  try {
    const response = await axios.post(
      "http://api.example.com/graphql",
      mutation({
        operation: "thoughtCreate",
        variables: {
          name: "Tyrion Lannister",
          thought: "I drink and I know things.",
        },
        fields: ["id"],
      })
    );

    console.log(response);
  } catch (error) {
    console.log(error);
  }
}

โ†‘ all examples

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

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 http://github.com/atulmy

The MIT License (http://www.opensource.org/licenses/mit-license.php)

More Repositories

1

crate

๐Ÿ‘• ๐Ÿ‘– ๐Ÿ“ฆ A sample web and mobile application built with Node, Express, React, React Native, Redux and GraphQL. Very basic replica of stitchfix.com / krate.in (allows users to get monthly subscription of trendy clothes and accessories).
JavaScript
2,400
star
2

fullstack-graphql

๐ŸŒˆ Simple Fullstack GraphQL Application. API built with Express + GraphQL + Sequelize (supports MySQL, Postgres, Sqlite and MSSQL). WebApp built with React + Redux to access the API. Written in ES6 using Babel + Webpack.
JavaScript
1,026
star
3

fullstack-javascript-architecture

โœ๏ธ Opinionated project architecture for Full-Stack JavaScript Applications.
JavaScript
652
star
4

oauth

๐Ÿ”— OAuth 2.0 implementation for various providers in one place.
JavaScript
426
star
5

node-express-react-redux-zwitter

๐Ÿฃ A basic clone of Twitter (Boilerplate App) - Separate API (express+mongo) and Frontend (react+redux) folders using Node, Express, MongoDB, React (create-react-app), React Router v4 and Redux.
JavaScript
92
star
6

universal-react

๐ŸŒ A simple universal react application with server side rendering built with latest versions of React (v16+), React Router (v5+), Redux (v4+), Express (v5+), Webpack (v4+), Babel Preset ES6 ๐Ÿ‘จโ€๐Ÿ’ป
JavaScript
79
star
7

hire-smart

โœ… HIRE SMART (community edition) - Streamline hiring process, scheduling interviews and tracking candidates.
JavaScript
70
star
8

react-recoil

A sample implementation of React Recoil.
JavaScript
44
star
9

react-native-curated

๐Ÿ’โ€โ™‚๏ธ Hand picked collection of packages, tutorials and more for React Native.
43
star
10

wispy

๐ŸŒฑ An experimental lightweight (remote procedure call) API pattern.
JavaScript
36
star
11

meteor-react-simple-chat

๐Ÿ’ฌ Basic chat application using Meteor 1.4 and React.
JavaScript
25
star
12

meteor-baseui

๐Ÿ“ฑ๐Ÿ–ฅ Basic UI: Mobile + Web
HTML
13
star
13

node-react-zwitter

๐Ÿง NodeJS, Express, MySQL and React Boilerplate App - Zwitter (Basic clone of Twitter)
JavaScript
13
star
14

cv

๐Ÿ“„ Curriculum Vitae
12
star
15

meteor-bootstrap

๐Ÿฃ Meteor Bootstrap / Boilerplate Project with essential folder structures and packages.
JavaScript
10
star
16

meteor-mafia

๐ŸŽฎ Mafia: The Party Game!
JavaScript
9
star
17

meteor-rock-paper-scissors

๐Ÿ‘Šโœ‹โœŒ๏ธ Rock Paper Scissors - Play online with your friends or with computer
JavaScript
7
star
18

meteor-tictactoe

๐ŸŽฎ Tic Tac Toe - Play multiplayer online with your friends
JavaScript
6
star
19

node-express-handlebars-zwitter

๐Ÿง NodeJS, Express, Mongoose and Handlebars Boilerplate App - Zwitter (Basic clone of Twitter)
JavaScript
5
star
20

jquery-connectors

๐Ÿ”— Draws a path between two HTML elements.
JavaScript
5
star
21

fullstack-validator

๐Ÿ›ก A simple validation library for server and client side JavaScript applications.
TypeScript
5
star
22

meteor-1.4-zwitter

๐Ÿง Meteor 1.4 Boilerplate App - Zwitter (Basic clone of Twitter)
JavaScript
4
star
23

tool-aspectratio

๐Ÿ“ฑ ๐Ÿ–ฅ ๐Ÿ’ป Calculate aspect ratio online for images, display screens, montors and mobile easily.
PHP
4
star
24

php-angular-easyapp

An easy, flexible, very light weight, extendable, small to medium scale application template. Recommended for beginners exploring web technologies. Best suited for SPAs and RIAs.
PHP
4
star
25

node-basics

Basics of NodeJS
JavaScript
4
star
26

meteor-react-zwitter

๐Ÿง Meteor + ReactJS Boilerplate App - Zwitter (Basic clone of Twitter)
JavaScript
3
star
27

baseui

๐Ÿ“ฑ๐Ÿ–ฅ Basic UI: Mobile + Web
HTML
3
star
28

node-express-angular-job-finder

๐Ÿ” A sample app built on Mongo, Express and Angular and Node
CSS
2
star
29

workstation

1
star