Skip to content

Commit

Permalink
op refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
openhoat committed May 29, 2017
1 parent a8e5ba1 commit ed9fc0e
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 112 deletions.
25 changes: 12 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ $ grql --help
Example of query : get a Giffy image from GraphQLHub

```
$ grql '{ giphy { random(tag:"superbike") { url } } }'
$ grql query '{ giphy { random(tag:"superbike") { url } } }'
```

Result :
Expand All @@ -51,7 +51,7 @@ Result :
Use YAML output format :

```
$ grql '{ giphy { random(tag:"superbike") { url } } }' -y
$ grql query '{ giphy { random(tag:"superbike") { url } } }' -y
```

Result :
Expand All @@ -75,49 +75,49 @@ environnements :
Specify your own graphql server :

```
$ grql --baseurl https://mysupergraphql.server/graphql "{ myquery(foo: "bar") }"
$ grql --baseurl https://mysupergraphql.server/graphql query "{ myquery(foo: "bar") }"
```

Save own graphql server to a named configuration :

```
$ grql --baseurl https://mysupergraphql.server/graphql \
--conf mysuperserver --save \
'{ myquery(foo: "bar") }'
query '{ myquery(foo: "bar") }'
```

Save a query :

```
$ grql --query myquery '{ myquery(foo: "bar") }' --save
$ grql --alias myquery query '{ myquery(foo: "bar") }' --save
```

Next, to replay the query :

```
$ grql --query myquery
$ grql --alias myquery query
```

### Query

The query content is passed either by command argument :

```
$ grql '{ contact { username: "jdoe"} }'
$ grql query '{ contact { username: "jdoe"} }'
```

or by stdin :

```
$ echo '{ contact { username: "jdoe"} }' | grql
$ echo '{ contact { username: "jdoe"} }' | grql query
```

### Fragments

Save a new fragment :

