Skip to content

Commit 29479fa

Browse files
committed
WIP to get this cleaned up
1 parent 70daed7 commit 29479fa

11 files changed

+2627
-259
lines changed

.eslintignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

.eslintrc.json

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"env": {
3+
"commonjs": true,
4+
"es6": true
5+
},
6+
"extends": ["airbnb-base", "plugin:import/typescript", "plugin:@typescript-eslint/recommended", "plugin:jsdoc/recommended"],
7+
"parser": "@typescript-eslint/parser",
8+
"plugins": ["jsdoc"],
9+
"rules": {
10+
"import/extensions": 0
11+
}
12+
}

lib/api.ts

+30-32
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
/* eslint-disable no-console */
2-
import * as _ from "lodash";
2+
import * as _ from 'lodash';
33
import * as queryString from 'query-string';
4-
import { globalCommandLineOptions } from "./cli-utils";
5-
import { argvToApiEnv, getApiEnvCommandLineOptions, ApiEnv, fixApiEnvKey } from "./apiEnv";
6-
import { runQuery } from "./run-query";
7-
import config from "./config";
4+
import * as chalk from 'chalk';
5+
import { globalCommandLineOptions } from './cli-utils';
6+
import {
7+
argvToApiEnv, getApiEnvCommandLineOptions, ApiEnv, fixApiEnvKey,
8+
} from './apiEnv';
9+
import runQuery from './run-query';
10+
import config from './config';
811

