graphqurl

curl for GraphQL with autocomplete, subscriptions and GraphiQL. Also a dead...

README

graphqurl

oclif Version
Azure Pipelines Appveyor CI Downloads/week License

graphqurl is a curl like CLI for GraphQL. It's features include:
- CLI for making GraphQL queries. It also provisions queries with autocomplete.
- Run a custom GraphiQL, where you can specify request's headers, locally against any endpoint
- Use as a library with Node.js or from the browser
- Supports subscriptions
- Export GraphQL schema

Made with :heart: by Hasura

Graphqurl Demo
GraphiQL Demo
Subscriptions triggering bash


Table of contents

  CLI
    + Query
    + Auto-complete
    + GraphiQL
    + Subscription
    + Export schema
    + Args
    + Flag Reference
    + Using Promises:
  API
    + Client
    + Subscriptions
  CLI


Installation


Steps to Install CLI


  1. ``` sh
  2. npm install -g graphqurl
  3. ```

Steps to Install Node Library


  1. ``` sh
  2. npm install --save graphqurl
  3. ```

Usage


CLI


Query


  1. ``` sh
  2. gq https://my-graphql-endpoint/graphql \
  3.      -H 'Authorization: Bearer <token>' \
  4.      -q 'query { table { column } }'
  5. ```

Auto-complete


Graphqurl can auto-complete queries using schema introspection. Execute the
command without providing a query string:

  1. ``` sh
  2. $ gq <endpoint> [-H <header:value>]
  3. Enter the query, use TAB to auto-complete, Ctrl+Q to execute, Ctrl+C to cancel
  4. gql>
  5. ```

You can use TAB to trigger auto-complete. Ctrl+C to cancel the input and
Ctrl+Q/Enter to execute the query.

GraphiQL


Open GraphiQL with a given endpoint:

  1. ``` sh
  2. gq <endpoint> -i
  3. ```

This is a custom GraphiQL where you can specify request's headers.



Subscription


Subscriptions can be executed and the response is streamed on to stdout.

  1. ``` sh
  2. gq <endpoint> \
  3.    -q 'subscription { table { column } }'
  4. ```

Export schema


Export GraphQL schema to GraphQL or JSON format:

  1. ``` sh
  2. gq <endpoint> --introspect > schema.graphql

  3. # json
  4. gq <endpoint> --introspect --format json > schema.json
  5. ```

Command


  1. ``` sh
  2. $ gq ENDPOINT [-q QUERY]
  3. ```

Args


ENDPOINT: graphql endpoint (can be also set as GRAPHQURL_ENDPOINT env var)

Flag Reference


FlagShorthandDescription
|---------------------|-----------|-------------------------------------------------------------------------------------------------------|
`--query``-q`GraphQL
`--header``-H`request
`--variable``-v`Variables
`--variablesJSON``-n`Variables
`--graphiql``-i`Open
`--graphiqlHost``-a`Host
`--graphiqlPort``-p`Port
`--singleLine``-l`Prints
`--introspect`|
`--format`|
`--help``-h`Outputs
`--version`|
|`--queryFile`|
|`--operationName`|
|`--variablesFile`|


Node Library


Using callbacks:


  1. ``` js
  2. const { createClient } = require('graphqurl');

  3. const client = createClient({
  4.   endpoint: 'https://my-graphql-endpoint/graphql',
  5.   headers: {
  6.     'Authorization': 'Bearer <token>'
  7.   }
  8. });

  9. function successCallback(response, queryType, parsedQuery) {
  10.   if (queryType === 'subscription') {
  11.     // handle subscription response
  12.   } else {
  13.     // handle query/mutation response
  14.   }
  15. }

  16. function errorCallback(error, queryType, parsedQuery) {
  17.   console.error(error);
  18. }

  19. client.query(
  20.   {
  21.     query: 'query ($id: Int) { table_by_id (id: $id) { column } }',
  22.     variables: { id: 24 }
  23.   },
  24.   successCallback,
  25.   errorCallback
  26. );

  27. ```

Using Promises:


For queries and mutations,

  1. ``` js
  2. const { createClient } = require('graphqurl');

  3. const client = createClient({
  4.   endpoint: 'https://my-graphql-endpoint/graphql',
  5.   headers: {
  6.     'Authorization': 'Bearer <token>'
  7.   }
  8. });

  9. client.query(
  10.   {
  11.     query: 'query ($id: Int) { table_by_id (id: $id) { column } }',
  12.     variables: { id: 24 }
  13.   }
  14. ).then((response) => console.log(response))
  15. .catch((error) => console.error(error));
  16. ```

For subscriptions,

  1. ``` js
  2. const { createClient } = require('graphqurl');

  3. const client = createClient({
  4.   endpoint: 'https://my-graphql-endpoint/graphql',
  5.   headers: {
  6.     'Authorization': 'Bearer <token>'
  7.   },
  8.   websocket: {
  9.     endpoint: 'wss://my-graphql-endpoint/graphql',
  10.     onConnectionSuccess: () => console.log('Connected'),
  11.     onConnectionError: () => console.log('Connection Error'),
  12.   }
  13. });

  14. client.subscribe(
  15.   {
  16.     subscription: 'subscription { table { column } }',
  17.   },
  18.   (event) => {
  19.     console.log('Event received: ', event);
  20.     // handle event
  21.   },
  22.   (error) => {
  23.     console.log('Error: ', error);
  24.     // handle error
  25.   }
  26. )
  27. ```

