/stations/:id route
This commit is contained in:
parent
de11857a7e
commit
72f6cf2485
2 changed files with 42 additions and 0 deletions
2
index.js
2
index.js
|
@ -7,6 +7,7 @@ const hsts = require('hsts')
|
||||||
const pkg = require('./package.json')
|
const pkg = require('./package.json')
|
||||||
const stations = require('./lib/stations')
|
const stations = require('./lib/stations')
|
||||||
const allStations = require('./lib/all-stations')
|
const allStations = require('./lib/all-stations')
|
||||||
|
const station = require('./lib/station')
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
hostname: process.env.HOSTNAME || '2.db.transport.rest',
|
hostname: process.env.HOSTNAME || '2.db.transport.rest',
|
||||||
|
@ -19,6 +20,7 @@ const config = {
|
||||||
const api = createApi(hafas, config, (api) => {
|
const api = createApi(hafas, config, (api) => {
|
||||||
api.get('/stations', stations)
|
api.get('/stations', stations)
|
||||||
api.get('/stations/all', allStations)
|
api.get('/stations/all', allStations)
|
||||||
|
api.get('/stations/:id', station)
|
||||||
})
|
})
|
||||||
|
|
||||||
api.listen(config.port, (err) => {
|
api.listen(config.port, (err) => {
|
||||||
|
|
40
lib/station.js
Normal file
40
lib/station.js
Normal 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
|
Loading…
Reference in a new issue