Git Product home page Git Product logo

graphqurl's Introduction

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 ❤️ by Hasura


Graphqurl Demo

GraphiQL Demo

Subscriptions triggering bash


Table of contents

Installation

Steps to Install CLI

npm install -g graphqurl

Steps to Install Node Library

npm install --save graphqurl

Usage

CLI

Query

gq https://my-graphql-endpoint/graphql \
     -H 'Authorization: Bearer <token>' \
     -q 'query { table { column } }'

Auto-complete

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

$ gq <endpoint> [-H <header:value>]
Enter the query, use TAB to auto-complete, Ctrl+Q to execute, Ctrl+C to cancel
gql>

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:

gq <endpoint> -i

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.

gq <endpoint> \
   -q 'subscription { table { column } }'

Export schema

Export GraphQL schema to GraphQL or JSON format:

gq <endpoint> --introspect > schema.graphql

# json
gq <endpoint> --introspect --format json > schema.json

Command

$ gq ENDPOINT [-q QUERY]

Args

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

Flag Reference

Flag Shorthand Description
--query -q GraphQL query to execute
--header -H request header
--variable -v Variables used in the query
--variablesJSON -n Variables used in the query as JSON
--graphiql -i Open GraphiQL with the given endpoint, headers, query and variables
--graphiqlHost -a Host to use for GraphiQL. (Default: localhost)
--graphiqlPort -p Port to use for GraphiQL
--singleLine -l Prints output in a single line, does not prettify
--introspect Introspect the endpoint and get schema
--format Output format for GraphQL schema after introspection. Options: json, graphql (Default: graphql)
--help -h Outputs the command help text
--version Outputs CLI version
--queryFile File to read the query from
--operationName Name of the operation to execute from the query file
--variablesFile JSON file to read the query variables from

Node Library

Using callbacks:

const { createClient } = require('graphqurl');

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'Authorization': 'Bearer <token>'
  }
});

function successCallback(response, queryType, parsedQuery) {
  if (queryType === 'subscription') {
    // handle subscription response
  } else {
    // handle query/mutation response
  }
}

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

client.query(
  {
    query: 'query ($id: Int) { table_by_id (id: $id) { column } }',
    variables: { id: 24 }
  },
  successCallback,
  errorCallback
);

Using Promises:

For queries and mutations,

const { createClient } = require('graphqurl');

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'Authorization': 'Bearer <token>'
  }
});

client.query(
  {
    query: 'query ($id: Int) { table_by_id (id: $id) { column } }',
    variables: { id: 24 }
  }
).then((response) => console.log(response))
 .catch((error) => console.error(error));

For subscriptions,

const { createClient } = require('graphqurl');

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'Authorization': 'Bearer <token>'
  },
  websocket: {
    endpoint: 'wss://my-graphql-endpoint/graphql',
    onConnectionSuccess: () => console.log('Connected'),
    onConnectionError: () => console.log('Connection Error'),
  }
});

client.subscribe(
  {
    subscription: 'subscription { table { column } }',
  },
  (event) => {
    console.log('Event received: ', event);
    // handle event
  },
  (error) => {
    console.log('Error: ', error);
    // handle error
  }
)

API

createClient

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

const { createClient } = require('graphqurl');
  • 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

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql'
});

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

const { createClient } = require('graphqurl');

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'x-access-key': 'mysecretxxx',
  },
});

client.query(
  {
    query: `
      query ($name: String) {
        table(where: { column: $name }) {
          id
          column
        }
      }
    `,
    variables: {
      name: 'Alice'
    }
  }
).then((response) => console.log(response))
 .catch((error) => console.error(error));

Subscriptions

Using promises,

const { createClient } = require('graphqurl');
const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'Authorization': 'Bearer Andkw23kj=Kjsdk2902ksdjfkd'
  }
  websocket: {
    endpoint: 'wss://my-graphql-endpoint/graphql',
  }
})

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

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

client.subscribe(
  {
    query: 'subscription { table { column } }',
  },
  eventCallback,
  errorCallback
)

CLI

Generic example:

gq \
     https://my-graphql-endpoint/graphql \
     -H 'Authorization: Bearer <token>' \
     -H 'X-Another-Header: another-header-value' \
     -v 'variable1=value1' \
     -v 'variable2=value2' \
     -q 'query { table { column } }'

Maintained with ❤️ by Hasura

