balena-cli/lib/resin/server/server.coffee

77 lines
1.5 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-11-26 16:07:10 +00:00
connection = require('../../connection/connection')
config = require('../../config')
2014-11-26 16:42:10 +00:00
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) ->
connection.isOnline(callback)
(isOnline, callback) ->
if not isOnline
return callback(new Error('You need internet connection to perform this task'))
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
2014-11-18 14:33:24 +00:00
createFacadeFunction = (method) ->
lowerCaseMethod = method.toLowerCase()
exports[lowerCaseMethod] = (url, body, callback) ->
options = {
method
url
}
if _.isFunction(body)
callback = body
else
options.json = body
return exports.request(options, callback)
for method in [
'GET'
'HEAD'
'POST'
'PATCH'
'PUT'
'DELETE'
]
createFacadeFunction(method)