1+ #!/usr/bin/env node
2+ 'use strict' ;
3+ const fs = require ( 'fs' ) ;
4+ const request = require ( 'request' ) ;
5+ const queryObj = { } ;
6+ const program = require ( 'commander' ) ;
7+ const variablesRegex = / v a r i a b l e s ( [ \s \S ] * ) } / gm;
8+
9+ program
10+ . version ( '0.0.1' )
11+ . usage ( '<file> <token>' )
12+ . arguments ( '<file> <token>' )
13+ . action ( function ( file , token ) {
14+ console . log ( "Running query: " + file ) ;
15+ runQuery ( file , token ) ;
16+ } )
17+ . description ( 'Execute specified GraphQL query' ) ;
18+
19+ program . parse ( process . argv ) ;
20+
21+ if ( ! process . argv . slice ( 2 ) . length )
22+ {
23+ console . log ( "Missing query file and/or token argument" ) ;
24+ process . exitCode = 1 ;
25+ }
26+
27+ function runQuery ( file , token ) {
28+
29+ try {
30+ var queryText = fs . readFileSync ( process . argv [ 2 ] , "utf8" ) ;
31+ }
32+ catch ( e ) {
33+ console . log ( "Problem opening query file: " + e . message ) ;
34+ process . exit ( 1 ) ;
35+ }
36+
37+ //If there is a variables section, extract the values and add them to the query JSON object. Otherwise, add and empty object
38+ queryObj . variables = variablesRegex . test ( queryText ) ? JSON . parse ( queryText . match ( variablesRegex ) [ 0 ] . split ( "variables " ) [ 1 ] ) : { }
39+ //Remove the variables section from the query text, whether it exists or not
40+ queryObj . query = queryText . replace ( variablesRegex , '' ) ;
41+
42+ request ( {
43+ url : "https://api.github.com/graphql"
44+ , method : "POST"
45+ , headers : {
46+ 'authorization' : 'bearer ' + token
47+ , 'content-type' : 'application/json'
48+ , 'user-agent' : 'octoweenie'
49+ }
50+ , json : true
51+ , body : queryObj
52+ //,body: testQuery
53+ } , function ( error , response , body ) {
54+ console . log ( JSON . stringify ( body , null , 2 ) ) ;
55+ } ) ;
56+ } ;
0 commit comments