From 99f15760a8343745fd0b52a68f68e4096b0e32af Mon Sep 17 00:00:00 2001 From: Jannis R Date: Fri, 10 Nov 2017 00:06:15 +0100 Subject: [PATCH] stations route --- api.js | 2 ++ lib/stations.js | 47 +++++++++++++++++++++++++++++++++++++++++++++++ package.json | 4 +++- 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 lib/stations.js diff --git a/api.js b/api.js index 91dbf86..d4622f9 100644 --- a/api.js +++ b/api.js @@ -11,6 +11,7 @@ const nocache = require('nocache') const pkg = require('./package.json') const departures = require('./lib/departures') const journeys = require('./lib/journeys') +const stations = require('./lib/stations') const allStations = require('./lib/all-stations') @@ -40,6 +41,7 @@ const noCache = nocache() api.get('/stations/:id/departures', noCache, departures) api.get('/journeys', noCache, journeys) +api.get('/stations', stations) api.get('/stations/all', allStations) diff --git a/lib/stations.js b/lib/stations.js new file mode 100644 index 0000000..585ab12 --- /dev/null +++ b/lib/stations.js @@ -0,0 +1,47 @@ +'use strict' + +const autocomplete = require('db-stations-autocomplete') +const stations = require('db-stations') +const parse = require('cli-native').to +const createFilter = require('db-stations/create-filter') +const ndjson = require('ndjson') + +const err400 = (msg) => { + const err = new Error(msg) + err.statusCode = 400 + return err +} + +const complete = (req, res, next) => { + const fuzzy = req.query.fuzzy === 'true' + const completion = req.query.completion !== 'false' + + res.json(autocomplete(req.query.query, fuzzy, completion)) + next() +} + +const filter = (req, res, next) => { + if (Object.keys(req.query).length === 0) { + return next(err400('Missing properties.')) + } + + const selector = Object.create(null) + for (let prop in req.query) selector[prop] = parse(req.query[prop]) + const filter = createFilter(selector) + + stations.full() + .on('error', next) + .pipe(filter) + .on('error', next) + .pipe(ndjson.stringify()) + .on('error', next) + .pipe(res) + .once('finish', () => next()) +} + +const route = (req, res, next) => { + if (req.query.query) complete(req, res, next) + else filter(req, res, next) +} + +module.exports = route diff --git a/package.json b/package.json index d4205f9..1bafcd4 100644 --- a/package.json +++ b/package.json @@ -31,11 +31,13 @@ "compression": "^1.7.1", "corser": "^2.0.1", "db-hafas": "^1.1.0", - "db-stations": "^1.22.0", + "db-stations": "^1.24.0", + "db-stations-autocomplete": "^1.0.0", "express": "^4.16.2", "hafas-departures-in-direction": "^0.1.0", "hsts": "^2.1.0", "morgan": "^1.9.0", + "ndjson": "^1.5.0", "nocache": "^2.0.0", "parse-messy-time": "^2.1.0", "shorthash": "^0.0.2"