From 126bc316f0c951b634d523abe913a398f9bed45a Mon Sep 17 00:00:00 2001 From: Jannis R Date: Wed, 22 Jun 2016 02:09:02 +0200 Subject: [PATCH] parse common data --- index.js | 27 +++++++++++++++++++-------- package.json | 3 ++- parse.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 9 deletions(-) create mode 100644 parse.js diff --git a/index.js b/index.js index 9a299187..0bee41ac 100644 --- a/index.js +++ b/index.js @@ -1,19 +1,30 @@ 'use strict' const got = require('got') +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) + if (Array.isArray(c.prodL)) d.locations = c.prodL.map(parse.product) + if (Array.isArray(c.remL)) d.locations = c.remL.map(parse.remark) + if (Array.isArray(c.opL)) d.locations = c.opL.map(parse.agency) + return d +} const request = (cfg) => (data) => { + let body = {lang: 'en', svcReqL: [data]} + if (cfg.onBody) body = cfg.onBody(body) + let req = { - json: true, + json: true, body: JSON.stringify(body), headers: { 'Content-Type': 'application/json', 'Accept-Encoding': 'gzip, deflate' - }, - body: JSON.stringify({ - client: cfg.client, ext: cfg.ext - , ver: cfg.version, auth: cfg.auth - , lang: 'en', svcReqL: [data] - }) + } } if (cfg.req) req = cfg.req(req) @@ -23,7 +34,7 @@ const request = (cfg) => (data) => { 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) - return data.res + return cfg.onData || onData(data.res) }).catch(console.error) } diff --git a/package.json b/package.json index 287f2eea..21cc20dc 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "keywords": ["hafas", "public", "transport", "api"], "engines" : {"node": ">=4"}, "dependencies": { - "got": "^6.3" + "got": "^6.3", + "moment-timezone": "^0.5.4" } } diff --git a/parse.js b/parse.js new file mode 100644 index 00000000..119fb373 --- /dev/null +++ b/parse.js @@ -0,0 +1,43 @@ +'use strict' + + + +const types = {P: 'poi', S: 'station', A: 'address'} +// todo: what is s.rRefL? +const location = (l) => { + const type = types[l.type] || 'unknown' + const result = { + type, name: l.name + , latitude: l.crd ? l.crd.y / 1000000 : null + , longitude: l.crd ? l.crd.x / 1000000 : null + } + if (type === 'poi' || type === 'station') result.id = parseInt(l.extId) + if ('pCls' in l) result.products = l.pCls + return result +} + + + +// todo: what is p.number vs p.line? +// todo: what is p.icoX? +// todo: what is p.cls? +// todo: what is p.oprX? +const product = (p) => { + if (!p.prodCtx) return null + return { + name: p.name, nr: +p.number, class: p.cls, + productCode: +p.prodCtx.catCode, productName: p.prodCtx.catOutS + } +} + + + +const remark = (r) => null // todo + + + +const agency = (a) => a.name +module.exports = { + dateTime, + location, product, remark, agency +}