crowdstart.js
Version:
Ecommerce SDK for JavaScript and client for Crowdstart.
124 lines (105 loc) • 3.02 kB
JavaScript
// Generated by CoffeeScript 1.10.0
var Xhr, XhrClient, cookie, isFunction, newError, ref, updateQuery;
Xhr = require('xhr-promise-es6');
Xhr.Promise = require('broken');
cookie = require('js-cookie');
ref = require('../utils'), isFunction = ref.isFunction, newError = ref.newError, updateQuery = ref.updateQuery;
module.exports = XhrClient = (function() {
XhrClient.prototype.sessionName = 'crwdst';
function XhrClient(opts) {
if (opts == null) {
opts = {};
}
if (!(this instanceof XhrClient)) {
return new XhrClient(opts);
}
this.endpoint = 'https://api.crowdstart.com';
this.key = opts.key, this.debug = opts.debug;
if (opts.endpoint) {
this.setEndpoint(opts.endpoint);
}
this.getUserKey();
}
XhrClient.prototype.setEndpoint = function(endpoint) {
return this.endpoint = endpoint.replace(/\/$/, '');
};
XhrClient.prototype.setStore = function(id) {
return this.storeId = id;
};
XhrClient.prototype.setKey = function(key) {
return this.key = key;
};
XhrClient.prototype.getKey = function() {
return this.userKey || this.key || this.constructor.KEY;
};
XhrClient.prototype.getUserKey = function() {
var session;
if ((session = cookie.getJSON(this.sessionName)) != null) {
if (session.userKey != null) {
this.userKey = session.userKey;
}
}
return this.userKey;
};
XhrClient.prototype.setUserKey = function(key) {
cookie.set(this.sessionName, {
userKey: key
}, {
expires: 7 * 24 * 3600 * 1000
});
return this.userKey = key;
};
XhrClient.prototype.deleteUserKey = function() {
cookie.set(this.sessionName, {
userKey: null
}, {
expires: 7 * 24 * 3600 * 1000
});
return this.userKey;
};
XhrClient.prototype.getUrl = function(url, data, key) {
if (isFunction(url)) {
url = url.call(this, data);
}
return updateQuery(this.endpoint + url, 'token', key);
};
XhrClient.prototype.request = function(blueprint, data, key) {
var opts;
if (key == null) {
key = this.getKey();
}
opts = {
url: this.getUrl(blueprint.url, data, key),
method: blueprint.method,
data: JSON.stringify(data)
};
if (this.debug) {
console.log('--REQUEST--');
console.log(opts);
}
return (new Xhr).send(opts).then(function(res) {
if (this.debug) {
console.log('--RESPONSE--');
console.log(res);
}
res.data = res.responseText;
return res;
})["catch"](function(res) {
var err, error, ref1;
try {
res.data = (ref1 = res.responseText) != null ? ref1 : JSON.parse(res.xhr.responseText);
} catch (error) {
err = error;
}
err = newError(data, res);
if (this.debug) {
console.log('--RESPONSE--');
console.log(res);
console.log('ERROR:', err);
}
throw err;
});
};
return XhrClient;
})();
//# sourceMappingURL=xhr.js.map