forked from derhuerst/hafas-rest-api-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
233 lines (211 loc) · 6.06 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
'use strict'
/**
* @typedef {import('ky').Options} KyOptions
* @typedef {import('ky').HTTPError} HTTPError
* @typedef {import('ky').ResponsePromise} ResponsePromise
*/
import stringifyQuery from 'qs/lib/stringify.js'
import ky from 'ky-universal'
import {parse as parseContentType} from 'content-type'
import createDebug from 'debug'
const debug = createDebug('hafas-rest-api-client')
const RESPONSE = Symbol('Response')
const HEADERS = Symbol('Response.headers')
const SERVER_TIMING = Symbol('Server-Timing header')
const CACHE = Symbol('X-Cache header')
/**
* @param {string} endpoint - The API endpoint URL
* @param {Object} [opt={}] - Additional options
* @param {string} [opt.userAgent='hafas-rest-api-client'] - User agent string
* @returns {Object} - The API client methods
*/
const createClient = (endpoint, opt = {}) => {
new URL(endpoint); // throws if endpoint URL is invalid
const {
userAgent,
} = {
userAgent: 'hafas-rest-api-client',
}
/**
* @param {string} path - The API path
* @param {Object} [query={}] - Query parameters
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The API response data
*/
const request = async (path, query = {}, opt = {}) => {
const url = new URL(path, endpoint)
const cfg = {
mode: 'cors',
redirect: 'follow',
searchParams: stringifyQuery(Object.fromEntries([
...url.searchParams.entries(),
...Object.entries(query),
]), {allowDots: true}),
...opt,
headers: {
'Accept': 'application/json',
'User-Agent': userAgent,
...(opt.headers || {}),
},
}
let res
try {
res = await ky.get(url.href, cfg)
debug(res.status, path, query, opt)
} catch (err) {
// parse JSON body, attach to error object
try {
const headers = err.response && err.response.headers
const cType = headers && headers.get('content-type')
if (cType && parseContentType(cType).type === 'application/json') {
err.body = await err.response.json()
if (err.body.msg) err.message += ' – ' + err.body.msg
}
// eslint-disable-next-line no-empty
} catch (_) {}
throw err
}
const body = await res.json()
Object.defineProperty(body, RESPONSE, {value: res})
Object.defineProperty(body, HEADERS, {value: res.headers})
Object.defineProperty(body, SERVER_TIMING, {
value: res.headers.get('Server-Timing') || null,
})
Object.defineProperty(body, CACHE, {
value: res.headers.get('X-Cache') || null,
})
return body
}
/**
* @param {Object} query - Query parameters
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The locations response data
*/
const locations = async (query, opt = {}) => {
return await request('/locations', {
query,
...opt,
})
}
/**
* @param {Object} loc - Location coordinates
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The nearby stops response data
*/
const nearby = async (loc, opt = {}) => {
return await request('/stops/nearby', {
...loc,
...opt,
})
}
/**
* @param {string} query - Query string
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The stations response data
*/
const stations = async (query, opt = {}) => {
return await request('/stations', {
...opt,
query,
})
}
/**
* @param {Object} loc - Location coordinates
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The reachable stops response data
*/
const reachableFrom = async (loc, opt = {}) => {
return await request('/stops/reachable-from', {
...loc,
...opt,
})
}
/**
* @param {string} id - Stop/station ID
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The stop/station response data
*/
const stop = async (id, opt = {}) => {
if (!id) throw new TypeError('invalid id')
return await request('/stops/' + encodeURIComponent(id), opt)
}
/**
* @param {string} type - Either 'departures' or 'arrivals'
* @returns {Function} - The station board function
*/
const _stationBoard = (type) => async (stop, opt = {}) => {
if (!stop) throw new TypeError('invalid stop')
if (stop.id) stop = stop.id
else if ('string' !== typeof stop) throw new TypeError('invalid stop')
return await request(`/stops/${encodeURIComponent(stop)}/departures`, opt)
}
const departures = _stationBoard('departures')
const arrivals = _stationBoard('arrivals')
/**
* @param {Object} from - Origin location
* @param {Object} to - Destination location
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The journeys response data
*/
const journeys = async (from, to, opt = {}) => {
return await request('/journeys', {
from, to,
...opt,
})
}
/**
* @param {string} ref - Ref URL for the journey
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The refreshed journey response data
*/
const refreshJourney = async (ref, opt = {}) => {
if (!ref) throw new TypeError('invalid ref')
return await request('/journeys/' + encodeURIComponent(ref), opt)
}
/**
* @param {string} id - Trip ID
* @param {string} lineName - Line name of the trip
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The trip response data
*/
const trip = async (id, lineName, opt = {}) => {
if (!id) throw new TypeError('invalid id')
return await request('/trips/' + encodeURIComponent(id), {
lineName,
...opt,
})
}
/**
* @param {Object} bbox - Bounding box coordinates
* @param {KyOptions} [opt={}] - Additional options for ky
* @returns {Promise<Object>} - The radar response data
*/
const radar = async (bbox, opt = {}) => {
return await request('/radar', {
...bbox,
...opt,
})
}
return {
locations,
nearby,
stations,
reachableFrom,
stop,
departures, arrivals,
journeys,
refreshJourney,
trip,
radar,
}
}
/**
* @type {typeof createClient}
*/
export default createClient
export {
RESPONSE,
HEADERS,
SERVER_TIMING,
CACHE,
}