Class: Gleis::API
- Inherits:
-
Object
- Object
- Gleis::API
- Defined in:
- lib/gleis/api.rb
Overview
This class uses REST over HTTPS to communicate with the API server
Class Method Summary collapse
Class Method Details
.request(method, action, token = nil, body = {}) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/gleis/api.rb', line 6 def self.request(method, action, token = nil, body = {}) url = Config::API_URL + Config::API_VERSION + '/cli/' + action user_agent = RestClient::Platform.default_user_agent + ' Gleis/' + VERSION begin case method when 'get', 'delete' resp = RestClient.send(method, url, 'X-Gleis-Token': token, content_type: :json, accept: :json, user_agent: user_agent) when 'post', 'put' resp = if token RestClient::Request.execute(method: method.to_s, url: url, payload: body.to_json, read_timeout: 600, headers: { 'X-Gleis-Token': token, 'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': user_agent }) else RestClient.send(method, url, body.to_json, content_type: :json, accept: :json, user_agent: user_agent) end when 'stream' stream_output = proc { |response| response.read_body do |chunk| puts chunk end } RestClient::Request.execute(method: :get, url: url, block_response: stream_output, headers: { 'X-Gleis-Token': token }) end rescue RestClient::BadRequest abort('Authentication failed.') rescue RestClient::Unauthorized abort('Not authenticated, please login first.') rescue RestClient::Forbidden => e = if e.response.body.empty? 'You do not have the required permissions, please contact the app owner.' else JSON.parse(e.response.body)['message'] end abort() rescue RestClient::NotFound abort('Application not found.') rescue RestClient::InternalServerError abort('An error occured on the platform. Please contact support if this problem persists.') rescue RestClient::Exceptions::ReadTimeout abort('The request timed out reading data from the platform.') rescue StandardError # (e.g. SocketError, Errno::ECONNREFUSED, RestClient::BadGateway, ...) abort('There was an issue connecting to the Gleis API server.') else # Streaming GET returns Net::HTTPInternalServerError in case of issue and no usable response body # In that case the class of resp.body == Net::ReadAdapter if defined? resp if resp.body.empty? # If there is no body return whole response object resp else # Return Ruby data structure of the JSON parsed body JSON.parse(resp.body) end end end end |