From 844780d805ecb8f4084455fb8f0433766bcf51a9 Mon Sep 17 00:00:00 2001 From: Jannis R Date: Wed, 22 Jun 2016 01:39:59 +0200 Subject: [PATCH] ability to fetch data --- index.js | 29 ++++++++++++++++++++++++++++- package.json | 5 ++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index eba3ac44..9a299187 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,30 @@ 'use strict' -// todo +const got = require('got') + +const request = (cfg) => (data) => { + let req = { + json: true, + 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) + + 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) + return data.res + }).catch(console.error) +} + +module.exports = request diff --git a/package.json b/package.json index 252d4b6d..287f2eea 100644 --- a/package.json +++ b/package.json @@ -10,5 +10,8 @@ "bugs": "https://github.com/derhuerst/hafas-client/issues", "license": "ISC", "keywords": ["hafas", "public", "transport", "api"], - "engines" : {"node": ">=4"} + "engines" : {"node": ">=4"}, + "dependencies": { + "got": "^6.3" + } }