forked from codeforboston/MBTA-API-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mbta.js
54 lines (52 loc) · 1.12 KB
/
mbta.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
var request = require("request");
var q = require('q');
var parser = (new require('xml2js').Parser()).parseString;
var busBase = "http://webservices.nextbus.com/service/publicXMLFeed"
var RTA = require('rta');
var subways = {
red:"http://developer.mbta.com/lib/rthr/red.json",
orange:"http://developer.mbta.com/lib/rthr/orange.json",
blue:"http://developer.mbta.com/lib/rthr/blue.json"
};
var mbta = new RTA('mbta',10);
function Cache(){
var cache = {};
this.check=function(code,def){
if(code in cache){
cache[code].then(function(a){
def.resolve(a);
},function(a){
def.reject(a);
});
return false;
}else{
cache[code]=def.promise;
setTimeout(function(){
delete cache[code]
},10000);
return true;
}
}
}
var subwayCache = new Cache();
mbta.subway = function(line,cb){
var def = q.defer();
if(cb){
def.promise.then(function(a){cb(null,a)},cb);
}
if(subwayCache.check(line,def)){
if(line in subways){
request({
url:subways[line],
},function(e,r,b){
if(e){
def.reject(e);
}else{
def.resolve(JSON.parse(b));
}
});
}
}
return def.promise;
}
module.exports=mbta;