912
const makeUsageString = (toolName: string) => `This tool has a lot of options, here are some examples:
1013
@@ -19,10 +22,17 @@ ${toolName} --local /v1/endpoint param1=X param2=Y
1922
2023
${toolName} --local /v1/endpoint --env=staging param1=X param2=Y
2124
would run against localhost, but look for STAGING_API_KEY
22-
`
23-
24-
function parseArgv() {
25-
let yargs = require("yargs");
25+
`;
26+
27+
/**
28+
* Return parsed commandline arguments
29+
*
30+
* @returns {any} the parsed commandline arguments
31+
*/
32+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
33+
function parseArgv(): any {
34+
// eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
35+
const yargs = require('yargs');
2636

2737
yargs.usage(makeUsageString(process.argv[0]));
2838

@@ -42,27 +52,13 @@ const argv = parseArgv();
4252
let endpoint = argv._[0];
4353

4454
if (!endpoint) {
45-
console.error("This tool requires an api endpoint to be specified");
55+
console.error('This tool requires an api endpoint to be specified');
4656
process.exit(1);
4757
}
4858

49-
function printResponse(response: any) {
50-
console.log(response);
51-
52-
if (typeof response === "object") {
53-
if (process.stdout.isTTY) {
54-
console.dir(response, { depth: null, colors: true });
55-
} else {
56-
console.log(JSON.stringify(response, null, 4));
57-
}
58-
} else {
59-
console.log(response);
60-
}
61-
}
62-
6359
let apiEnv: ApiEnv;
6460

65-
let params: any = {};
61+
let params: Record<string, string> = {};
6662

6763
if (argv._.length === 1 && argv._[0].startsWith('http')) {
6864
// The user just specified a radar url, they probably just want to run it with the
@@ -77,27 +73,29 @@ if (argv._.length === 1 && argv._[0].startsWith('http')) {
7773
if (!apiEnv.keyEnv) {
7874
_.forEach(config.hosts, (hostEntry) => {
7975
if (url.host === hostEntry.host) {
80-
apiEnv.keyEnv = hostEntry.keyEnv
76+
apiEnv.keyEnv = hostEntry.keyEnv;
8177
}
82-
})
78+
});
8379
}
8480

8581
fixApiEnvKey(apiEnv);
8682

8783
endpoint = url.pathname;
88-
params = queryString.parse(url.search);
84+
params = queryString.parse(url.search) as Record<string, string>;
8985
} else {
9086
apiEnv = argvToApiEnv(argv);
9187

9288
argv._.slice(1).forEach((datum: string) => {
93-
if (!datum.includes("=")) {
89+
if (!datum.includes('=')) {
9490
console.error(`data argument ${datum} did not have =, exiting`);
9591
process.exit(1);
9692
}
97-
const key = datum.split("=")[0];
98-
const value = datum.split("=")[1];
93+
const key = datum.split('=')[0];
94+
const value = datum.split('=')[1];
9995
params[key] = value;
10096
});
10197
}
10298

103-
runQuery(apiEnv, { params, method: argv.method, endpoint, verbose: true }).then(({ data }) => printResponse(data));
99+
runQuery(apiEnv, {
100+
params, method: argv.method, endpoint, verbose: true,
101+
}).then(({ data }) => console.dir(data, { depth: null, colors: chalk.level > 0 }));

lib/apiEnv.ts

+45-28
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,44 @@
1-
import * as _ from "lodash";
2-
import logger from "./logger";
3-
import { ConfigHostEntry } from "./config";
4-
import config from "./config";
5-
import { failedExit } from "./cli-utils";
1+
import * as _ from 'lodash';
2+
import logger from './logger';
3+
import config, { ConfigHostEntry } from './config';
4+
5+
import { failedExit } from './cli-utils';
6+
7+
// eslint-disable-next-line @typescript-eslint/no-var-requires
8+
require('dotenv').config();
69

710
const apiEnvCommandLineOptions: Record<string, any> = {
811
host: {
9-
type: "string",
10-
description: "Host/port - will override --env",
12+
type: 'string',
13+
description: 'Host/port - will override --env',
1114
},
1215
protocol: {
13-
choices: ["http", "https"],
16+
choices: ['http', 'https'],
1417
description:
15-
"What protocol to use (if not specified in url), defaults to http for local, https otherwise",
18+
'What protocol to use (if not specified in url), defaults to http for local, https otherwise',
1619
},
1720
key: {
18-
type: "string",
19-
description: `Authorization key, if not specified will try to find one in the env, in .env or, in local mode, directly in mongo`,
21+
type: 'string',
22+
description: 'Authorization key, if not specified will try to find one in the env, in .env or, in local mode, directly in mongo',
2023
},
2124
};
2225

26+
/**
27+
*
28+
*/
2329
export function getApiEnvCommandLineOptions(): Record<string, any> {
2430
if (config.keyTypes) {
2531
apiEnvCommandLineOptions.key_type = {
2632
choices: config.keyTypes,
2733
default: config.keyTypes[0],
28-
description: "authorization key type to use",
34+
description: 'authorization key type to use',
2935
};
3036
}
3137

3238
if (config.hosts) {
3339
apiEnvCommandLineOptions.env = {
3440
choices: [..._.keys(config.hosts), ..._.flatMap(config.hosts, (v) => v.aliases || [])],
35-
description: `api host to talk to`,
41+
description: 'api host to talk to',
3642
};
3743

3844
_.forEach(config.hosts, (hostEntry: ConfigHostEntry, key: string) => {
@@ -53,44 +59,55 @@ export interface ApiEnv {
5359
keyType?: string;
5460
}
5561

56-
type KeyParams = Pick<ApiEnv, "keyEnv" | "keyType">;
62+
type KeyParams = Pick<ApiEnv, 'keyEnv' | 'keyType'>;
5763

64+
/**
65+
* @param root0
66+
* @param root0.keyEnv
67+
* @param root0.keyType
68+
*/
5869
function findKey({ keyEnv, keyType }: KeyParams): string {
59-
require("dotenv").config();
60-
61-
const env_variable_name = [keyEnv, keyType, "API_KEY"]
70+
const envVariableName = [keyEnv, keyType, 'API_KEY']
6271
.filter((s) => !_.isEmpty(s))
63-
.join("_")
72+
.join('_')
6473
.toUpperCase();
65-
logger.info(`Looking for key in env ${env_variable_name}`);
66-
const key = process.env[env_variable_name];
74+
logger.info(`Looking for key in env ${envVariableName}`);
75+
const key = process.env[envVariableName];
6776
if (!key) {
68-
failedExit(`No key found for ${env_variable_name} in .env and --key not specified`);
77+
failedExit(`No key found for ${envVariableName} in .env and --key not specified`);
6978
}
7079
return key;
7180
}
7281

73-
export function fixApiEnvKey(apiEnv: Partial<ApiEnv>) {
74-
apiEnv.key =
75-
apiEnv.key ||
76-
findKey({ keyEnv: apiEnv.keyEnv || "", keyType: apiEnv.keyType || config.keyTypes?.[0] });
82+
/**
83+
* @param apiEnv
84+
*/
85+
export function fixApiEnvKey(apiEnv: Partial<ApiEnv>): void {
86+
// eslint-disable-next-line no-param-reassign
87+
apiEnv.key = apiEnv.key
88+
|| findKey({ keyEnv: apiEnv.keyEnv || '', keyType: apiEnv.keyType || config.keyTypes?.[0] });
7789
}
7890

91+
/**
92+
* @param argv
93+
*/
7994
export function argvToApiEnv(argv: any): ApiEnv {
8095
let apiEnv: Partial<ApiEnv> = _.clone(argv);
8196

8297
let aliasedHostEntry: ConfigHostEntry;
8398
_.forEach(config.hosts, (hostEntry: ConfigHostEntry, key: string) => {
8499
if (argv[key]) {
85100
if (aliasedHostEntry) {
86-
throw new Error(`Can only specify one of ${_.keys(config.hosts).join(",")}`);
101+
throw new Error(`Can only specify one of ${_.keys(config.hosts).join(',')}`);
87102
}
88103

89104
if (hostEntry.takesArg) {
90105
const toReplace = key.toUpperCase();
106+
// eslint-disable-next-line no-param-reassign
91107
hostEntry.host = hostEntry.host.replace(toReplace, argv[key]);
92108
}
93109

110+
// eslint-disable-next-line no-param-reassign
94111
hostEntry.keyEnv = hostEntry.keyEnv || key;
95112

96113
aliasedHostEntry = hostEntry;
@@ -104,10 +121,10 @@ export function argvToApiEnv(argv: any): ApiEnv {
104121
};
105122
}
106123

107-
if (apiEnv.host.startsWith("http")) {
124+
if (apiEnv.host.startsWith('http')) {
108125
const url = new URL(apiEnv.host);
109126
apiEnv.host = url.host;
110-
apiEnv.protocol = url.protocol.replace(":", "");
127+
apiEnv.protocol = url.protocol.replace(':', '');
111128
}
112129

113130
fixApiEnvKey(apiEnv);

lib/cli-utils.ts

+9-6
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
1+
/**
2+
* @param msg
3+
*/
14
export function failedExit(msg: string) {
25
console.error(msg);
36
process.exit(1);
47
}
58

69
export const globalCommandLineOptions = {
710
method: {
8-
choices: ["GET", "POST", "PUT"],
9-
default: "GET",
10-
description: "what http method to use",
11+
choices: ['GET', 'POST', 'PUT'],
12+
default: 'GET',
13+
description: 'what http method to use',
1114
},
1215
color: {
13-
type: "boolean",
14-
description: "turns on/off colorized output, defaults to true for stdin, false for redirected output"
16+
type: 'boolean',
17+
description: 'turns on/off colorized output, defaults to true for stdin, false for redirected output',
1518
},
16-
};
19+
};

0 commit comments

Comments
 (0)