graphqurl's People

Contributors

0xflotus avatar 99hats avatar azure-pipelines[bot] avatar coco98 avatar daa avatar dependabot[bot] avatar dsandip avatar heyrict avatar jakubknejzlik avatar motleydev avatar rkaranam avatar shahidhk avatar shraddhaag avatar simonepri avatar ssendev avatar stardustrain avatar wawhal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphqurl's Issues

401 Unauthorized when connecting to GitHub HTTPS GraphQL API?

I have a working curl to access the GitHub API (where ${TOKEN} is a bash/zsh environment variable containing a valid GitHub personal access token):

curl -H "Authorization: bearer ${TOKEN}" https://api.github.com/graphql

However I can't seem get it to work with graphqurl?

$ gq https://api.github.com/graphql -H 'Authorization: bearer ${TOKEN}' 


Introspecting schema... !
    Error: Network error: Response not successful: Received status code 401

Wireshark shows it trying TLSv1.3 instead of TLSv1.2 though otherwise I'm unclear how to proceed without starting to dig into the source code here (and sadly don't have infinite time).

Aside: A demo in the animated GIFs works for me:

gq http://graphql.communitygraph.org/graphql/ -i

Edit: A nicer working curl:

 curl -H "Authorization: bearer ${TOKEN}" -X POST -d " \
 { \
   \"query\": \"query { viewer { login }}\" \
 } \
" https://api.github.com/graphql
{"data":{"viewer":{"login":"pzrq"}}}

Any ideas if I'm missing something obvious?

remove apollo client from the library

graphqurl uses apollo-client underneath to make queries and subscriptions. Apollo client is actually unnecessary for this use case. This library can be more performant and lightweight if we remove the apollo-client and simply use node-fetch for queries and mutations and isomorphic-ws for subscriptions.

Checklist:

  • Use node-fetch for HTTP calls
  • Use isomorphic-ws for subscriptions.

WebSocket connection has not been established

Running a very similar example to the documented one but I can't seem to get subscriptions working (queries run fine).

main.js

const { createClient } = require('graphqurl');

const client = createClient({
    endpoint: 'https://<hasura-cloud-domain>/v1/graphql',
    headers: {
        'X-Hasura-Admin-Secret': '<secret>'
    },
    websocket: {
        endpoint: 'wss://<hasura-cloud-domain>/v1/graphql',
        onConnectionSuccess: () => console.log('Connected'),
        onConnectionError: () => console.log('Connection Error'),
    }
});

const eventCallback = (event) => {
    console.log('Event received:', event);
};

function errorCallback(error) {
    console.error(error);
}

client.subscribe(
    {
        query: 'subscription { core_brand_by_pk(id: 872) { name } }',
    },
    eventCallback,
    errorCallback
);
>>> node main.js
WebSocket connection has not been established
Connected

update graphql dependency to latest

Currently there is graphql": "0.9.1" installed as dependency - but Latest version: 15.3.0
Please update it - I gaving issue where exported schema includes wrong typings for example

