balena-cli/lib/server/server.coffee

57 lines
1.3 KiB
CoffeeScript
Raw Normal View History

2014-10-31 15:59:23 +00:00
request = require('request')
urljoin = require('url-join')
async = require('async')
2014-10-31 15:59:23 +00:00
config = require('../config')
token = require('../token/token')
2014-10-31 15:59:23 +00:00
exports.request = (method = 'GET', url, json, callback) ->
2014-10-31 15:59:23 +00:00
method = method.toUpperCase()
url = urljoin(config.remoteUrl, url)
2014-10-31 15:59:23 +00:00
async.waterfall [
2014-10-31 15:59:23 +00:00
(callback) ->
token.getToken(callback)
(savedToken, callback) ->
requestOptions = {
url
method
json
}
2014-10-31 15:59:23 +00:00
if savedToken?
requestOptions.headers =
'Authorization': "Bearer #{savedToken}"
2014-10-31 15:59:23 +00:00
request(requestOptions, callback)
2014-10-31 15:59:23 +00:00
(response, body, callback) ->
try
response.body = JSON.parse(response.body)
2014-10-31 15:59:23 +00:00
if response?.statusCode >= 400
error = new Error(response.body)
2014-10-31 15:59:23 +00:00
return callback(error, response, response.body)
2014-10-31 15:59:23 +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)