-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.js
executable file
·177 lines (154 loc) · 4.7 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
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
#!/usr/bin/env node
const path = require("path");
require("dotenv").config({ path: path.join(__dirname, ".env") });
const axios = require("axios");
const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const chalk = require("chalk");
const argv = yargs(hideBin(process.argv)).argv;
const weatherSymbols = {
Clear: "☀️",
Rain: "☔",
Clouds: "☁️",
Snow: "❄️",
Drizzle: "🌧️",
Thunderstorm: "⛈️",
};
const DEFAULT_LOCATION = process.env.DEFAULT_LOCATION;
const BORDER = chalk.greenBright("*".repeat(80));
const capitalize = (str) => str[0].toUpperCase() + str.slice(1);
const displayCurrentAlerts = (alerts) => {
if (!alerts) {
console.log(chalk.red("No Alerts"));
return;
} else {
console.log();
console.log(chalk.redBright("---ALERTS---"));
console.log();
for (let alert of alerts) {
console.log(chalk.yellowBright(alert.event));
console.log(alert.description);
}
}
};
const degToDirection = (degrees) => {
const sector = Math.floor(degrees / 45 + 0.5);
const directions = [
"North",
"Northeast",
"East",
"Souteast",
"South",
"Soutwest",
"West",
"Northwest",
];
return directions[sector % 8];
};
const displayCurrentWeather = (weatherData) => {
let description = weatherData.current.weather[0].main;
let symbol = weatherSymbols[description];
console.log(BORDER);
console.log(
chalk.whiteBright(
`CURRENT WEATHER FOR ${chalk.cyan(
capitalize(weatherData.city)
)}, ${chalk.cyan(weatherData.state)}:`
)
);
console.log(`Current Temperature: ${Math.floor(weatherData.current.temp)}°F`);
console.log(
`Low: ${chalk.blueBright(
Math.floor(weatherData.daily[0].temp.min)
)} / High: ${chalk.redBright(Math.floor(weatherData.daily[0].temp.max))}`
);
console.log(
`Wind Speed: ${Math.round(
weatherData.current.wind_speed
)} mph ${degToDirection(weatherData.current.wind_deg)}`
);
console.log(`Humidity: ${weatherData.current.humidity}%`);
console.log("Description: " + symbol + " " + description);
displayCurrentAlerts(weatherData.alerts || null);
console.log(BORDER);
console.log;
};
const displayForecast = (weatherData) => {
const dateDisplayOptions = {
weekday: "long",
month: "short",
day: "numeric",
};
console.log(`\nDaily forecast:`);
for (let day of weatherData.daily.slice(0, 7)) {
const date = new Date(day.dt * 1000);
const dateFormatted = date.toLocaleDateString("en-US", dateDisplayOptions);
const description = day.weather[0].main;
const symbol = weatherSymbols[description];
console.log(BORDER);
console.log(`Date: ${dateFormatted}`);
console.log(
`Low: ${chalk.blueBright(
Math.floor(day.temp.min)
)}°F / High: ${chalk.redBright(Math.floor(day.temp.max))}`
);
console.log(`Humidity: ${day.humidity}%`);
console.log(
"Description: " +
symbol +
" " +
description +
" - " +
day.weather[0].description
);
console.log("");
}
};
const getCoords = async (city, state) => {
let response;
let url;
if (state) {
url = `https://api.openweathermap.org/geo/1.0/direct?q=${city},${state},US&appid=${process.env.OPENWEATHER_API_KEY}`;
} else {
url = `https://api.openweathermap.org/geo/1.0/direct?q=${city}&appid=${process.env.OPENWEATHER_API_KEY}`;
}
response = await axios.get(url);
if (response.data.length === 0) throw new Error("Invalid city/state");
const data = response.data[0] || response.data;
return [data.lat, data.lon];
};
const getWeather = async (lat, lon, city, state, forecast) => {
try {
const response = await axios.get(
`https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&units=imperial&appid=${process.env.OPENWEATHER_API_KEY}`
);
const weatherData = response.data;
weatherData.city = city;
weatherData.state = state;
displayCurrentWeather(weatherData);
if (forecast) displayForecast(weatherData);
} catch (error) {
console.error(`Error getting weather data: ${error}`);
}
};
const main = async (cityState = DEFAULT_LOCATION, forecast = false) => {
let state;
let city;
const cityStatePattern = /^[a-z. ]+\s*,\s*[a-z]{2}$/i;
if (cityState.toLowerCase() === "forecast") {
city = "Fritch";
state = "tx";
forecast = true;
} else if (!cityStatePattern.test(cityState)) {
throw new Error("You must submit your location in format of 'city,state' ");
} else {
[city, state] = cityState.split(",");
}
try {
const [lat, lon] = await getCoords(city, state);
getWeather(lat, lon, city, state, forecast);
} catch (error) {
console.log(error);
}
};
main(argv._[0], argv._[1]);