2017-11-11 22:49:04 +01:00
|
|
|
'use strict'
|
|
|
|
|
2018-01-23 01:24:37 +01:00
|
|
|
let captureStackTrace = () => {}
|
|
|
|
if (process.env.NODE_ENV === 'dev') {
|
|
|
|
captureStackTrace = require('capture-stack-trace')
|
|
|
|
}
|
2018-01-23 01:30:20 +01:00
|
|
|
const {stringify} = require('query-string')
|
2017-11-11 22:49:04 +01:00
|
|
|
const Promise = require('pinkie-promise')
|
|
|
|
const {fetch} = require('fetch-ponyfill')({Promise})
|
|
|
|
|
|
|
|
const request = (profile, data) => {
|
|
|
|
const body = profile.transformReqBody({lang: 'en', svcReqL: [data]})
|
|
|
|
const req = profile.transformReq({
|
|
|
|
method: 'post',
|
|
|
|
// todo: CORS? referrer policy?
|
|
|
|
body: JSON.stringify(body),
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
'Accept-Encoding': 'gzip, deflate',
|
|
|
|
'user-agent': 'https://github.com/derhuerst/hafas-client'
|
|
|
|
},
|
|
|
|
query: null
|
|
|
|
})
|
|
|
|
const url = profile.endpoint + (req.query ? '?' + stringify(req.query) : '')
|
|
|
|
|
2018-01-23 01:24:37 +01:00
|
|
|
// Async stack traces are not supported everywhere yet, so we create our own.
|
|
|
|
const err = new Error()
|
|
|
|
err.isHafasError = true
|
|
|
|
err.request = body
|
|
|
|
captureStackTrace(err)
|
|
|
|
|
2017-11-11 22:49:04 +01:00
|
|
|
return fetch(url, req)
|
|
|
|
.then((res) => {
|
2018-01-23 01:24:37 +01:00
|
|
|
err.statusCode = res.status
|
2017-11-11 22:49:04 +01:00
|
|
|
if (!res.ok) {
|
2018-01-23 01:24:37 +01:00
|
|
|
err.message = res.statusText
|
|
|
|
throw err
|
2017-11-11 22:49:04 +01:00
|
|
|
}
|
|
|
|
return res.json()
|
|
|
|
})
|
|
|
|
.then((b) => {
|
2018-01-23 01:24:37 +01:00
|
|
|
if (b.err) {
|
|
|
|
err.message = b.err
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
if (!b.svcResL || !b.svcResL[0]) {
|
|
|
|
err.message = 'invalid response'
|
|
|
|
throw err
|
|
|
|
}
|
2017-11-11 22:49:04 +01:00
|
|
|
if (b.svcResL[0].err !== 'OK') {
|
2018-01-28 14:12:52 +01:00
|
|
|
err.message = b.svcResL[0].errTxt || b.svcResL[0].err
|
2018-01-23 01:24:37 +01:00
|
|
|
throw err
|
2017-11-11 22:49:04 +01:00
|
|
|
}
|
|
|
|
const d = b.svcResL[0].res
|
|
|
|
const c = d.common || {}
|
|
|
|
|
2017-11-12 01:23:34 +01:00
|
|
|
if (Array.isArray(c.remL)) {
|
|
|
|
d.remarks = c.remL.map(rem => profile.parseRemark(profile, rem))
|
|
|
|
}
|
|
|
|
if (Array.isArray(c.opL)) {
|
|
|
|
d.operators = c.opL.map(op => profile.parseOperator(profile, op))
|
|
|
|
}
|
2018-01-05 18:46:19 +01:00
|
|
|
if (Array.isArray(c.prodL)) {
|
|
|
|
const parse = profile.parseLine(profile, d.operators)
|
|
|
|
d.lines = c.prodL.map(parse)
|
|
|
|
}
|
2018-01-26 16:25:13 +01:00
|
|
|
if (Array.isArray(c.locL)) {
|
|
|
|
const parse = loc => profile.parseLocation(profile, loc, d.lines)
|
|
|
|
d.locations = c.locL.map(parse)
|
|
|
|
}
|
2017-11-11 22:49:04 +01:00
|
|
|
return d
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = request
|