UNPKG

docparse-add-imacros

Version:

add extracted data to the docparse system using the docparse rest api in an imacros for firefox environment

83 lines (77 loc) 2.45 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', 'config']) if (err) { return cb(err) } var payload = data.payload var payloadKeys = [ 'loginID', 'supplierCode', 'billNumber' ] err = rk.truthySync(payload, payloadKeys) if (err) { return cb(err) } cb(); } function getURL(data) { var config = data.config; var api = config.api var url = 'https://'+ encodeURIComponent(api.email) + ':' + encodeURIComponent(api.password) + '@'+api.host + ':'+api.port + '/api/scrape/add'; return url; } function parseResponse(request, cb) { var body = request.response; if (body === 'Unauthorized') { iimDisplay('add request failed, "Unauthorized"'); return cb('error adding docparse data, body: "Unauthorized"'); } var statusCode = request.status; if (statusCode !== 200) { iimDisplay('add failed, bad status code: ' + statusCode); return cb('error with add request bad status code: ' + statusCode); } var resData = JSON.parse(body); iimDisplay('fetch complete with result: ' + JSON.stringify(resData)); cb(null, resData); } function make_base_auth(user, password) { var tok = user + ':' + password; var hash = btoa(tok); return "Basic " + hash; } module.exports = function(data, cb) { iimDisplay('validating add request data'); validateData(data, function (err, reply) { if (err) { iimDisplay('add request data failed to be validated: ' + err); return cb(err); } iimDisplay('add request data validated'); if (!cb) { iimDisplay('no callback supplied to fetch data'); alert('no callback supplied to fetch data'); return; } iimDisplay('getting url for add request'); var config = data.config; var url = getURL(data); delete data.config; var sendData = JSON.stringify(data); var auth = make_base_auth(config.api.username, config.api.password); var async = false; var xhr = new XMLHttpRequest(); iimDisplay('setting headers'); xhr.open("POST", url, async); xhr.setRequestHeader('Content-Type', 'application/json'); // xhr.setRequestHeader("Authorization", auth); // iimDisplay('headers set'); xhr.send(sendData); iimDisplay('sent post'); iimDisplay('add response: ' + xhr.response); parseResponse(xhr, cb); }); };