-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (69 loc) · 2.58 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
var exports = module.exports = {};
const request = require('request');
const API_KEY = '377d840e54b59adbe53608ba1aad70e8';
const API_BASE = 'https://live.kvv.de/webapp/';
const SEARCH_STOP_BY_NAME_PATH = 'stops/byname/';
const SEARCH_STOP_BY_LAT_LONG_PATH = 'stops/bylatlon/';
const SEARCH_STOP_BY_STOP_ID_PATH = 'stops/bystop/';
const GET_DEPARTURES_BY_STOPID_PATH = "departures/bystop/";
const GET_DEPARTURES_BY_ROUTE_PATH = 'departures/byroute/';
const STOPS_IDENTIFIER = 'stops';
function query(path, params = {}) {
params['key'] = API_KEY;
var url = API_BASE + path + "?" + encodeParameters(params);
return new Promise(function(resolve, reject) {
request(url, function(error, response, body) {
resolve(JSON.parse(body));
});
});
}
function encodeParameters(params) {
var str = [];
for(var p in params)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(params[p]));
return str.join("&");
}
function encode(value) {
return encodeURIComponent(value);
}
/**
* Search for stops by name.
* @param {*} name Name of the stop to look for.
* @param {*} maxInfos Maximum number of stops to return.
*/
exports.searchStopsByName = async function (name, maxInfos = 2) {
return (await query(SEARCH_STOP_BY_NAME_PATH + encode(name)))[STOPS_IDENTIFIER].slice(0, maxInfos);
};
/**
* Search for stops by latitude and longitude.
* @param {*} latitude Latitude of the position.
* @param {*} longitude Longitude of the position.
* @param {*} maxInfos Maximum number of stops to return.
*/
exports.searchStopsByLatLong = async function (latitude, longitude, maxInfos = 2) {
return (await query(SEARCH_STOP_BY_LAT_LONG_PATH + encode(latitude) + '/' + encode(longitude)))[STOPS_IDENTIFIER].slice(0, maxInfos);
};
/**
* Search for a stop by the respective stop ID.
* @param {*} stopId The stop ID to look for.
*/
exports.searchStopByStopId = async function (stopId) {
return (await query(SEARCH_STOP_BY_STOP_ID_PATH + encode(stopId)));
};
/**
* Search for departures by stop ID.
* @param {*} stopId The stop ID that departures should be
* @param {*} maxInfos Maximum number of departures to return.
*/
exports.getDepartures = async function (stopId, maxInfos = 4) {
return (await query(GET_DEPARTURES_BY_STOPID_PATH + encode(stopId), {'maxInfos': maxInfos}));
};
/**
*
* @param {*} stopId
* @param {*} route
* @param {*} max_info
*/
exports.getDeparturesByRoute = async function (stopId, route, max_info=4) {
return (await query(GET_DEPARTURES_BY_ROUTE_PATH + encode(route) + '/' + encode(stopId), {'maxInfos': maxInfos}));
};