-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
70 lines (56 loc) · 2.05 KB
/
server.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
'use strict';
console.log('server.js is connected');
require('dotenv').config();
const express = require('express');
const app = express();
const cors = require('cors');
const superagent = require('superagent');
const PORT = process.env.PORT;
app.use(cors());
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
app.get('/', (req,res) => {
res.send(`Connected on Port: ${PORT}`);
});
function Location(searchedCity, display_name, lat, lon) {
this.search_query = searchedCity;
this.formatted_query = display_name;
this.latitude = parseFloat(lat);
this.longitude = parseFloat(lon);
}
function Weather(weather,valid_date) {
this.forecast = weather;
this.time = valid_date;
}
app.get('/location', (request,response) => {
const apiKey = process.env.GEOCODE_API_KEY;
const searchedCity = request.query.city;
const url = `https://us1.locationiq.com/v1/search.php?key=${apiKey}&q=${searchedCity}&format=json`;
superagent.get(url).then(apiReturned => {
const returnedLocation = apiReturned.body[0];
const newLocation = new Location(searchedCity, returnedLocation.display_name, returnedLocation.lat, returnedLocation.lon);
response.status(200).send(newLocation);
}).catch(error => {
response.status(500).send(error);
})
});
app.get('/weather', (request, response) => {
const latitude = parseFloat(request.query.latitude);
const longitude = parseFloat(request.query.longitude);
const searchedCity = request.query.search_query;
const apiKey = process.env.WEATHER_API_KEY;
const url = `http://api.weatherbit.io/v2.0/forecast/daily`;
const searchParameters = {
key:apiKey, city:searchedCity, days:8
};
superagent.get(url).query(searchParameters).then(returnData => {
let weatherArr = returnData.body.data.map( day => {
return new Weather(day.weather.description,day.valid_date);
});
response.status(200).send(weatherArr);
}).catch(error => {
response.status(500).send('There was an error');
})
});
app.use('*', (req,res) => {
res.status(500).send('Status: 500<br> Server has error');
});