balena-cli/lib/server/server.coffee

84 lines
1.6 KiB
CoffeeScript
Raw Normal View History

2014-11-18 13:59:19 +00:00
_ = require('lodash')
2014-10-31 15:59:23 +00:00
request = require('request')
urlResolve = require('url').resolve
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
2014-11-18 13:59:19 +00:00
exports.request = (options = {}, callback) ->
if not options.url?
throw new Error('Missing 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) ->
2014-11-18 13:59:19 +00:00
options.url = urlResolve(config.remoteUrl, options.url)
if options.method?
options.method = options.method.toUpperCase()
_.defaults options,
method: 'GET'
2014-11-18 14:05:38 +00:00
gzip: true
2014-10-31 15:59:23 +00:00
if savedToken?
options.headers ?= {}
_.extend options.headers,
'Authorization': "Bearer #{savedToken}"
2014-10-31 15:59:23 +00:00
2014-11-18 13:59:19 +00:00
request(options, 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) ->
2014-11-18 13:59:19 +00:00
return exports.request {
method: 'GET'
url: url
}, callback
exports.head = (url, callback) ->
2014-11-18 13:59:19 +00:00
return exports.request {
method: 'HEAD'
url: url
}, callback
exports.delete = (url, callback) ->
2014-11-18 13:59:19 +00:00
return exports.request {
method: 'DELETE'
url: url
}, callback
exports.post = (url, json, callback) ->
2014-11-18 13:59:19 +00:00
return exports.request {
method: 'POST'
url: url
json: json
}, callback
exports.put = (url, json, callback) ->
2014-11-18 13:59:19 +00:00
return exports.request {
method: 'PUT'
url: url
json: json
}, callback
exports.patch = (url, json, callback) ->
2014-11-18 13:59:19 +00:00
return exports.request {
method: 'PATCH'
url: url
json: json
}, callback