-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
95 lines (82 loc) · 2.75 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
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
/* Application Name: app.js
* Purpose: Server Side Vanguard Trailhead Weather Application
*/
//Variable Declarations
var express = require('express');
var request = require('request');
var cfenv = require('cfenv');
var app = express();
var appEnv = cfenv.getAppEnv();
app.use(express.static(__dirname + '/public'));
//Set Local Timezone
process.env.TZ = 'America/Los_Angeles';
//API Information
var weather_host = "http://api.wunderground.com/api/"; //Weather API host
var apiKey = process.env.WUAPIKEY //Wunderground API Key (Environment Variable)
/* Function: weatherAPI
* Inputs: path: (Wunderground API path) (See WUnderground API Documentation)
* Returns: JSON data from API call or Error data from failed API call
* Notes: None
*/
function weatherAPI(path, done) {
//Build Full WUnderground URL API call
var url = weather_host + apiKey + path;
console.log(url);
//Make API Call
request({
url: url,
method: "GET",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
}
}, function(err, req, data) {
if (err) {
done(err);
} else {
if (req.statusCode >= 200 && req.statusCode < 400) {
try {
done(null, JSON.parse(data));
} catch(e) {
console.log(e);
done(e);
}
} else {
console.log(err);
done({ message: req.statusCode, data: data });
}
}
});
}
/* Monitor for requests on /api/weather
* Called by client script pgLoadDefault.js
* Prepares API call to WeatherUnderground
* Error handling/JSON return to client
*/
app.get('/api/weather', function(req, res) {
//Calculate Yesterdays Date (for historical hourly data)
var yesterdayDate = new Date(new Date() - (1000*60*60*24));
var yr = yesterdayDate.getFullYear();
var mo = yesterdayDate.getMonth() + 1;
var da = yesterdayDate.getDate();
//Format Date for API Call (add leading zero)
if(Number(mo) < 10) mo = "0" + mo;
if(Number(da) < 10) da = "0" + da;
console.log("Calculated Yesterday Date:" + mo + "/" + da + "/" + yr);
console.log("Making Call...");
//Build PATH and make API Call. See WUnderground API Documentation
weatherAPI("/conditions/forecast10day/history_" + yr + mo + da + "/q/94105.json"
, function(err, result) {
if (err) {
console.log(err);
res.send(err).status(400);
} else {
console.log("WUnderground API Call Success");
res.json(result);
}
});
});
// Application monitoring server
app.listen(process.env.PORT, function() {
console.log("server starting on " + appEnv.url);
});