```
$ cat << EOM | grql -f gifInfo -s
$ cat << EOM | grql fragment gifInfo -s
fragment on GiphyGIFData {
id
url
Expand All @@ -133,15 +133,15 @@ EOM
Use it in a query :

```
$ grql '{ giphy { random(tag:"superbike") { ...${gifInfo} } } }' -y
$ grql query '{ giphy { random(tag:"superbike") { ...${gifInfo} } } }' -y
```

### Mutations

Change my details with my contacts graphql server :

```
$ cat << EOM | grql -e contacts -m
$ cat << EOM | grql -e contacts mutate
{
patchMe(input: {firstName: "John", lastName: "Doe"}) {
id
Expand All @@ -160,10 +160,9 @@ EOM
- dryrun : does not finally execute the query
- env : show current environment or select the specified environment
- nocolor : disable color mode
- query : select a query to save or play
- alias : select an alias to save or play
- save : save options to current environment
- yaml : enable YAML output format
- mutation : execute a mutation instead of a query
- var : inject a variable (format key=value)

Enjoy!
39 changes: 12 additions & 27 deletions lib/cmd.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@ const config = require('./config')
const { __ } = require('./i18n')

exports = module.exports = yargs
.usage(util.format(__('Usage') + ': %s [%s] [%s]',
.usage(util.format(__('Usage') + ': %s [%s] [%s] [%s]',
chalk.bold(config.cmdName),
chalk.cyan.bold('options'),
chalk.bold.yellow('data')
chalk.bold.yellow(__('command')),
chalk.bold.yellow(__('data')),
chalk.cyan.bold('options')
))
.wrap(120)
.command('query', __('make a graphql query'))
.command('mutate', __('make a graphql mutation'))
.command('fragment', __('create a graphql fragment'))
.command('schema', __('fetch graphql schema'))
.options({
'env': {
description: chalk.cyan.bold(__('select environment')),
Expand Down Expand Up @@ -40,15 +45,15 @@ exports = module.exports = yargs
}
})
.options({
'query': {
description: chalk.cyan.bold(__('get or set query name')),
'alias': {
description: chalk.cyan.bold(__('use or set query alias')),
type: 'string',
alias: 'q',
alias: 'a',
}
})
.options({
'save': {
description: chalk.cyan.bold(__('persists options to file (%s)', config.configFile)),
description: chalk.cyan.bold(__('save options to file (%s)', config.configFile)),
type: 'boolean',
alias: 's',
}
Expand Down Expand Up @@ -91,25 +96,5 @@ exports = module.exports = yargs
type: 'string'
}
})
.options({
'fragment': {
description: chalk.cyan.bold(__('create a fragment')),
type: 'string',
alias: 'f',
}
})
.options({
'mutation': {
description: chalk.cyan.bold(__('send graphql mutation')),
type: 'boolean',
alias: 'm',
}
})
.options({
'schema': {
description: chalk.cyan.bold(__('show server schema')),
type: 'string',
}
})
.example(`${config.cmdName} '{ giphy { random(tag:"superbike") { url } } }'`)
.epilogue(__('for more information, contact'))
154 changes: 90 additions & 64 deletions lib/grql.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@ const grql = (...args) => Promise.resolve()
const argv = cmd.parse(args)
return Promise.resolve()
.then(() => {
const command = argv._[0]
if (argv.nocolor) {
chalk.enabled = false
}
const renderOpts = {yaml: argv.yaml, noColor: argv.nocolor}
if (argv.help) {
return cmd.showHelp(help => {
h.print.err(help)
Expand All @@ -57,79 +59,57 @@ const grql = (...args) => Promise.resolve()
)
const envName = config.settings.defaultEnv
if (argv.verbose) {
h.print.out(chalk.gray(`using environment '${envName}'`))
h.print.out(chalk.gray(__(`using environment %s`, envName)))
}
_.set(config, `settings.env.${envName}`, _.get(config, `settings.env.${envName}`, {}))
const env = config.settings.env[envName]
Object.assign(env, _.pickBy(_.pick(argv, config.envFields), _.identity))
if (argv.verbose) {
h.print.out(chalk.gray('environment details :'))
h.render(_.omit(env, 'password'), {yaml: argv.yaml, noColor: argv.nocolor})
}
if (typeof argv.schema !== 'undefined') {
return fetchSchema(env.baseurl)
.then(data => {
const schema = JSON.parse(data)
const key = ['data', '__schema']
if (argv.schema) {
key.push(argv.schema.split('.'))
}
h.render(_.get(schema, key.join('.')), {yaml: argv.yaml, noColor: argv.nocolor})
})
const aliasMap = {query: 'queries', 'mutate': 'mutations'}
const aliasKey = aliasMap[command]
const data = (function loadData() {
let data = argv._[1] ||
config.stdinContent ||
(aliasKey && _.get(config.settings, `${aliasKey}.${argv.alias}`))
if (aliasKey) {
data = (function loadFragment(data) {
const fragmentRe = /(\$\{[^\}]+\})/g
const fragmentMatch = data.match(fragmentRe) || []
return fragmentMatch.reduce((data, fragmentRef) => {
const fragmentNameMatch = fragmentRef.match(/\$\{([^\}]+)\}/)
const fragmentName = fragmentNameMatch && fragmentNameMatch[1]
const fragment = fragmentName &&
client.createFragment(_.get(config.settings, `fragments.${fragmentName}`))
return fragment ? data.replace(fragmentRef, fragment) : data
}, data)
})(data)
}
return data
})()
if (argv.alias && aliasKey) {
_.set(config.settings, `${aliasKey}.${argv.alias}`, data)
}
const data = argv._[0] || config.stdinContent || (argv.query && _.get(config.settings, `queries.${argv.query}`))
const transportOpt = {}
if (env.user) {
_.set(transportOpt, 'headers.Authorization', basicAuthHeader(env.user, env.password))
}
const transport = new Transport(env.baseurl, transportOpt)
const client = new Lokka({transport})
if (argv.fragment) {
_.set(config.settings, `fragments.${argv.fragment}`, data)
} else if (argv.query) {
if (data) {
_.set(config.settings, `queries.${argv.query}`, data)
} else {
throw new Error(__("Error: query '%s' not found", argv.query))
}
}
if (argv.verbose) {
h.print.out(chalk.gray('request headers :'))
h.render(_.get(transport, '_httpOptions.headers'), {yaml: argv.yaml, noColor: argv.nocolor})
}
if (argv.save) {
!argv.dryrun && config.save()
h.print.err(chalk.yellow.bold(__('options successfully saved')))
h.print.out(chalk.gray(__('environment details :')))
h.render(_.omit(env, 'password'), renderOpts)
h.print.out(chalk.gray(__('request headers :')))
h.render(_.get(transport, '_httpOptions.headers'), renderOpts)
h.print.out(chalk.gray(__('data :')))
h.render(data, renderOpts)
}
if (!argv.fragment && data) {
const fragmentRe = /(\$\{[^\}]+\})/g
const fragmentMatch = data.match(fragmentRe) || []
const queryData = fragmentMatch.reduce((data, fragmentRef) => {
const fragmentNameMatch = fragmentRef.match(/\$\{([^\}]+)\}/)
const fragmentName = fragmentNameMatch && fragmentNameMatch[1]
const fragment = fragmentName && client.createFragment(_.get(config.settings, `fragments.${fragmentName}`))
return fragment ? data.replace(fragmentRef, fragment) : data
}, data)
if (argv.verbose) {
h.print.out(chalk.gray('data :'))
h.render(queryData, {yaml: argv.yaml, noColor: argv.nocolor})
}
const vars = argv.var && (Array.isArray(argv.var) ? argv.var : [argv.var])
.reduce((vars, item) => {
const match = item.match(/(.*)=(.*)/)
return Object.assign(vars, {[match[1]]: match[2]})
}, {})
if (argv.verbose) {
h.print.out(chalk.gray('variables :'))
h.render(vars, {yaml: argv.yaml, noColor: argv.nocolor})
}
if (argv.dryrun) {
return
}
return client[argv.mutation ? 'mutate' : 'query'](queryData, vars)
.then(result => {
h.render(result, {yaml: argv.yaml, noColor: argv.nocolor})
})
const vars = argv.var && (Array.isArray(argv.var) ? argv.var : [argv.var])
.reduce((vars, item) => {
const match = item.match(/(.*)=(.*)/)
return Object.assign(vars, {[match[1]]: match[2]})
}, {})
if (argv.verbose) {
h.print.out(chalk.gray(__('variables :')))
h.render(vars, renderOpts)
}
if (argv._.length < 1) {
if (typeof argv.env !== 'undefined' && !argv.env) {
Expand All @@ -144,15 +124,61 @@ const grql = (...args) => Promise.resolve()
.join('\n'))
return
}
if (typeof argv.query !== 'undefined' && !argv.query) {
h.print.out(chalk.bold('saved queries :'))
h.render(_.get(config.settings, `queries`), {yaml: argv.yaml, noColor: argv.nocolor})
return
if (typeof argv.alias !== 'undefined' && !argv.alias) {
h.print.out(chalk.bold(__('saved queries :')))
h.render(_.get(config.settings, `queries`), renderOpts)
h.print.out(chalk.bold(__('saved mutations :')))
h.render(_.get(config.settings, `mutations`), renderOpts)
}
if (!argv.save) {
throw new Error(__('Error : missing argument'))
}
}
if (argv.dryrun) {
return
}
return Promise.resolve()
.then(() => {
switch (command) {
case 'schema':
return fetchSchema(env.baseurl)
.then(schemaJSON => {
const schema = JSON.parse(schemaJSON)
const key = ['data', '__schema']
if (data) {
key.push(data.split('.'))
}
h.render(_.get(schema, key.join('.')), renderOpts)
})
case 'fragment':
if (data) {
_.set(config.settings, `fragments.${argv.alias}`, data)
} else {
h.render(_.get(config.settings, 'fragments' + (argv.alias ? `.${argv.alias}` : '')), renderOpts)
}
return
case 'query':
return client.query(data, vars)
.then(result => {
h.render(result, {yaml: argv.yaml, noColor: argv.nocolor})
})
case 'mutate':
return client.query(data, vars)
.then(result => {
h.render(result, renderOpts)
})
default:
if (!argv.save) {
throw new Error(__('Error : unsupported operation'))
}
}
})
.then(() => {
if (argv.save) {
!argv.dryrun && config.save()
h.print.err(chalk.yellow.bold(__('options successfully saved')))
}
})
})
.then(() => {
if (!standalone) {
Expand Down
2 changes: 1 addition & 1 deletion lib/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const h = {
if (yaml) {
h.print.out(h.toPrettyJson(data, noColor))
} else if (typeof data !== 'object') {
h.print.out(data ? chalk.bold(data) : chalk.cyan.bold('empty'))
h.print.out(data ? chalk.bold(data) : chalk.cyan.bold(__('empty')))
} else {
h.print.out(chalk.bold(JSON.stringify(data, null, 2)))
}
Expand Down
12 changes: 11 additions & 1 deletion locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,15 @@
"Error : missing argument": "Error : missing argument",
"set a variable used in query (format : key=value)": "set a variable used in query (format : key=value)",
"create a fragment": "create a fragment",
"send graphql mutation": "send graphql mutation"
"send graphql mutation": "send graphql mutation",
"command": "command",
"data": "data",
"make a graphql query": "make a graphql query",
"empty": "empty",
"using environment %s": "using environment %s",
"environment details :": "environment details :",
"request headers :": "request headers :",
"data :": "data :",
"variables :": "variables :",
"use or set query alias": "use or set query alias"
}
Loading

0 comments on commit ed9fc0e

Please sign in to comment.