UNPKG

docparse-check-imacros

Version:

check if a given bill already exists in the docparse database using the docparse server REST api

79 lines (75 loc) 2.76 kB
/** * Get a list of existing bills from the DocParse api server */ var rk = require('required-keys'); function validateData(data, cb) { var err = rk.truthySync(data, ['supplierCode', 'billNumber', 'config']) if (err) { return cb(err) } cb() } function getURL(data) { var config = data.config; iimDisplay('building query string'); var queryString = 'supplierCode=' + encodeURIComponent(data.supplierCode) + '&billNumber=' + encodeURIComponent(data.billNumber); iimDisplay('built query string: ' +queryString); var api = config.api var url = 'https://'+ encodeURIComponent(api.email) + ':' + encodeURIComponent(api.password) + '@'+api.host + ':' + api.port + '/api/scrape/check?' + queryString; iimDisplay('got url: ' + url); return url; } function parseResponse(request, cb) { var body = request.response; if (body === 'Unauthorized') { iimDisplay('check failed, "Unauthorized"'); return cb('error checking if scraper should download a bill, body: "Unauthorized"'); } var responseData = JSON.parse(body); var statusCode = request.status; if (statusCode !== 200) { iimDisplay('check failed, bad status code: ' + statusCode); return cb('error checking if scraper should download bill, bad status code: ' + statusCode); } if (!responseData.hasOwnProperty('download')) { iimDisplay('check reply missing "download" field'); return cb('check reply missing "download" property'); } if (!responseData.hasOwnProperty('message')) { iimDisplay('check reply missing "message" field'); return cb('check reply missing "message"" property'); } iimDisplay('check complete with result: ' + JSON.stringify(responseData.download)); cb(null, responseData.download); } module.exports = function(data, cb) { iimDisplay('validating check data'); validateData(data, function (err, reply) { if (err) { return cb(err); } iimDisplay('check data validated'); if (!cb) { iimDisplay('no callback supplied to check data'); alert('no callback supplied to check data'); return; } if (data.billNumbers) { var index = data.billNumbers.indexOf(data.billNumber); if (index >= 0) { var download = false; return cb(null, download); } } iimDisplay('getting url'); var url = getURL(data); iimDisplay('got url: ' + url); var request = new XMLHttpRequest(); var async = false; request.open('GET', url, async); request.send(); // because of "false" above, will block until the request is done and status // is available. Not recommended, however it works for simple cases. iimDisplay('parsing check response: ' + request.response); parseResponse(request, cb); }); };