From 72f6cf24852eb81796ec2e24df74a97b6d8793c4 Mon Sep 17 00:00:00 2001 From: Jannis R Date: Tue, 9 Jan 2018 16:51:42 +0100 Subject: [PATCH] /stations/:id route --- index.js | 2 ++ lib/station.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 lib/station.js 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