forked from sdhani/PlantPal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grab_current_weather.js
79 lines (70 loc) · 2.51 KB
/
grab_current_weather.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
/* OpenWeatherMap API calls using Heroku config vars
* reads weather table zipcode collumn and grabs local
* weather from the current weather API and writes current
* weather into weather table matching zipcodes
*/
const request = require('request');
const {
Client
} = require('pg');
// global variables to be used in api calls
const connectionString = process.env.DATABASE_URL;
const units = process.env.OWEATHER_UNITS;
const apiKey = process.env.OWEATHER_TOKEN;
// variables that change with each api call
var zipcode;
var lat;
var lon;
// variables to write into table (using weather description only for now for testing)
var descr;
// set db connection parameters
const db = new Client({
connectionString: connectionString
});
db.connect();
// read zipcode from weather table and feed into getWeather fucntion, API call
db.query('SELECT zipcode FROM weather', (err, res) => {
if (err) {
console.log(err.stack);
} else {
for (let i = 0, p = Promise.resolve(); i < res.rows.length; i++) {
p = p.then(_ => new Promise(resolve =>
setTimeout(function () {
zipcode = res.rows[i].zipcode;
getWeather();
resolve();
}, Math.random() * 1000)
));
}
}
});
// not a great solution, but couldn't figure out a db.connection promise
setTimeout(killConnection, 60000);
function killConnection() {
db.end();
};
// takes zipcode value from db.query and executes current weather api call
function getWeather() {
zip = zipcode;
let weather_url = `http://api.openweathermap.org/data/2.5/weather?zip=${zip},us&units=${units}&appid=${apiKey}`;
console.log(zipcode);
request(weather_url, function (err, response, body) {
if (err) {
console.log('error:', error);
} else {
var forcast = JSON.parse(body);
current_temp = `${forcast.main.temp}`;
description = `${forcast.weather[0].description}`;
if (forcast.hasOwnProperty("rain")) {
rain = `${forcast.rain["1h"]}`;
} else {
rain = '0.00';
}
// write results into weather table by zipcode
db.query("UPDATE weather SET day_current_temp = '" + current_temp + "', weather_description = '" + description + "', hourly_rain = '" + rain + "' WHERE zipcode = '" + zipcode + "'", (err, res) => {
if (err)
console.log(err.stack);
});
}
});
};