-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather.js
108 lines (94 loc) · 2.74 KB
/
weather.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
#!/usr/bin/env node
import { args } from './services/args.service.js';
import { printError, printSuccess } from './services/log.service.js';
import { getKeysValues, saveKeyValue } from './services/storage.service.js';
import {
getCoordCity,
getCurrentWeather,
getDailyWeather,
getHourlyWeather,
} from './services/api.service.js';
import {
outputCurrentWeather,
outputDailyWeather,
outputHourlyWeather,
} from './services/output.service.js';
import { COMMAND_NAME } from './constatns.js';
import { handlerError } from './helpers/handlerError.js';
const command = args._[0];
const saveToken = async (token) => {
if (!token.length) {
printError('Не передан токен, для получения помощи введите ключ -h');
return;
}
try {
await saveKeyValue('token', token);
printSuccess('Токен сохранен!');
} catch (e) {
printError(`Ошибка при сохранении токена, ${e.message}`);
}
};
const saveCity = async (city) => {
try {
const config = await getKeysValues();
if (!config.token) {
printError('Сначала установите токен с помощью -t [TOKEN]');
return;
}
const response = await getCoordCity(city);
await saveKeyValue('lat', response?.data?.coord?.lat);
await saveKeyValue('lon', response?.data?.coord?.lon);
await saveKeyValue('city', city);
printSuccess('Город сохранен!');
} catch (e) {
printError(
`Ошибка при сохранении города. Возможно вы не указали токен или допустили ошибку в написании города`,
);
}
};
const getCurrentForecast = async () => {
try {
const response = await getCurrentWeather();
outputCurrentWeather(response.data);
} catch (e) {
handlerError(e);
}
};
const getDailyForecast = async () => {
try {
const config = await getKeysValues();
const response = await getDailyWeather();
outputDailyWeather(response.data, config.city);
} catch (e) {
handlerError(e);
}
};
const getHourlyForecast = async () => {
try {
const config = await getKeysValues();
const response = await getHourlyWeather();
outputHourlyWeather(response.data, config.city);
} catch (e) {
handlerError(e);
}
};
const main = async () => {
if (args.token) {
return await saveToken(args.token);
}
if (args.city) {
return await saveCity(args.city);
}
process.stdout.write('\u001b[2J\u001b[0;0H');
if (command === COMMAND_NAME.hourly) {
await getHourlyForecast();
return;
}
if (command === COMMAND_NAME.daily) {
await getDailyForecast();
return;
}
// current weather
await getCurrentForecast();
};
main();