Last active
January 10, 2018 08:26
-
-
Save marcus-sa/c59c5a3f3fdbcca3b425678c4972f01f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var superagent = require('superagent'); | |
if (!String.prototype.startsWith) { | |
String.prototype.startsWith = function(search, pos) { | |
return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; | |
} | |
} | |
var methods = ['get', 'post', 'put', 'patch', 'del']; | |
function ApiClient(url) { | |
return function (store) { | |
this.url = url || ''; | |
for (var i; i < methods.length; i++) { | |
var method = methods[i]; | |
this[method] = function (path, options) { | |
options = options || {}; | |
var csrfToken = store.get('csrfToken') || window.__csrf_token | |
return new Promise(function (resolve, reject) { | |
var request = superagent[method](this.formatUrl(path)); | |
if (options.params) { | |
request.query(options.params); | |
} | |
if (csrfToken) { | |
request.set('X-CSRF-Token', csrfToken); | |
} | |
if (options.headers) { | |
request.set(options.headers); | |
} | |
if (this.token) { | |
request.set('Authorization', 'Bearer ' + this.token); | |
} | |
if (option.files) { | |
for (var i; i < options.files.length; i++) { | |
var file = options.files[i]; | |
request.attach(file.key, file.value); | |
} | |
} | |
if (option.fields) { | |
for (var i; i < options.fields.length; i++) { | |
var item = options.fields[i]; | |
request.attach(item.key, item.value); | |
} | |
} | |
if (data) { | |
request.send(data); | |
} | |
request.end(function(err, res) { | |
if (err) { | |
reject(res.body || err); | |
} else { | |
resolve(res.body); | |
} | |
}); | |
}); | |
} | |
} | |
} | |
} | |
ApiClient.prototype.formatUrl = function(path) { | |
if (path.startsWith('//') || path.startsWith('http') || path.startsWith('www')) { | |
return path; | |
} else { | |
var adjustedPath = path[0] !== '/' ? '/' + path : path; | |
return this.url + adjustedPath; | |
} | |
} | |
ApiClient.prototype.setJwtToken = function (token) { | |
this.token = token; | |
} | |
exports['default'] = ApiClient; | |
module.exports = exports['default']; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment