-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
79 lines (62 loc) · 2.36 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
71
72
73
74
75
76
77
78
79
require('dotenv').config({ path: '.env.server' });
const fastify = require('fastify')({ logger: true });
const fastifyStatic = require('fastify-static');
const fetch = require("node-fetch");
const zipcodes = require('zipcodes');
const path = require('path');
fastify.register(fastifyStatic, {
root: path.join(__dirname, 'build'),
})
fastify.get('/', async (req, resp) => {
resp.sendFile('index.html');
});
fastify.get('/api/', async (req, resp) => {
if (Object.prototype.hasOwnProperty.call(req.query, 'zipcode')) {
// change zipcode to lat,lng
const geolocation = zipcodes.lookup(req.query.zipcode);
if (!geolocation ||
!Object.prototype.hasOwnProperty.call(geolocation, 'latitude') ||
!Object.prototype.hasOwnProperty.call(geolocation, 'longitude')) {
throw new Error("Zipcode seems to be invalid. Please try again.");
}
// make request to dark sky
const weatherUrl = `https://api.darksky.net/forecast/${process.env.DARK_SKY_API_KEY}/${geolocation.latitude},${geolocation.longitude}`;
const getData = async url => {
let json;
try {
const response = await fetch(url);
json = await response.json();
} catch (error) {
fastify.log.error(error);
}
/**
* Format icons
*/
if (Object.prototype.hasOwnProperty.call(json, 'currently')) {
json.currently.icon = json.currently.icon.toUpperCase().replace(/-/g, '-');
}
if (Object.prototype.hasOwnProperty.call(json, 'daily') &&
Object.prototype.hasOwnProperty.call(json.daily, 'icon')) {
json.currently.icon = json.currently.icon.toUpperCase().replace(/-/g, '_');
json.daily.icon = json.daily.icon.toUpperCase().replace(/-/g, '_');
for (const key in json.daily.data) {
if (Array.prototype.keys.call(json.daily.data, key)) {
json.daily.data[key].icon = json.daily.data[key].icon.toUpperCase().replace(/-/g, '_');
}
}
}
return json;
};
const response = await getData(weatherUrl);
resp.code(200).send(response);
} else {
throw new Error("Route requires 'zipcode'");
}
});
fastify.listen(process.env.PORT || 5000, process.env.HOST || '0.0.0.0', (err, address) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info(`Server listening on ${fastify.server.address().port}`)
});