-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
57 lines (49 loc) · 1.68 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
'use strict'
const {IANAZone, DateTime} = require('luxon')
const isNonEmptyString = str => 'string' === typeof str && !!str
const defaultHafasOpts = {
// https://github.com/public-transport/cached-hafas-client/blob/c6a990d45dfab141870263e95f7ec7bdd49b3241/readme.md#bypassing-the-cache
[Symbol.for('cached-hafas-client:cached')]: false,
duration: 5,
remarks: false,
}
const createHealthCheck = (hafas, stationId, hafasOpts = defaultHafasOpts) => {
if (!hafas || 'function' !== typeof hafas.departures || !hafas.profile) {
throw new Error('missing or invalid hafas-client instance')
}
if (!isNonEmptyString(hafas.profile.timezone)) {
throw new Error('missing or empty hafas.profile.timezone')
}
if (!isNonEmptyString(stationId)) {
throw new Error('missing or empty station ID')
}
try {
const opt = Object.assign({}, hafasOpts)
opt.when = new Date()
hafas.departures(stationId, opt).catch(() => {}) // silence rejections
} catch (originalError) {
const err = new Error('hafas.departures(stationId) throws')
err.originalError = originalError
throw err
}
// this is expensive, so we only do it once
const zone = new IANAZone(hafas.profile.timezone)
const checkIfHealthy = () => {
const opt = Object.assign({}, hafasOpts)
opt.when = DateTime.fromMillis(Date.now(), {zone})
.startOf('week')
.plus({weeks: 1, hours: 8}) // todo: don't assume `monday === 1`
.toJSDate()
return hafas.departures(stationId, opt)
.then((res) => {
const deps = 'object' === typeof res && Array.isArray(res.departures)
// hafas-client@6
? res.departures
// hafas-client@5
: res
return deps.length > 0
})
}
return checkIfHealthy
}
module.exports = createHealthCheck