-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathapiKey.ts
60 lines (55 loc) · 1.76 KB
/
apiKey.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
import { Argv, CommandBuilder } from 'yargs';
import { oneLine } from 'common-tags';
import config from '../utils/config';
import logger from '../utils/logger';
export const command = 'apiKey <key>';
export const describe = 'set the API key to be used for authenticated requests';
interface ApiKeyArgvOptions {
key: string;
}
interface ApiKeyHandlerOptions {
key: string;
}
export const builder: CommandBuilder<
ApiKeyArgvOptions,
ApiKeyHandlerOptions
> /* istanbul ignore next */ = (yargs): Argv<ApiKeyHandlerOptions> =>
yargs
.positional('key', { type: 'string' })
.demandOption('key')
.check(argv => {
if (!argv.key.length) {
throw new Error('The key argument must not be empty.');
}
return true;
})
.group(['h', 'v'], 'Global Options:').epilog(oneLine`
Please obtain an API key from https://haveibeenpwned.com/API/Key and then
run "pwned apiKey <key>" to configure pwned.
`);
/**
* Stores the user's specified API key to be used for future requests to
* authenticated endpoints.
*
* @param {object} argv the parsed argv object
* @param {string} argv.key the user's API key
* @returns {Promise<void>} the resulting Promise where output is rendered
*/
export const handler = async ({ key }: ApiKeyHandlerOptions): Promise<void> => {
try {
config.set('apiKey', key);
if (config.get('apiKey') === key) {
logger.log(oneLine`
✔ API key saved successfully. It will be used in future requests made
to haveibeenpwned.com services that require authentication.
`);
} else {
throw new Error(oneLine`
✖ API key mismatch: the key read back from config does not match the
key supplied!
`);
}
} catch (err) {
logger.error(err.message);
}
};