-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
api.js
94 lines (83 loc) · 2.37 KB
/
api.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
'use strict'
const createHafas = require('db-hafas')
const createApi = require('hafas-rest-api')
const createHealthCheck = require('hafas-client-health-check')
const Redis = require('ioredis')
const withCache = require('cached-hafas-client')
const redisStore = require('cached-hafas-client/stores/redis')
const {join: pathJoin} = require('path')
const serveStatic = require('serve-static')
const {parseBoolean} = require('hafas-rest-api/lib/parse')
const pkg = require('./package.json')
const {loyaltyCardParser} = require('./lib/loyalty-cards')
const stations = require('./routes/stations')
const station = require('./routes/station')
const docsRoot = pathJoin(__dirname, 'docs')
const berlinHbf = '8011160'
let hafas = createHafas(pkg.name)
let healthCheck = createHealthCheck(hafas, berlinHbf)
if (process.env.REDIS_URL) {
const redis = new Redis(process.env.REDIS_URL || null)
hafas = withCache(hafas, redisStore(redis), {
cachePeriods: {
locations: 6 * 60 * 60 * 1000, // 6h
},
})
const checkHafas = healthCheck
const checkRedis = () => new Promise((resolve, reject) => {
setTimeout(reject, 1000, new Error('didn\'t receive a PONG'))
redis.ping().then(
res => resolve(res === 'PONG'),
reject,
)
})
healthCheck = async () => (
(await checkHafas()) === true &&
(await checkRedis()) === true
)
}
const mapRouteParsers = (route, parsers) => {
if (route !== 'journeys') return parsers
return {
...parsers,
loyaltyCard: loyaltyCardParser,
firstClass: {
description: 'Search for first-class options?',
type: 'boolean',
default: 'false',
parse: parseBoolean,
},
}
}
const modifyRoutes = (routes, hafas, config) => {
routes['/stations/:id'] = station
routes['/stations'] = stations
return routes
}
const config = {
hostname: process.env.HOSTNAME || 'localhost',
port: process.env.PORT ? parseInt(process.env.PORT) : 3000,
name: pkg.name,
description: pkg.description,
homepage: pkg.homepage,
version: pkg.version,
docsLink: 'https://github.com/derhuerst/db-rest/blob/5/docs/readme.md',
openapiSpec: true,
logging: true,
aboutPage: false,
etags: 'strong',
csp: `default-src 'none' style-src 'self' 'unsafe-inline' img-src https:`,
healthCheck,
mapRouteParsers,
modifyRoutes,
}
const api = createApi(hafas, config, (api) => {
api.use('/', serveStatic(docsRoot, {
extensions: ['html', 'htm'],
}))
})
module.exports = {
hafas,
config,
api,
}