/stations/:id route

This commit is contained in:
Jannis R 2018-01-09 16:51:42 +01:00
parent de11857a7e
commit 72f6cf2485
No known key found for this signature in database
GPG key ID: 0FE83946296A88A5
2 changed files with 42 additions and 0 deletions

View file

@ -7,6 +7,7 @@ const hsts = require('hsts')
const pkg = require('./package.json')
const stations = require('./lib/stations')
const allStations = require('./lib/all-stations')
const station = require('./lib/station')
const config = {
hostname: process.env.HOSTNAME || '2.db.transport.rest',
@ -19,6 +20,7 @@ const config = {
const api = createApi(hafas, config, (api) => {
api.get('/stations', stations)
api.get('/stations/all', allStations)
api.get('/stations/:id', station)
})
api.listen(config.port, (err) => {

40
lib/station.js Normal file
View file

@ -0,0 +1,40 @@
'use strict'
const stations = require('db-stations')
const err400 = (msg) => {
const err = new Error(msg)
err.statusCode = 400
return err
}
// This is terribly inefficient, because we read all stations for every request.
// todo: optimize it
const route = (req, res, next) => {
const id = req.params.id.trim()
const stream = stations.full()
let found = false
const onStation = (station) => {
if (station.id !== id) return
found = true
stream.removeListener('data', onStation)
res.json(station)
next()
}
stream.on('data', onStation)
const onEnd = () => {
if (!found) return next(err400('Station not found.'))
}
stream.once('end', onEnd)
stream.once('error', (err) => {
stream.removeListener('data', onStation)
stream.removeListener('end', onEnd)
next(nerr)
})
}
module.exports = route