-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
59 lines (50 loc) · 1.56 KB
/
server.js
File metadata and controls
59 lines (50 loc) · 1.56 KB
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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const forecast = require("./data/data.js");
const port = process.env.PORT || 4000;
const server = express();
server.use(express.json());
server.use(cors());
// Server listening to local port or to the port from Heroku app.
if (process.env.NODE_ENV !== "test") {
server.listen(port, err => {
if (err) console.log(err);
console.log(`Server running in port ${port}`);
});
}
//To check if the server is running
server.get("/", (req, res) => {
res.status(200).json({ message: "The Weather server is up and running!" });
});
/**
* Gets the forecast for a particular place
*/
server.get("/forecast/:place", (req, res) => {
//Gets the name of the place
let { place } = req.params;
//Filters the forecast for that place
let myForecasts = forecast.filter(forecast => forecast.city == place);
//If forecast is available sends the forecast. Otherwise sends the message.
if (myForecasts.length > 0) {
myForecasts.length = myForecasts.length > 5 ? 5 : myForecasts.length;
res.status(200).json({
forecasts: myForecasts,
currentForecast: myForecasts[0],
city: place
});
} else {
res
.status(204)
.json({ message: "No weather information to display.", city: place });
}
});
/**
* Gets the distinct list of cities for the drop down.
*/
server.get("/cities", (req, res) => {
// Gets the unique list of cities
let myCities = [...new Set(forecast.map(item => item.city))];
res.status(200).json(myCities);
});
module.exports = server;