2014-10-31 15:59:23 +00:00
|
|
|
request = require('request')
|
|
|
|
urljoin = require('url-join')
|
2014-11-14 15:05:30 +00:00
|
|
|
async = require('async')
|
2014-10-31 15:59:23 +00:00
|
|
|
config = require('../config')
|
2014-11-14 15:05:30 +00:00
|
|
|
token = require('../token/token')
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
exports.request = (method = 'GET', url, json, callback) ->
|
2014-10-31 15:59:23 +00:00
|
|
|
method = method.toUpperCase()
|
2014-11-18 12:53:07 +00:00
|
|
|
url = urljoin(config.remoteUrl, url)
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
async.waterfall [
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
(callback) ->
|
|
|
|
token.getToken(callback)
|
2014-10-31 17:25:02 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
(savedToken, callback) ->
|
|
|
|
requestOptions = {
|
|
|
|
url
|
|
|
|
method
|
|
|
|
json
|
|
|
|
}
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
if savedToken?
|
|
|
|
requestOptions.headers =
|
|
|
|
'Authorization': "Bearer #{savedToken}"
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
request(requestOptions, callback)
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
(response, body, callback) ->
|
|
|
|
try
|
|
|
|
response.body = JSON.parse(response.body)
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
if response?.statusCode >= 400
|
|
|
|
error = new Error(response.body)
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:53:46 +00:00
|
|
|
return callback(error, response, response.body)
|
2014-10-31 15:59:23 +00:00
|
|
|
|
2014-11-14 15:05:30 +00:00
|
|
|
], callback
|
|
|
|
|
|
|
|
exports.get = (url, callback) ->
|
|
|
|
return exports.request('GET', url, null, callback)
|
|
|
|
|
|
|
|
exports.head = (url, callback) ->
|
|
|
|
return exports.request('HEAD', url, null, callback)
|
|
|
|
|
|
|
|
exports.delete = (url, callback) ->
|
|
|
|
return exports.request('DELETE', url, null, callback)
|
|
|
|
|
|
|
|
exports.post = (url, json, callback) ->
|
|
|
|
return exports.request('POST', url, json, callback)
|
|
|
|
|
|
|
|
exports.put = (url, json, callback) ->
|
|
|
|
return exports.request('PUT', url, json, callback)
|
|
|
|
|
|
|
|
exports.patch = (url, json, callback) ->
|
|
|
|
return exports.request('PATCH', url, json, callback)
|