API


createClient


The createClient function is available as a named export. It takes init options and returns client.

  1. ```
  2. const { createClient } = require('graphqurl');
  3. ```


- options: [Object, required] graphqurl init options with the following properties:
  - endpoint: [String, required] GraphQL endpoint
  - headers: [Object] Request header, defaults to {}. These headers will be added along with all the GraphQL queries, mutations and subscriptions made through the client.
  - websocket: [Object] Options for configuring subscriptions over websocket. Subscriptions are not supported if this field is empty.
    - endpoint: [String, ] WebSocket endpoint to run GraphQL subscriptions.
    - shouldRetry: [Boolean] Boolean value whether to retry closed websocket connection. Defaults to false.
    - parameters: [Object] Payload to send the connection init message with
    - onConnectionSuccess: [void => void] Callback function called when the GraphQL connection is successful. Please not that this is different from the websocket connection being open. Please check the followed protocol for more details.
    - onConnectionError: [error => null] Callback function called if the GraphQL connection over websocket is unsuccessful
    - onConnectionKeepAlive: [void => null]: Callback function called when the GraphQL server sends GRAPHQL_CONNECTION_KEEP_ALIVE messages to keep the connection alive.

- Returns: [client]

Client



  1. ``` js
  2. const client = createClient({
  3.   endpoint: 'https://my-graphql-endpoint/graphql'
  4. });
  5. ```

The graphqurl client exposeses the following methods:

- client.query: [(queryoptions, successCallback, errorCallback) => Promise (response)]
  - queryOptions: [Object required]
    - query: [String required] The GraphQL query or mutation to be executed over HTTP
    - variables: [Object] GraphQL query variables. Defaults to {}
    - headers: [Object] Header overrides. If you wish to make a GraphQL query while adding to or overriding the headers provided during initalisations, you can pass the headers here.
  - successCallback: [response => null] Success callback which is called after a successful response. It is called with the following parameters:
    - response: The response of your query
  - errorCallback: [error => null] Error callback which is called after the occurrence of an error. It is called with the following parameters:
    - error: The occurred error
  - Returns: [Promise (response) ] This function returns the response wrapped in a promise.
    - response: response is a GraphQL compliant JSON object in case of queries and mutations.

- client.subscribe: [(subscriptionOptions, eventCallback, errorCallback) => Function (stop)]
  - subscriptionOptions: [Object required]
    - subscription: [String required] The GraphQL subscription to be started over WebSocket
    - variables: [Object] GraphQL query variables. Defaults to {}
    - onGraphQLData: [(response) => null] You can optionally pass this function as an event callback
    - onGraphQLError: [(response) => null] You can optionally pass this function as an error callback
    - onGraphQLComplete: [() => null] Callback function called when the GraphQL subscription is declared as complete by the server and no more events will be received
  - eventCallback: [(response) => null] Event callback which is called after receiving an event from the given subscription. It is called with the following parameters:
    - event: The received event from the subscription
  - errorCallback: [error => null] Error callback which is called after the occurrence of an error. It is called with the following parameters:
    - error: The occurred error
  - Returns: [void => null] This is a function to stop the subscription


More Examples


Node Library


Queries and Mutations


Query example with variables

  1. ``` js
  2. const { createClient } = require('graphqurl');

  3. const client = createClient({
  4.   endpoint: 'https://my-graphql-endpoint/graphql',
  5.   headers: {
  6.     'x-access-key': 'mysecretxxx',
  7.   },
  8. });

  9. client.query(
  10.   {
  11.     query: `
  12.       query ($name: String) {
  13.         table(where: { column: $name }) {
  14.           id
  15.           column
  16.         }
  17.       }
  18.     `,
  19.     variables: {
  20.       name: 'Alice'
  21.     }
  22.   }
  23. ).then((response) => console.log(response))
  24. .catch((error) => console.error(error));
  25. ```

Subscriptions


Using promises,

  1. ``` js
  2. const { createClient } = require('graphqurl');
  3. const client = createClient({
  4.   endpoint: 'https://my-graphql-endpoint/graphql',
  5.   headers: {
  6.     'Authorization': 'Bearer Andkw23kj=Kjsdk2902ksdjfkd'
  7.   }
  8.   websocket: {
  9.     endpoint: 'wss://my-graphql-endpoint/graphql',
  10.   }
  11. })

  12. const eventCallback = (event) => {
  13.   console.log('Event received:', event);
  14.   // handle event
  15. };

  16. const errorCallback = (error) => {
  17.   console.log('Error:', error)
  18. };

  19. client.subscribe(
  20.   {
  21.     query: 'subscription { table { column } }',
  22.   },
  23.   eventCallback,
  24.   errorCallback
  25. )
  26. ```


CLI


Generic example:

  1. ``` sh
  2. gq \
  3.      https://my-graphql-endpoint/graphql \
  4.      -H 'Authorization: Bearer <token>' \
  5.      -H 'X-Another-Header: another-header-value' \
  6.      -v 'variable1=value1' \
  7.      -v 'variable2=value2' \
  8.      -q 'query { table { column } }'
  9. ```

Maintained with :heart: by Hasura