UNPKG

tender

Version:

Tender API client

116 lines (99 loc) 3.2 kB
// Generated by CoffeeScript 1.4.0 var TenderUpdate, async, morph, request, tenderUpdate, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; request = require('request'); async = require('async'); morph = require('morph'); TenderUpdate = (function() { function TenderUpdate(client, options, callback) { var _this = this; this.client = client; this.options = options; this.callback = callback; this.update = __bind(this.update, this); this.init = __bind(this.init, this); this.run = __bind(this.run, this); this.options.qs = this.options.qs || {}; if (!(this.client.subdomain && typeof this.client.subdomain === "string")) { return this.callback(new Error("No subdomain specified")); } if (this.client.token) { this.options.qs.auth = this.client.token; } else if (this.client.username || this.client.password) { if (!this.client.username) { return this.callback(new Error("No username specified")); } if (!this.client.password) { return this.callback(new Error("No password specified")); } } else { return this.callback(new Error("No authentication specified")); } this.run(function(err, data) { return _this.callback(err, data); }); } TenderUpdate.prototype.run = function(callback) { return async.waterfall([this.init, this.update, this.finalize], function(err, result) { return callback(err, result); }); }; TenderUpdate.prototype.init = function(callback) { if (this.options.data) { this.options.data = morph.toSnake(this.options.data); } return callback(null); }; TenderUpdate.prototype.update = function(callback) { var options, _this = this; options = { uri: this.options.uri, qs: this.options.qs, json: this.options.data, encoding: 'utf8', method: this.options.method || "POST", headers: { accept: "application/vnd.tender-v1+json" } }; if (!this.client.token) { options.auth = "" + this.client.username + ":" + this.client.password; } return request(options, function(err, response, body) { if (err) { console.log(err); } if (body === "The page you are looking for can\'t be found") { return callback(new Error("Resource not found")); } return callback(null, response, body); }); }; TenderUpdate.prototype.finalize = function(response, body, callback) { var data; if (body === ' ') { data = { result: true, message: 'Action successful' }; } else if (typeof body === 'string') { try { data = JSON.parse(body); } catch (error) { return callback(new Error("(Tender) " + body)); } } else { data = body; } if ((data != null ? data.href : void 0) != null) { data.id = data.href.substring(data.href.lastIndexOf('/') + 1); } return callback(null, data); }; return TenderUpdate; })(); tenderUpdate = function(client, options, callback) { return new TenderUpdate(client, options, callback); }; module.exports = tenderUpdate;