2017-11-10 00:06:15 +01:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const autocomplete = require('db-stations-autocomplete')
|
2018-01-30 12:11:25 +01:00
|
|
|
const allStations = require('db-stations/full.json')
|
2017-11-10 00:06:15 +01:00
|
|
|
const parse = require('cli-native').to
|
|
|
|
const createFilter = require('db-stations/create-filter')
|
|
|
|
const ndjson = require('ndjson')
|
|
|
|
|
2018-01-30 12:11:25 +01:00
|
|
|
const hasProp = (o, k) => Object.prototype.hasOwnProperty.call(o, k)
|
|
|
|
|
2017-11-10 00:06:15 +01:00
|
|
|
const err400 = (msg) => {
|
|
|
|
const err = new Error(msg)
|
|
|
|
err.statusCode = 400
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
const complete = (req, res, next) => {
|
2018-01-30 12:11:25 +01:00
|
|
|
const limit = req.query.results && parseInt(req.query.results) || 3
|
|
|
|
const fuzzy = parse(req.query.fuzzy) === true
|
|
|
|
const completion = parse(req.query.completion) !== false
|
|
|
|
const results = autocomplete(req.query.query, limit, fuzzy, completion)
|
|
|
|
|
|
|
|
const data = []
|
|
|
|
for (let result of results) {
|
|
|
|
// todo: make this more efficient
|
|
|
|
const station = allStations.find(s => s.id === result.id)
|
|
|
|
if (!station) continue
|
|
|
|
|
|
|
|
data.push(Object.assign(result, station))
|
|
|
|
}
|
2017-11-10 00:06:15 +01:00
|
|
|
|
2018-01-30 12:11:25 +01:00
|
|
|
res.json(data)
|
2017-11-10 00:06:15 +01:00
|
|
|
next()
|
|
|
|
}
|
|
|
|
|
|
|
|
const filter = (req, res, next) => {
|
|
|
|
if (Object.keys(req.query).length === 0) {
|
|
|
|
return next(err400('Missing properties.'))
|
|
|
|
}
|
|
|
|
|
|
|
|
const selector = Object.create(null)
|
2018-01-30 12:11:25 +01:00
|
|
|
for (let prop in req.query) {
|
2020-01-31 15:00:47 +01:00
|
|
|
const val = parse(req.query[prop])
|
2018-01-30 12:11:25 +01:00
|
|
|
if (prop.slice(0, 12) === 'coordinates.') { // derhuerst/db-rest#2
|
|
|
|
prop = 'location.' + prop.slice(12)
|
|
|
|
}
|
2020-01-31 15:00:47 +01:00
|
|
|
selector[prop] = val
|
2018-01-30 12:11:25 +01:00
|
|
|
}
|
2017-11-10 00:06:15 +01:00
|
|
|
const filter = createFilter(selector)
|
|
|
|
|
2018-01-30 12:11:25 +01:00
|
|
|
res.type('application/x-ndjson')
|
|
|
|
const out = ndjson.stringify()
|
|
|
|
out
|
|
|
|
.once('error', next)
|
2017-11-10 00:06:15 +01:00
|
|
|
.pipe(res)
|
|
|
|
.once('finish', () => next())
|
2018-01-30 12:11:25 +01:00
|
|
|
|
|
|
|
for (let station of allStations) {
|
|
|
|
if (filter(station)) out.write(station)
|
|
|
|
}
|
|
|
|
out.end()
|
2017-11-10 00:06:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const route = (req, res, next) => {
|
|
|
|
if (req.query.query) complete(req, res, next)
|
|
|
|
else filter(req, res, next)
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = route
|