-
Notifications
You must be signed in to change notification settings - Fork 114
/
index.ts
100 lines (89 loc) 路 2.59 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
export * from './types'
export * from './utils'
import { join as joinPaths } from 'path'
import { existsSync, readdirSync } from 'fs'
import { CommandObject } from './types'
import { CommandModule, Argv } from 'yargs'
import * as _ from 'lodash'
import * as ora from 'ora'
import * as inquirer from 'inquirer'
import * as npmPaths from 'npm-paths'
import chalk from 'chalk'
import {
getGraphQLProjectConfig,
getGraphQLConfig,
ConfigNotFoundError,
} from 'graphql-config'
import * as dotenv from 'dotenv'
function listPluggings(dir: string): string[] {
return readdirSync(dir)
.filter(moduleName => moduleName.startsWith('graphql-cli-'))
.map(moduleName => joinPaths(dir, moduleName))
}
export function installCommands() {
const plugins = _(npmPaths())
.filter(existsSync)
.map(listPluggings)
.flatten()
.uniq()
.value() as string[]
let yargs = require('yargs')
for (const moduleName of ['./cmds', ...plugins]) {
try {
const cmdModule = require(moduleName)
const cmdModules = Array.isArray(cmdModule) ? cmdModule : [cmdModule]
for (const cmd of cmdModules) {
yargs = yargs.command(wrapCommand(cmd))
}
} catch (e) {
console.log(`Can't load ${moduleName} plugin:` + e.stack)
}
}
return yargs
}
function wrapCommand(commandObject: CommandObject): CommandModule {
const originalHandler = commandObject.handler
commandObject.handler = argv => {
const envPath = argv['dotenv'] || '.env'
dotenv.config({ path: envPath })
const context = {
prompt: inquirer.createPromptModule(),
spinner: ora(),
getProjectConfig() {
if (argv['project']) {
return getGraphQLProjectConfig(process.cwd(), argv['project'])
} else {
return getGraphQLProjectConfig()
}
},
getConfig() {
return getGraphQLConfig()
},
}
let result = new Promise((resolve, reject) => {
try {
resolve(originalHandler(context, argv))
} catch (e) {
reject(e)
}
})
result.catch(e => {
if (context.spinner['enabled']) {
context.spinner.stopAndPersist()
}
// TODO: add debug flag for calltrace
console.log(chalk.red(e.message))
if (e instanceof ConfigNotFoundError) {
console.log(
chalk.yellow(
`\nRun ${chalk.green('graphql init')} to create new .graphqlconfig`,
),
)
}
// FIXME: set non-zero exit code
})
}
return commandObject as CommandModule
}
// Mutation calls "graphql mutation addUser --id 1 --name Test"
// Execute static .graphql files