db-vendo-client/index.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-06-22 01:39:04 +02:00
'use strict'
2016-06-22 01:39:59 +02:00
const got = require('got')
2016-06-22 02:09:02 +02:00
const parse = require('./parse')
2016-06-26 18:14:41 +02:00
const id = (x) => x
const defaults = {
onBody: id,
onReq: id,
onLocation: parse.location,
onLine: parse.line,
2016-06-26 18:14:41 +02:00
onRemark: parse.remark,
onOperator: parse.operator
2016-06-22 02:09:02 +02:00
}
2016-06-22 01:39:59 +02:00
2016-06-22 02:09:02 +02:00
2016-06-26 18:14:41 +02:00
2017-07-24 14:25:43 +02:00
const hafasError = (msg) => {
const err = new Error(msg)
err.isHafasError = true
return err
}
2017-10-03 17:36:42 +02:00
const createRequest = (opt) => {
2016-06-26 18:14:41 +02:00
opt = Object.assign({}, defaults, opt)
2017-10-03 17:36:42 +02:00
const request = (data) => {
2016-06-26 18:14:41 +02:00
const body = opt.onBody({lang: 'en', svcReqL: [data]})
const req = opt.onReq({
2017-10-04 02:12:12 +02:00
json: true, body: body,
2016-06-26 18:14:41 +02:00
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'user-agent': 'https://github.com/derhuerst/hafas-client'
2016-06-26 18:14:41 +02:00
}
})
return got.post(opt.endpoint, req)
.then((res) => {
const b = res.body
2017-07-24 14:25:43 +02:00
if (b.err) throw hafasError(b.err)
2016-07-18 19:21:31 +02:00
if (!b.svcResL || !b.svcResL[0]) throw new Error('invalid response')
2017-07-24 14:25:43 +02:00
if (b.svcResL[0].err !== 'OK') throw hafasError(b.svcResL[0].errTxt)
2016-06-26 18:14:41 +02:00
const d = b.svcResL[0].res
const c = d.common || {}
if (Array.isArray(c.locL)) d.locations = c.locL.map(opt.onLocation)
if (Array.isArray(c.prodL)) d.lines = c.prodL.map(opt.onLine)
2016-06-26 18:14:41 +02:00
if (Array.isArray(c.remL)) d.remarks = c.remL.map(opt.onRemark)
if (Array.isArray(c.opL)) d.operators = c.opL.map(opt.onOperator)
2016-06-26 18:14:41 +02:00
return d
2017-10-03 17:36:42 +02:00
})
2016-06-22 01:39:59 +02:00
}
2017-10-03 17:36:42 +02:00
return request
2016-06-22 01:39:59 +02:00
}
2017-10-03 17:36:42 +02:00
module.exports = createRequest