-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·434 lines (378 loc) · 11.1 KB
/
cli.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#!/usr/bin/env node
import btcValue, {
getSupportedCurrencies,
getPercentageChangeLastHour,
getPercentageChangeLastDay,
getPercentageChangeLastWeek,
setApiKey
} from 'btc-value';
import meow from 'meow';
import {writeFile, promises as fs} from 'node:fs';
import chalk from 'chalk';
import Ora from 'ora';
import logSymbols from 'log-symbols';
import path from 'node:path';
import getSymbolFromCurrency from 'currency-symbol-map';
import {fileURLToPath} from 'node:url';
const spinner = new Ora();
const defaultConfiguration = {
default: 'USD',
quantity: 1,
autorefresh: 15,
apiKey: '',
provider: 'coingecko'
};
const directoryPath = path.dirname(fileURLToPath(import.meta.url));
const configFile = path.join(directoryPath, './config.json');
let config;
try {
config = JSON.parse(await fs.readFile(path.join(directoryPath, './config.json')));
} catch {
// Set the config to the default if its not found in the file
config = defaultConfiguration;
}
let defaultCurrency = config.default;
let {
quantity,
autorefresh,
apiKey, provider
} = config;
// eslint-disable-next-line no-unused-vars
let autorefreshTimer;
const cli = meow(`
Usage
$ btc-value
Options
--key -k Set the API key (Obtain key at: https://coinmarketcap.com/api/)
--decimal -d Print value as decimal
--save -s [code] Set the currency that will be used by default
--currency -c [code] Print the value in another currency
--list -l Print a list of all supported currencies
--quantity -q [number] Print the value of the given quantity
--autorefresh -a [seconds] Automatic refresh printing every x seconds
--percentage -p [h|d|w] Print the percentage change (h = hour, d = day, w = week)
--reset -r Reset the configuration to the default
--provider [cmc|coingecko] Set the currency provider to retrieve Bitcoin values from
Examples
$ btc-value
$ btc-value -k <example-API-key>
$ btc-value -d
$ btc-value -s NOK
$ btc-value -c NOK
$ btc-value -q 2.2
$ btc-value -p h
$ btc-value --provider coingecko
`, {
flags: {
key: {
type: 'string',
alias: 'k'
},
decimal: {
type: 'boolean',
alias: 'd'
},
save: {
type: 'string',
alias: 's'
},
currency: {
type: 'string',
alias: 'c'
},
list: {
type: 'boolean',
alias: 'l'
},
quantity: {
type: 'number',
alias: 'q'
},
autorefresh: {
type: 'number',
alias: 'a'
},
percentage: {
type: 'string',
alias: 'p'
},
reset: {
type: 'boolean',
alias: 'r'
},
provider: {
type: 'string'
}
},
importMeta: import.meta
});
// Search if input currency code matches any in the currency list
async function isValidCurrencyCode(currencyCode) {
// eslint-disable-next-line no-param-reassign
currencyCode = currencyCode.toLowerCase();
let currency;
const supportedCurrencies = await getSupportedCurrencies();
// eslint-disable-next-line no-restricted-syntax
for (const supportedCurrency of supportedCurrencies) {
if (currencyCode === supportedCurrency.toLowerCase()) {
currency = supportedCurrency;
break;
}
}
if (!currency) {
spinner.stop();
console.log(chalk.redBright(`${logSymbols.error} Please choose a valid currency code`));
console.log('Type `btc-value -l` for a list of all valid currencies');
process.exit(1);
}
return currency;
}
// Helper function for printing and stopping the spinner
function printOutput(input) {
spinner.stop();
console.log(input);
}
// Helper function for printing percentage in red and green
function printPercentage(percentage) {
if (percentage.startsWith('-')) {
printOutput(chalk.redBright(percentage));
} else {
printOutput(chalk.green(percentage));
}
}
// Helper function to print error and exit with code 1
function exitError(error) {
spinner.stop();
console.log(chalk.redBright(`${logSymbols.error} ${error}`));
process.exit(1);
}
function saveConfig(newConfig) {
return new Promise((resolve, reject) => {
// Save new config file
writeFile(configFile, newConfig, error => {
if (error) {
reject();
return;
}
resolve();
});
});
}
function convertToTwoDecimals(number) {
// Check if the number is not an integer. If it is not, convert it to two decimals.
if (number % 1 === 0) return number;
return Number.parseFloat(number.toFixed(2));
}
function parseOptions(currencyValue, options) {
let parsedValue = currencyValue;
// Set the new currency value if quantity is provided
if (options.quantity) {
parsedValue *= options.quantity;
}
// If `isDecimal` is false => return an integer
if (!options.isDecimal) {
parsedValue = Number.parseInt(parsedValue, 10);
}
return convertToTwoDecimals(parsedValue);
}
// For calling all functions every time in a timeout with `a` flag
async function checkAllFlags() {
// If `s` flag is set => set currency as default
if (cli.flags.save !== undefined) {
defaultCurrency = await isValidCurrencyCode(cli.flags.save);
const newConfig = JSON.stringify({
default: defaultCurrency,
quantity,
autorefresh,
apiKey,
provider
}, undefined, 4);
const defaultCurrencySymbol = getSymbolFromCurrency(defaultCurrency);
try {
await saveConfig(newConfig);
console.log(chalk.green(`${logSymbols.success} Default currency set to: ${defaultCurrency} (${defaultCurrencySymbol})`));
} catch {
exitError('Something wrong happened, could not save new default currency.');
}
}
let multiplier = 1;
const printAsDecimal = cli.flags.decimal;
if (cli.flags.quantity) {
if (typeof cli.flags.quantity === 'number') {
// Check if quantity is not the same as the old one
if (quantity !== cli.flags.quantity) {
// Save the new value of `quantity`
quantity = cli.flags.quantity;
const newConfig = JSON.stringify({
default: defaultCurrency,
quantity,
autorefresh,
apiKey,
provider
}, undefined, 4);
try {
await saveConfig(newConfig);
console.log(chalk.green(`${logSymbols.success} Quantity set to: ${quantity}`));
console.log(`Value of ${quantity} BTC:`);
spinner.start();
} catch {
exitError('Something wrong happened, could not save new quantity.');
}
}
} else {
console.log(`Value of ${quantity} BTC:`);
spinner.start();
}
multiplier = quantity;
}
// If `p` flag is set => print percentage change
if (cli.flags.percentage !== undefined) {
switch (cli.flags.percentage) {
case 'h': {
try {
const percentage = await getPercentageChangeLastHour();
printPercentage(`${percentage}%`);
} catch (error) {
console.log(error);
exitError('Please check your internet connection');
}
break;
}
case 'd':
case '': {
try {
const percentage = await getPercentageChangeLastDay();
printPercentage(`${percentage}%`);
} catch (error) {
console.log(error);
exitError('Please check your internet connection');
}
break;
}
case 'w': {
try {
const percentage = await getPercentageChangeLastWeek();
printPercentage(`${percentage}%`);
} catch (error) {
console.log(error);
exitError('Please check your internet connection');
}
break;
}
default: {
exitError('Invalid percentage input. Check `btc-value --help`.');
}
}
} else if (cli.flags.currency) {
// If `d` flag is set => return value as decimal
// USD is the default currency in the API
// If `c` flag is set => convert to other currency
// Print value of given `quantity` or just 1 BTC
const currency = await isValidCurrencyCode(cli.flags.currency);
try {
const value = await btcValue(cli.flags.currency);
const parsedValue = parseOptions(value, {isDecimal: printAsDecimal, quantity: multiplier});
const currencySymbol = getSymbolFromCurrency(currency);
printOutput(`${chalk.yellow(currencySymbol)}${parsedValue}`);
} catch (error) {
console.log(error);
exitError('Please check your internet connection');
}
} else {
try {
const value = await btcValue(defaultCurrency);
const parsedValue = parseOptions(value, {isDecimal: printAsDecimal, quantity: multiplier});
const defaultCurrencySymbol = getSymbolFromCurrency(defaultCurrency);
printOutput(`${chalk.yellow(defaultCurrencySymbol)}${parsedValue}`);
} catch (error) {
console.log(error);
exitError('Please check your internet connection');
}
}
// If `a` flag is set => set interval for automatic refreshing value printing
if (cli.flags.autorefresh !== undefined) {
if (cli.flags.autorefresh !== true) {
autorefresh = cli.flags.autorefresh;
}
// eslint-disable-next-line no-unused-vars
autorefreshTimer = setTimeout(checkAllFlags, autorefresh * 1000);
spinner.start();
}
}
const supportedProviders = new Set(['cmc', 'coingecko']);
// If `l` flag is set => print list of supported currency codes
if (cli.flags.list) {
let currencyOutprint = ' List of all supported currency codes:';
const supportedCurrencies = await getSupportedCurrencies();
for (let index = 0; index < supportedCurrencies.length; index++) {
// To separate the currency codes on different lines
if (index % 9 === 0) {
currencyOutprint += '\n ';
}
currencyOutprint += supportedCurrencies[index];
if (index !== supportedCurrencies.length - 1) {
currencyOutprint += ', ';
}
}
console.log(currencyOutprint);
process.exit(0);
}
if (cli.flags.provider) {
if (!supportedProviders.has(cli.flags.provider)) {
exitError('Please select a valid currency provider');
}
provider = cli.flags.provider;
const newConfig = JSON.stringify({
default: defaultCurrency,
quantity,
autorefresh,
apiKey,
provider
}, undefined, 4);
try {
await saveConfig(newConfig);
console.log(chalk.green(`${logSymbols.success} Set \`${cli.flags.provider}\` as currency provider`));
} catch {
exitError('Something wrong happened, could not save new currency provider');
}
process.exit(0);
}
// If `r` flag is set => reset configuration file
if (cli.flags.reset) {
const newConfig = JSON.stringify(defaultConfiguration, undefined, 4);
try {
await saveConfig(newConfig);
const defaultCurrencySymbol = getSymbolFromCurrency(defaultCurrency);
console.log(chalk.green(`${logSymbols.success} Default configuration reset to: ${defaultConfiguration.default} (${defaultCurrencySymbol})`));
} catch {
exitError('Something wrong happened, could not reset default configuration.');
}
process.exit(0);
}
// If `k` flag is set => set the API key
if (cli.flags.key) {
apiKey = cli.flags.key;
const newConfig = JSON.stringify({
default: defaultCurrency,
quantity,
autorefresh,
apiKey,
provider
}, undefined, 4);
try {
await saveConfig(newConfig);
console.log(chalk.green(`${logSymbols.success} API key is set`));
} catch {
exitError('Something wrong happened, could not save API key.');
}
process.exit(0);
}
if (provider === 'cmc') {
// Ensure that the API key is set if using data from CoinMarketCap
if (apiKey) {
setApiKey(apiKey);
} else {
exitError('You need to provide an API key to use CMC as a provider for the CLI. Set CoinGecko as a provider using `btc-value --provider coingecko`.\nOr go to https://coinmarketcap.com/api/ for obtaining a key.');
}
}
await checkAllFlags();