forked from mateodelnorte/forecast.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (67 loc) · 2.18 KB
/
index.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
var log = require('debug')('forecast.io'),
request = require('request'),
util = require('util'),
qs = require('querystring');
function ForecastError (errors) {
Error.captureStackTrace(this, ForecastError);
this.errors = errors;
}
util.inherits(ForecastError, Error);
ForecastError.prototype.toString = function toString (){
return "ForecastError: " + this.errors;
}
function Forecast (options) {
if ( ! options) throw new ForecastError('APIKey must be set on Forecast options');
if ( ! options.APIKey) throw new ForecastError('APIKey must be set on Forecast options');
this.APIKey = options.APIKey;
this.requestTimeout = options.timeout || 2500
this.url = 'https://api.forecast.io/forecast/' + options.APIKey + '/';
}
Forecast.prototype.buildUrl = function buildUrl (latitude, longitude, time, options) {
if (typeof time === 'object') {
options = time;
delete time;
}
var query = '?' + qs.stringify(options);
var url = this.url + latitude + ',' + longitude;
if (typeof time === 'number') {
url += ',' + time;
}
url += query;
log('get ' + url);
return url;
}
Forecast.prototype.get = function get (latitude, longitude, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
var url = this.buildUrl(latitude, longitude, options);
request.get({uri:url, timeout:this.requestTimeout}, function (err, res, data) {
if (err) {
callback(err);
} else if(res.headers['content-type'].indexOf('application/json') > -1) {
callback(null, res, JSON.parse(data));
} else if(res.statusCode === 200) {
callback(null, res, data);
} else {
callback(new ForecastError(data), res, data);
}
});
};
Forecast.prototype.getAtTime = function getAtTime (latitude, longitude, time, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
var url = this.buildUrl(latitude, longitude, time, options);
request.get({uri:url, timeout:this.requestTimeout}, function (err, res, data) {
if (err) {
callback(err);
} else {
data = JSON.parse(data);
callback(null, res, data);
}
});
};
module.exports = Forecast;