UNPKG

@graphql-hive/cli

Version:

A CLI util to manage and control your GraphQL Hive

195 lines 7.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.graphqlRequest = graphqlRequest; const tslib_1 = require("tslib"); const colors_1 = tslib_1.__importDefault(require("colors")); const graphql_1 = require("graphql"); const core_1 = require("@graphql-hive/core"); const core_2 = require("@oclif/core"); const config_1 = require("./helpers/config"); class BaseCommand extends core_2.Command { get userConfig() { if (!this._userConfig) { throw new Error('User config is not initialized'); } return this._userConfig; } async init() { await super.init(); this._userConfig = new config_1.Config({ // eslint-disable-next-line no-process-env filepath: process.env.HIVE_CONFIG, rootDir: process.cwd(), }); const { args, flags } = await this.parse({ flags: this.ctor.flags, baseFlags: super.ctor.baseFlags, args: this.ctor.args, strict: this.ctor.strict, }); this.flags = flags; this.args = args; } success(...args) { this.log(colors_1.default.green('✔'), ...args); } fail(...args) { this.log(colors_1.default.red('✖'), ...args); } info(...args) { this.log(colors_1.default.yellow('ℹ'), ...args); } infoWarning(...args) { this.log(colors_1.default.yellow('⚠'), ...args); } bolderize(msg) { const findSingleQuotes = /'([^']+)'/gim; const findDoubleQuotes = /"([^"]+)"/gim; return msg .replace(findSingleQuotes, (_, value) => colors_1.default.bold(value)) .replace(findDoubleQuotes, (_, value) => colors_1.default.bold(value)); } maybe({ key, env, args, }) { if (args[key] != null) { return args[key]; } // eslint-disable-next-line no-process-env if (env && process.env[env]) { // eslint-disable-next-line no-process-env return process.env[env]; } return undefined; } /** * Get a value from arguments or flags first, then from env variables, * then fallback to config. * Throw when there's no value. * * @param key * @param args all arguments or flags * @param defaultValue default value * @param message custom error message in case of no value * @param env an env var name */ ensure({ key, args, legacyFlagName, defaultValue, message, env, }) { if (args[key] != null) { return args[key]; } if (legacyFlagName && args[legacyFlagName] != null) { return args[legacyFlagName]; } // eslint-disable-next-line no-process-env if (env && process.env[env]) { // eslint-disable-next-line no-process-env return process.env[env]; } const userConfigValue = this._userConfig.get(key); if (userConfigValue != null) { return userConfigValue; } if (defaultValue) { return defaultValue; } if (message) { throw new core_2.Errors.CLIError(message); } throw new core_2.Errors.CLIError(`Missing "${String(key)}"`); } cleanRequestId(requestId) { return requestId ? requestId.split(',')[0].trim() : undefined; } registryApi(registry, token) { const requestHeaders = { Authorization: `Bearer ${token}`, 'graphql-client-name': 'Hive CLI', 'graphql-client-version': this.config.version, }; return graphqlRequest({ endpoint: registry, additionalHeaders: requestHeaders, version: this.config.version, debug: this.flags.debug, }); } handleFetchError(error) { var _a, _b, _c, _d, _e; if (typeof error === 'string') { return this.error(error); } if (error instanceof Error) { if (isClientError(error)) { const errors = (_a = error.response) === null || _a === void 0 ? void 0 : _a.errors; if (Array.isArray(errors) && errors.length > 0) { return this.error(errors[0].message, { ref: this.cleanRequestId((_c = (_b = error.response) === null || _b === void 0 ? void 0 : _b.headers) === null || _c === void 0 ? void 0 : _c.get('x-request-id')), }); } return this.error(error.message, { ref: this.cleanRequestId((_e = (_d = error.response) === null || _d === void 0 ? void 0 : _d.headers) === null || _e === void 0 ? void 0 : _e.get('x-request-id')), }); } return this.error(error); } return this.error(JSON.stringify(error)); } async require(flags) { if (flags.require && flags.require.length > 0) { await Promise.all(flags.require.map(mod => Promise.resolve(`${require.resolve(mod, { paths: [process.cwd()] })}`).then(s => tslib_1.__importStar(require(s))))); } } } BaseCommand.baseFlags = { debug: core_2.Flags.boolean({ default: false, summary: 'Whether debug output for HTTP calls and similar should be enabled.', }), }; exports.default = BaseCommand; class ClientError extends Error { constructor(message, response) { super(message); this.response = response; } } function isClientError(error) { return error instanceof ClientError; } function graphqlRequest(config) { var _a; const requestHeaders = Object.assign(Object.assign({ 'Content-Type': 'application/json', Accept: 'application/json' }, (config.version ? { 'User-Agent': `hive-cli/${config.version}` } : {})), ((_a = config.additionalHeaders) !== null && _a !== void 0 ? _a : {})); // const isDebug = this.flags.debug; const isDebug = config.debug === true; return { async request(args) { const response = await core_1.http.post(config.endpoint, JSON.stringify({ query: typeof args.operation === 'string' ? args.operation : (0, graphql_1.print)(args.operation), variables: args.variables, }), { logger: { info: (...args) => { if (isDebug) { console.info(...args); } }, error: (...args) => { console.error(...args); }, }, headers: requestHeaders, timeout: args.timeout, }); if (!response.ok) { throw new Error(`Invalid status code for HTTP call: ${response.status}`); } const jsonData = (await response.json()); if (jsonData.errors && jsonData.errors.length > 0) { throw new ClientError(`Failed to execute GraphQL operation: ${jsonData.errors.map(e => e.message).join('\n')}`, { errors: jsonData.errors, headers: response.headers, }); } return jsonData.data; }, }; } //# sourceMappingURL=base-command.js.map