db-vendo-client/index.js

42 lines
1.1 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')
const onData = (d) => {
if (!d.common) return d
const c = d.common
if (Array.isArray(c.locL)) d.locations = c.locL.map(parse.location)
2016-06-25 01:39:44 +02:00
if (Array.isArray(c.prodL)) d.products = c.prodL.map(parse.product)
if (Array.isArray(c.remL)) d.remarks = c.remL.map(parse.remark)
if (Array.isArray(c.opL)) d.agencies = c.opL.map(parse.agency)
2016-06-22 02:09:02 +02:00
return d
}
2016-06-22 01:39:59 +02:00
const request = (cfg) => (data) => {
2016-06-22 02:09:02 +02:00
let body = {lang: 'en', svcReqL: [data]}
if (cfg.onBody) body = cfg.onBody(body)
2016-06-22 01:39:59 +02:00
let req = {
2016-06-22 02:09:02 +02:00
json: true, body: JSON.stringify(body),
2016-06-22 01:39:59 +02:00
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate'
2016-06-22 02:09:02 +02:00
}
2016-06-22 01:39:59 +02:00
}
2016-06-25 01:39:44 +02:00
if (cfg.onReq) req = cfg.onReq(req)
2016-06-22 01:39:59 +02:00
return got.post(cfg.endpoint, req)
.then((res) => {
if (res.body.err) return new Error(res.body.err)
if (!res.body.svcResL || !res.body.svcResL[0]) return new Error('invalid response')
const data = res.body.svcResL[0]
if (data.err !== 'OK') return new Error(data.errTxt)
2016-06-22 02:09:02 +02:00
return cfg.onData || onData(data.res)
2016-06-22 01:39:59 +02:00
}).catch(console.error)
}
module.exports = request