-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
88 lines (70 loc) · 2.37 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
'use strict';
const request = require('request');
const makeRequest = url => {
return new Promise((resolve, reject) => {
const options = {
url: `https://www.mvg.de/api/fahrinfo${url}`,
headers: {'X-MVG-Authorization-Key': '5af1beca494712ed38d313714d4caff6'}
};
request(options, (err, response, body) => {
if (err) {
reject(err);
return;
}
try {
resolve(JSON.parse(body));
} catch {
resolve(null);
}
});
});
};
const toStation = async input => {
if (input instanceof Object) {
return input;
}
return await exports.getStation(input);
};
exports.allStations = async () => {
return await makeRequest('/location/queryWeb?q=');
};
exports.getDepartures = async station => {
station = await toStation(station);
let departures = await makeRequest(`/departure/${station.id}?footway=0`);
return departures.departures.map(departure => {
departure.time = new Date(departure.departureTime);
return departure;
});
};
exports.getLines = async station => {
station = await toStation(station);
let departures = await makeRequest(`/departure/${station.id}?footway=0`);
if (!departures) return [];
return departures.servingLines;
};
exports.getStation = async input => {
let endpoint = typeof input === 'number' ? '/location/query' : '/location/queryWeb';
return (await makeRequest(`${endpoint}?q=${input}`)).locations[0];
};
exports.getStations = async name => {
return (await makeRequest(`/location/queryWeb?q=${name}`)).locations;
};
exports.getNearbyStations = async (latitude, longitude) => {
return (await makeRequest(`/location/nearby?latitude=${latitude}&longitude=${longitude}`)).locations;
};
exports.getRoute = async (start, destination, options = new Date()) => {
start = await toStation(start);
destination = await toStation(destination);
if (options instanceof Date) {
options = {time: options.getTime()};
}
options.fromStation = start.id;
options.toStation = destination.id;
let params = Object.entries(options).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
let response = await makeRequest(`/routing/?${params}`);
if (response === null) return null;
response.connectionList.forEach(connection => {
connection.departure = new Date(connection.departure).toLocaleString();
});
return response.connectionList;
};