type AppPurchaseOneTime implements AppPurchase, Node {
...

but this should be like

type AppPurchaseOneTime implements AppPurchase & Node {
...

http://spec.graphql.org/draft/#sec-Interfaces

So I'm hoping that updating the library will solve the issue.

Not working with async/await?

I'm trying to preload some data into an instance of Hasura on Heroku using graphqurl, node 10.12, and async/await. I have an async function that first queries for a record with a particular date, returns it if found, and issues a mutation to create it if not found. I added a log statement immediately before calling await query(....) and another immediately after, and shorten my input to only 5 lines (all with the same date). I'm seeing the first log statement output 5 times, then the 5 responses, instead of query, response, query, response etc.

Has anyone else tried async/await and seen it work?

let counter = 0;

/*
 * Find or create a gig with the given date at 7pm at Leadbone Studios
 * for the band Leadbone.
 */
async function findOrCreateGig(date) {
    let dt = fixDate(date);

    let cnt = ++counter;
    console.log(`${cnt}: Querying date ${date}`)

    let response = await query({
        query: `
            query gig($date: date!) {
                gig(where: {date: {_eq: $date}}) {
                    id
                }
            }
        `, ...endPt,
        variables: {
            date: dt
        }
    });


    console.log(`${cnt}: response for ${date}: ${response.data.gig.length}`)
    
    if(response.data.gig.length)
        return response.data.gig[0].id;

    // Create it
    response = await query({
        query: `
            mutation insert_gig($date: date!, $band: uuid!) {
                insert_gig(objects: [
                    {
                        date: $date,
                        recorded: true,
                        venue: "Leadbone Studios",
                        band: $band
                    }
                ]) {
                    returning {
                        id
                    }
                }
            }
        `, ...endPt,
        variables: {
            date: dt,
            band: leadbone
        }
    });

    assert(response);
    return response.data.insert_gig.returning[0].id;
}
Output:
1: Querying date 20180712
2: Querying date 20180712
3: Querying date 20180712
4: Querying date 20180712
5: Querying date 20180712
1: response for 20180712: 0
2: response for 20180712: 0
3: response for 20180712: 0
4: response for 20180712: 0
5: response for 20180712: 0

high vulnerabilities in npm

image

glob-parent <5.1.2
Severity: high
Regular expression denial of service - GHSA-ww39-953v-wcq6
fix available via npm audit fix
node_modules/glob-parent

node-fetch <2.6.7
Severity: high
node-fetch is vulnerable to Exposure of Sensitive Information to an Unauthorized Actor - GHSA-r683-j2x4-v87g
fix available via npm audit fix
node_modules/node-fetch

'Mutation did not trigger an event null' on 'npm test'

I was trying to run the tests per TESTING, but it's failing with:

$ GRAPHQURL_TEST_GRAPHQL_ENGINE_URL=http://localhost:8080/ GRAPHQURL_TEST_X_HASURA_ACCESS_KEY=myadminsecretkey npm test                                                 

> [email protected] test /Users/dave/dev/graphqurl
> node test/index.test.js && node test/clearstate.test.js

✔︎ Mutation with promise
✔︎ Query with promise
✔︎ Mutation with callback
✔︎ Query with callback
✖ Subscription with promise
Mutation did not trigger an event null
npm ERR! Test failed.  See above for more details.

I'm using the hasura/graphql-engine:v1.0.0-alpha44 Docker image, via this docker-compose.yml.

I can repro 100%.

Here's what it looks like.

Dark mode

Would be cool to have a dark mode on the node webpage

Show a message saying `invalid` graphql endpoint if it cannot introspect

➜ ~ gq http://localhost:8080

Error: Network error: Unexpected token N in JSON at position 0
at new ApolloError (~/.nvm/versions/node/v10.1.0/lib/node_modules/graphqurl/node_modules/apollo-client/bundle.umd.js:124:32)
at ~/.nvm/versions/node/v10.1.0/lib/node_modules/graphqurl/node_modules/apollo-client/bundle.umd.js:1248:45
at ~/.nvm/versions/node/v10.1.0/lib/node_modules/graphqurl/node_modules/apollo-client/bundle.umd.js:1680:21
at Array.forEach ()
at /.nvm/versions/node/v10.1.0/lib/node_modules/graphqurl/node_modules/apollo-client/bundle.umd.js:1679:22
at Map.forEach ()
at QueryManager.broadcastQueries (
/.nvm/versions/node/v10.1.0/lib/node_modules/graphqurl/node_modules/apollo-client/bundle.umd.js:1672:26)
at ~/.nvm/versions/node/v10.1.0/lib/node_modules/graphqurl/node_modules/apollo-client/bundle.umd.js:1175:35

Expectation: Invalid GraphQL endpoint.

Isn't it need to Content-Type headers?

First, I appreciate made a good library for GraphQL environment.

I have a question in use graphqurl.

Isn't it need to "Content-Type": "application/json" headers when requests to GraphQL server?

I'd made a simple GraphQL server with fastify + mercurius, and using graphqurl in CLI but an error occurred this:
image

I was found that 'content-type': 'text/plain;charset=UTF-8' in request headers, therefore I think parsing body with inappropriate parsing logic when receiving request in fastify server.

I'm confused as to whether I need to modify the server's parsing logic for instance like this?

fastify.addContentTypeParser('text/plain', { parseAs: 'string' }, function (req, body, done) {
  try {
    const json = JSON.parse(body)
    done(null, json)
  } catch (err) {
    err.statusCode = 400
    done(err, undefined)
  }
})

If this library is a problem and fixing it isn't a high priority, I'd like to try it.

Throws exception after installation for any command

gq -h
/usr/local/lib/node_modules/graphqurl/src/command.js:16 async run() { ^^^ SyntaxError: Unexpected identifier at Object.exports.runInThisContext (vm.js:78:16) at Module._compile (module.js:545:28) at Object.Module._extensions..js (module.js:582:10) at Module.load (module.js:490:32) at tryModuleLoad (module.js:449:12) at Function.Module._load (module.js:441:3) at Module.require (module.js:500:17) at require (internal/module.js:20:19) at Object.<anonymous> (/usr/local/lib/node_modules/graphqurl/bin/run:3:1) at Module._compile (module.js:573:32)

[bug,ci] does not work on node v8.0.0

though package.json specify node>=8.0.0, the installed cli failed on 8.0.0 with command

$ node -v
v8.0.0
$ npm -v
5.0.0
$ gq
/home/user/.nvm/versions/node/v8.0.0/lib/node_modules/graphqurl/node_modules/graphql-language-service-parser/dist/onlineParser.js:128
    state.prevState = { ...state };
                        ^^^

SyntaxError: Unexpected token ...
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/user/.nvm/versions/node/v8.0.0/lib/node_modules/graphqurl/node_modules/graphql-language-service-parser/dist/index.js:15:22)

However, the error disappear once switched to node==10.0.0. Should this be reflected somewhere in the CI yaml config?

refresh the lockfile to automatically remove the vulnerability introduced by tree-kit

Hi, @wawhal, I have reported a vulnerability issue in package terminal-kit.

As far as I am aware, vulnerability(high severity) SNYK-JS-TREEKIT-1077068 detected in package tree-kit<0.7.0 is directly referenced by  [email protected], on which your package [email protected] directly depends. As such, this vulnerability can also affect [email protected] via the following path:
[email protected][email protected][email protected](vulnerable version)

Since terminal-kit has released a new patched version [email protected] to resolve this issue ([email protected][email protected](fix version)), then this vulnerability patch can be automatically propagated into your project only if you update your lockfile. The following is your new dependency path :
[email protected][email protected][email protected](vulnerability fix version).

dependency path

A warm tip.
Best regards,
^_^

No examples with --variablesJSON

Hello,

I am having some difficulty passing a json object to my insert_one mutation using the --variablesJSON or -n flag on the command line I was unable to find an example on the usage of this flag.

Is it possible to have an example on the correct way to pass json object variables?

This is my mutation:
mutation addPing($data: json) { insert_response_time_one(object: {data: $data}) { data } }

This is my variable:
{ "data": { "rtt_max": 96.19, "rtt_mdev": 0.0, "packet_loss_count": 0, "packet_loss_rate": 0.0, "packet_duplicate_count": 0, "packet_receive": 1, "packet_duplicate_rate": 0.0, "packet_transmit": 1, "rtt_avg": 96.19, "destination": "8.8.8.8", "rtt_min": 96.19 } }

Is a 1.0.0 release imminent?

#63 has some great stuff we really need (it upgrades some dependencies from versions with licensing challenges to versions without) - I also saw the version increased to 1.0.0.

I know it was only just merged, but is there a 1.0.0 release to npm coming soon?

/cc @wawhal

Update graphql to latest version

Hi,

when I want to use your library and graphql inside firebase functions, I have to use graphql version 15.4.0 only. Otherwise firebase functions fails:

image

Can you update your deps to latest?

Thx

TypeScript types

Is anyone able to add TypeScript types directly to this library? Are PRs requested? I cannot find any on DefinitelyTyped via @types/graphqurl.

[FEATURE REQUEST] allow basic REPL like scripting

Hey there, congrats for gq, it's really an awesome tool.

Today thinking about the possibilities of gq, I was dreaming with the idea of allowing some sort of basic scripting. A very basic example of what I'd like to do in gq would be something like this:

gql> let repo = query {
  repositories(ref: "foo/foo")
} <CR>

mutation {
  createIssue(ref: "$repo.ref") {
   url
  }
} <CR>

# get the URL of the repo from the mutation response.

The idea would be that without too much complexity, have the ability of wiring some javascript code to prototype a simple flow of calling multiple graphql queries and mutations.

thoughts?

support gql-parsed strings as query

Right now query in the nodejs api is just a string. we should support gql-parsed strings too, so that if they are exported elsewhere, it can be used directly.

import gql from 'graphql-tag';

export const GRAPHQL_QUERY=gql`
  query {
    something {
      anotherthing
    }
  }
`;

Suggestions

  • Remove -e
  • Hit enter to execute query if the query is complete
  • Hit esc to hide current suggestion bar and bring it back on tab
  • Instead of last space use last ![A-Z,a-z,_,1-9]

[bug] subscription not working with Authorization header

Without Authorization header (and server auth disabled), it works as expected:

[15:41:23] vagrant: tmp $ graphqurl http://localhost:4000 -q 'subscription {ottRightCreated {right { id } } }'
@oclif/config reading core plugin /usr/local/lib/node_modules/graphqurl +0ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/package.json +0ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/oclif.manifest.json +1ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/.oclif.manifest.json +1ms
@oclif/config reading user plugins pjson /home/vagrant/.local/share/graphqurl/package.json +0ms
@oclif/config loadJSON /home/vagrant/.local/share/graphqurl/package.json +1ms
@oclif/config config done +0ms
gq init version: @oclif/[email protected] argv: [ 'http://localhost:4000', '-q', 'subscription {ottRightCreated {right { id } } }' ] +0ms
Executing query... event received
{
"data": {
"ottRightCreated": {
"right": {
"id": "ck8on7hw606vj0712rw45zxj5"
}
}
}
}
Waiting... \u28f7
^C
[15:42:04] vagrant: tmp $

Once server auth is enabled, adding the auth header works with queries

[15:44:09] vagrant: tmp $ graphqurl http://localhost:4000 -H 'Authorization: Bearer eyJraWQiOiJ0UXhVR0pDWVNyS0dNOTBSMDlCQUIzSUttVzBFMmJ1RnFRakdZTFk1V3JJIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULkpYUjB5cC1fQWxCZkRBOE4wRy01MldGV09kMGNvU3VFcnFEVHBjTWltZ2siLCJpc3MiOiJodHRwczovL2hhcm1vbmljaW5jLXZvcy5va3RhcHJldmlldy5jb20vb2F1dGgyL2F1c2Zqc2I0bjl4YUhSSVJRMGg3IiwiYXVkIjoiVk9TIFNjaGVkdWxlciIsImlhdCI6MTU4NjE1OTkyOCwiZXhwIjoxNTg2MjQ2MzI4LCJjaWQiOiIwb2Fmamw1cHp1VUJybFZtVjBoNyIsInNjcCI6WyJkZWZhdWx0Il0sInN1YiI6IjBvYWZqbDVwenVVQnJsVm1WMGg3In0.fhCCl3LnbO23PP3eTRKfHM8jGf9lNfcBGRuzfmygX99MJzMejKrhcz5BQUiMYRnibrJgUCYAvgt6vYRO-99yj8TJ4jddij6GxeyhHQwIzTLLhj745KRf-3l1Mu8roSYBgE76LL9PA5vyxn5WBhlFofPLr7Y0pszzXB4dFee1Kb6Fy3ghFqqodKYV_6fBsdMc2yZH-JLGpucuYIWK_DQ_jz0GKg5Xs48-hIJlB2IDn9lf_v6kPDp5ItmTeipxOPF8YcapWWQvBduoI1rUrIX1PbuDpMgYcNc9s3r18Qc8rqAlqRNCr-Eq0YyXG2eCGQ7w3PkpaWe8KfIGU2FEPRWjEA' -q 'query {envAll {backendVersion}}'
@oclif/config reading core plugin /usr/local/lib/node_modules/graphqurl +0ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/package.json +0ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/oclif.manifest.json +2ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/.oclif.manifest.json +0ms
@oclif/config reading user plugins pjson /home/vagrant/.local/share/graphqurl/package.json +0ms
@oclif/config loadJSON /home/vagrant/.local/share/graphqurl/package.json +1ms
@oclif/config config done +0ms
gq init version: @oclif/[email protected] argv: [ 'http://localhost:4000', '-H', 'Authorization: Bearer eyJraWQiOiJ0UXhVR0pDWVNyS0dNOTBSMDlCQUIzSUttVzBFMmJ1RnFRakdZTFk1V3JJIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULkpYUjB5cC1fQWxCZkRBOE4wRy01MldGV09kMGNvU3VFcnFEVHBjTWltZ2siLCJpc3MiOiJodHRwczovL2hhcm1vbmljaW5jLXZvcy5va3RhcHJldmlldy5jb20vb2F1dGgyL2F1c2Zqc2I0bjl4YUhSSVJRMGg3IiwiYXVkIjoiVk9TIFNjaGVkdWxlciIsImlhdCI6MTU4NjE1OTkyOCwiZXhwIjoxNTg2MjQ2MzI4LCJjaWQiOiIwb2Fmamw1cHp1VUJybFZtVjBoNyIsInNjcCI6WyJkZWZhdWx0Il0sInN1YiI6IjBvYWZqbDVwenVVQnJsVm1WMGg3In0.fhCCl3LnbO23PP3eTRKfHM8jGf9lNfcBGRuzfmygX99MJzMejKrhcz5BQUiMYRnibrJgUCYAvgt6vYRO-99yj8TJ4jddij6GxeyhHQwIzTLLhj745KRf-3l1Mu8roSYBgE76LL9PA5vyxn5WBhlFofPLr7Y0pszzXB4dFee1Kb6Fy3ghFqqodKYV_6fBsdMc2yZH-JLGpucuYIWK_DQ_jz0GKg5Xs48-hIJlB2IDn9lf_v6kPDp5ItmTeipxOPF8YcapWWQvBduoI1rUrIX1PbuDpMgYcNc9s3r18Qc8rqAlqRNCr-Eq0YyXG2eCGQ7w3PkpaWe8KfIGU2FEPRWjEA', '-q', 'query {envAll {backendVersion}}' ] +0ms
Executing query... done
{
"data": {
"envAll": {
"backendVersion": "465",
"__typename": "EnvPayload"
}
}
}
[15:44:46] vagrant: tmp $

But fail with subscription

[15:44:46] vagrant: tmp $ graphqurl http://localhost:4000 -H 'Authorization: Bearer eyJraWQiOiJ0UXhVR0pDWVNyS0dNOTBSMDlCQUIzSUttVzBFMmJ1RnFRakdZTFk1V3JJIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULkpYUjB5cC1fQWxCZkRBOE4wRy01MldGV09kMGNvU3VFcnFEVHBjTWltZ2siLCJpc3MiOiJodHRwczovL2hhcm1vbmljaW5jLXZvcy5va3RhcHJldmlldy5jb20vb2F1dGgyL2F1c2Zqc2I0bjl4YUhSSVJRMGg3IiwiYXVkIjoiVk9TIFNjaGVkdWxlciIsImlhdCI6MTU4NjE1OTkyOCwiZXhwIjoxNTg2MjQ2MzI4LCJjaWQiOiIwb2Fmamw1cHp1VUJybFZtVjBoNyIsInNjcCI6WyJkZWZhdWx0Il0sInN1YiI6IjBvYWZqbDVwenVVQnJsVm1WMGg3In0.fhCCl3LnbO23PP3eTRKfHM8jGf9lNfcBGRuzfmygX99MJzMejKrhcz5BQUiMYRnibrJgUCYAvgt6vYRO-99yj8TJ4jddij6GxeyhHQwIzTLLhj745KRf-3l1Mu8roSYBgE76LL9PA5vyxn5WBhlFofPLr7Y0pszzXB4dFee1Kb6Fy3ghFqqodKYV_6fBsdMc2yZH-JLGpucuYIWK_DQ_jz0GKg5Xs48-hIJlB2IDn9lf_v6kPDp5ItmTeipxOPF8YcapWWQvBduoI1rUrIX1PbuDpMgYcNc9s3r18Qc8rqAlqRNCr-Eq0YyXG2eCGQ7w3PkpaWe8KfIGU2FEPRWjEA' -q 'subscription {ottRightCreated {right { id } } }'
@oclif/config reading core plugin /usr/local/lib/node_modules/graphqurl +0ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/package.json +0ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/oclif.manifest.json +2ms
@oclif/config loadJSON /usr/local/lib/node_modules/graphqurl/.oclif.manifest.json +0ms
@oclif/config reading user plugins pjson /home/vagrant/.local/share/graphqurl/package.json +0ms
@oclif/config loadJSON /home/vagrant/.local/share/graphqurl/package.json +1ms
@oclif/config config done +0ms
gq init version: @oclif/[email protected] argv: [ 'http://localhost:4000', '-H', 'Authorization: Bearer eyJraWQiOiJ0UXhVR0pDWVNyS0dNOTBSMDlCQUIzSUttVzBFMmJ1RnFRakdZTFk1V3JJIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULkpYUjB5cC1fQWxCZkRBOE4wRy01MldGV09kMGNvU3VFcnFEVHBjTWltZ2siLCJpc3MiOiJodHRwczovL2hhcm1vbmljaW5jLXZvcy5va3RhcHJldmlldy5jb20vb2F1dGgyL2F1c2Zqc2I0bjl4YUhSSVJRMGg3IiwiYXVkIjoiVk9TIFNjaGVkdWxlciIsImlhdCI6MTU4NjE1OTkyOCwiZXhwIjoxNTg2MjQ2MzI4LCJjaWQiOiIwb2Fmamw1cHp1VUJybFZtVjBoNyIsInNjcCI6WyJkZWZhdWx0Il0sInN1YiI6IjBvYWZqbDVwenVVQnJsVm1WMGg3In0.fhCCl3LnbO23PP3eTRKfHM8jGf9lNfcBGRuzfmygX99MJzMejKrhcz5BQUiMYRnibrJgUCYAvgt6vYRO-99yj8TJ4jddij6GxeyhHQwIzTLLhj745KRf-3l1Mu8roSYBgE76LL9PA5vyxn5WBhlFofPLr7Y0pszzXB4dFee1Kb6Fy3ghFqqodKYV_6fBsdMc2yZH-JLGpucuYIWK_DQ_jz0GKg5Xs48-hIJlB2IDn9lf_v6kPDp5ItmTeipxOPF8YcapWWQvBduoI1rUrIX1PbuDpMgYcNc9s3r18Qc8rqAlqRNCr-Eq0YyXG2eCGQ7w3PkpaWe8KfIGU2FEPRWjEA', '-q', 'subscription {ottRightCreated {right { id } } }' ] +0ms
Executing query... error
^C
[15:45:57] vagrant: tmp $

How to use gq with mutation and json input file

Hello, I found the gq very usefull, but I'm stil looking for the right syntax how to implement a gq with a mutation and a json input file for the variables.

mutation looks like this:

queryFile:

mutation createRepository($input: CreateRepositoryInput!) {
createRepository(input: $input) {
clientMutationId
}
}

variableFile:

{
"input": {
"name" : "create-testrepo",
"visibility": "INTERNAL",
"description": "create test repository",
"ownerId": "xxxxxxxxxxxxxxxxxxxxx",
"teamId": "xxxxxxxxxxxxxxxxxx",
"hasIssuesEnabled": false,
"hasWikiEnabled": false
}
}

When I use this on the command line I get an error.

gq https://api.github.com/graphql -H "authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxx" -H "content-type: application/json" --variableFile='./repodata' --queryFile='./query.gql

» Error: cannot parse header '--variableFile='./repodata'' (multiple ':')

Please advice how to use.

Prefer 'operation' to 'query'

Per the docs

The operation type is either query, mutation, or subscription and describes what type of operation you're intending to do.

However many places in the README, and the library itself conflate 'query' with 'operation'. For example:


Under More Examples we see:

const { query } = require('graphqurl');

query(
  {
    query: `
      mutation ($id_insert_input: String!, $column_insert_input: String!) {

And later:

query(
  {
    query: 'subscription { table { column } }',

Under CLI we see:

gq \
     [snip]
     --variableFile='./queryVariables.json' \
     --queryFile='./query.gql

... but there is nothing to stop './query.gql containing a mutation.


In the code itself there is a red flag here:

if (queryType === 'query') {

} else if (queryType === 'mutation') {

} else if (queryType === 'subscription') {

⬆️ per the doc linked at the start of this issue I propose this should definitely be operationType.


Would you accept a PR to:

  1. Change the README to prefer 'operation' to 'query'.

  2. Rename query.js to operation.js, and:
    Re-export operation as query (to prevent API breaking change) in

    module.exports = {
    query,

  3. Add --operationFile to the CLI as an alias of --queryFile

Docker image

Hi,
Would you be open to distributing this as a Docker image?

It would help making this more portable and running it with it's right dependencies in environments that don't necessarily have NPM/Node/etc.

Proper error message when graphql endpoint is wrong

When the graphql server endpoint is wrong, then the following error is encountered. A better error message is expected.

For e.g in the below, the correct url should have been http://localhost:8080/graphql :

graphqurl-bad-endpoint

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.