forked from jameswyse/forecast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (74 loc) · 2.45 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
86
87
88
89
90
91
92
93
94
/**
* Forecast - Weather Info for Node.js
* By James Wyse <james@jameswyse.net>
*
* https://github.com/jameswyse/forecast/
*/
var defaults = require('lodash-node/modern/objects/defaults');
var crypto = require('crypto');
var moment = require('moment');
var providers = require('./providers');
/**
* Forecast Constructor
* @param {Object} options Options
*/
var Forecast = module.exports = function(options) {
this.options = options || {};
this.providers = providers;
this.cache = {};
defaults(this.options, {
service: 'forecast.io',
units: 'celcius',
cache: true,
ttl: { minutes: 30 }
});
if(this.options.key === 'your-api-key') {
this.options.key = null;
}
this.options.ttl = moment.duration(this.options.ttl);
};
/**
* Expired - Checks if the given `key` has expired.
* @param {String} key Cache key
* @return {Boolean} `true` if expired, `false` otherwise.
*/
Forecast.prototype.expired = function(key) {
if(this.cache[key] === undefined) return true;
var isOld = this.cache[key].expires < (new Date().getTime());
if(isOld) delete this.cache[key];
return isOld;
};
/**
* Get the current weather conditions
* @param {Array} apiParams Accepts a latitude and longitude pair and optionally a unix timestamp as an `Array`
* @param {Boolean} ignoreCache If true then the cache will be ignored
* @param {Function} callback Callback, signature: callback(err, result)
*/
Forecast.prototype.get = function(apiParams, ignoreCache, callback) {
var self = this;
var key = crypto.createHash('md5')
.update(this.options + apiParams)
.digest('hex');
if(typeof ignoreCache === 'function') {
callback = ignoreCache;
ignoreCache = false;
}
if(typeof ignoreCache !== 'boolean') ignoreCache = false;
if(!ignoreCache && this.options.cache && this.cache[key] && !this.expired(key)) {
console.log('cached!');
return callback(null, this.cache[key]);
}
var Service = this.providers[this.options.service.toLowerCase()];
if (Service instanceof Object) {
Service = Service[this.options.service.toLowerCase()];
}
var service = new Service(this.options);
service.get(apiParams, function(err, result) {
if(err) return callback(err);
if(result !== undefined && self.options.cache) {
self.cache[key] = result;
self.cache[key].expires = new Date().getTime() + self.options.ttl.asMilliseconds();
}
return callback(null, result);
});
};