docparse-bills-imacros
Version:
Uses imacros for firefox to get all existing bills for a given supplier code from the docparse server api
58 lines (52 loc) • 1.72 kB
JavaScript
/**
* Get a list of existing bills from the DocParse api server
*/
function validateData(data, cb) {
if (!data.supplierCode) {
return cb('supplier_code field missing from data parameter');
}
if (!data.config) {
return cb('"config" field missing from data parameter');
}
cb();
}
function getURL(data) {
var config = data.config;
var queryString = 'supplierCode='+encodeURIComponent(data.supplierCode);
var url = 'http://'+config.api.username + ':' + config.api.password
+ '@'+String(config.api.host) + ':'+String(config.api.port)
+ '/api/scrape/bills?' + queryString;
return url;
}
function parseResponse(request, cb) {
iimDisplay('getting bills...parsing response now');
var body = request.response;
if (body === 'Unauthorized') {
iimDisplay('getting bills, response says " ' + body + '"');
return cb('error getting logins: "Unauthorized"');
}
var responseData = JSON.parse(body);
var statusCode = request.status;
if (statusCode !== 200) {
return cb('error getting existing bills, bad status code: ' + statusCode);
}
var bills = responseData;
cb(null, bills);
}
module.exports = function(data, cb) {
validateData(data, function (err, reply) {
if (err) { return cb(err); }
if (!cb) {
return cb('you must provide a callback');
}
var url = getURL(data);
iimDisplay('getting bills at: ' + 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.
parseResponse(request, cb);
});
};