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

90 lines
1.9 KiB
CoffeeScript
Raw Normal View History

2014-11-18 09:59:19 -04:00
_ = require('lodash')
2014-10-31 11:59:23 -04:00
request = require('request')
progress = require('request-progress')
urlResolve = require('url').resolve
async = require('async')
2014-11-26 12:07:10 -04:00
connection = require('../../connection/connection')
settings = require('../settings')
2014-11-26 12:42:10 -04:00
token = require('../token/token')
2014-10-31 11:59:23 -04:00
2014-12-02 10:57:47 -04:00
exports.request = (options = {}, outerCallback, onProgress) ->
onProgress ?= _.noop
2014-11-18 09:59:19 -04:00
if not options.url?
throw new Error('Missing URL')
2014-10-31 11:59:23 -04:00
async.waterfall [
2014-10-31 11:59:23 -04: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) ->
options.url = urlResolve(settings.remoteUrl, options.url)
2014-11-18 09:59:19 -04:00
if options.method?
options.method = options.method.toUpperCase()
_.defaults options,
method: 'GET'
2014-11-18 10:05:38 -04:00
gzip: true
2014-10-31 11:59:23 -04:00
if savedToken?
options.headers ?= {}
_.extend options.headers,
'Authorization': "Bearer #{savedToken}"
2014-10-31 11:59:23 -04:00
2014-12-02 10:57:47 -04:00
if options.pipe?
progress(request(options))
.on('progress', onProgress)
.on('error', outerCallback)
.on('end', onProgress)
.pipe(options.pipe)
.on('error', outerCallback)
.on('close', outerCallback)
else
return request(options, callback)
2014-10-31 11:59:23 -04:00
(response, body, callback) ->
try
response.body = JSON.parse(response.body)
2014-10-31 11:59:23 -04:00
if response?.statusCode >= 400
error = new Error(response.body)
2014-10-31 11:59:23 -04:00
return callback(error, response, response.body)
2014-10-31 11:59:23 -04:00
2014-12-02 10:57:47 -04:00
], outerCallback
2014-11-18 10:33:24 -04:00
createFacadeFunction = (method) ->
lowerCaseMethod = method.toLowerCase()
exports[lowerCaseMethod] = (url, body, callback, onProgress) ->
2014-11-18 10:33:24 -04:00
options = {
method
url
}
if _.isFunction(body)
onProgress = callback
2014-11-18 10:33:24 -04:00
callback = body
else
options.json = body
return exports.request(options, callback, onProgress)
2014-11-18 10:33:24 -04:00
for method in [
'GET'
'HEAD'
'POST'
'PATCH'
'PUT'
'DELETE'
]
createFacadeFunction(method)