-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
46 lines (37 loc) · 1.59 KB
/
app.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
const express = require("express");
const axios = require("axios");
const conversionFunctions = require("./utils/ConversionUtils.js");
const app = express();
const port = 4001;
app.listen(port, () => {
console.log("Weather microservice running!");
});
app.get("/api/weather/", function(req, res) {
const city = req.query.c; // the city that is passed via the URL
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=2e15c965ff28cc6a856c04b3489f9d68`;
axios
.get(url)
.then(response => {
const temperatureK = response.data.main.temp;
const humidity = response.data.main.humidity;
const cityName = response.data.name;
const countryName = response.data.sys.country;
// Handle Temperature conversions from Kelvins
const temperatureF = conversionFunctions.convertKelvinToFahrenheit(temperatureK);
const temperatureC = conversionFunctions.convertKelvinToCelsius(temperatureK);
const weatherDisplay = `Right now, in \
${cityName}, ${countryName} the current temperature is \
${temperatureC.toFixed(1)} ºC \
(${temperatureF.toFixed(1)} ºF), with ${humidity}% humidity, \
conditions: ${response.data.weather[0].description} `.replace(/\s+/g, " ");
res.status(200).send(weatherDisplay)
})
.catch(error => {
if (error.response) {
res.status(404).send("Error occurred! Reason: " + error.response.data)
}
else {
res.status(404).send("Unknown error occurred!")
}
});
});