Skip to content

Instantly share code, notes, and snippets.

@thiagodsalles
Created June 25, 2023 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagodsalles/8d564fca3c01d5ee1977236fa882e750 to your computer and use it in GitHub Desktop.
Save thiagodsalles/8d564fca3c01d5ee1977236fa882e750 to your computer and use it in GitHub Desktop.
api class with response object dealing with exceptions
module ApiService
class Client
class Response
def initialize(code: nil, body: nil)
@code = code
@body = body
end
def success?
return true if (200..299).include?(code)
false
end
private
attr_reader :code, :body
end
def initialize
@user = ENV['SERVICE_USER']
@pass = ENV['SERVICE_PASS']
@client = Faraday.new(
url: ENV['SERVICE_URL'],
headers: { auth: nil }
) do |faraday|
faraday.request :json
faraday.response :json
end
end
delegate :get, :post, :put, :delete, to: :client
def login
params = { params: { user: user, password: pass } }
response = client.post('login', params)
self.token = response.body['result']
rescue Faraday::Error => e
Response.new(body: e.message)
else
Response.new(code: response.code, body: response.body)
end
def logout
response = client.post('logout', { auth: token })
self.token = nil
rescue Faraday::Error => e
Response.new(body: e.message)
else
Response.new(code: response.code, body: response.body)
end
def get_foo(**params)
response = client.get('foo', params)
rescue Faraday::Error => e
Response.new(body: e.message)
else
Response.new(code: response.code, body: response.body)
end
def create_bar(**params)
response = client.post('bar', { params: params })
rescue Faraday::Error => e
Response.new(body: e.message)
else
Response.new(code: response.code, body: response.body)
end
private
attr_reader :user, :pass, :client
def token=(token)
client.headers['auth'] = token
end
def token
client.headers['auth']
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment