diff --git a/index.js b/index.js index d01ce21..ddc90f5 100644 --- a/index.js +++ b/index.js @@ -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) => { diff --git a/lib/station.js b/lib/station.js new file mode 100644 index 0000000..38fb82d --- /dev/null +++ b/lib/station.js @@ -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