Repository URL to install this package:
|
Version:
4.0 ▾
|
require 'get_fitter/error'
module GetFitter
# Wrap request attrs
class Request
FORMAT = 'application/json'
# The format of the HTTP request
# @return [String]
# @api private
attr_accessor :as
# The http method for the request
# @return [Symbol]
# @api private
attr_accessor :method
# The resouce object that we going to call to fetch the data
# @return [Booking, Event, Organisation, User, Venue]
# @api private
attr_accessor :resource
# The remote url for the resource that we want to fetch
# @return [String]
# @api private
attr_accessor :uri
# Extra params we want to send with the http request
# @return [Hash]
# @api private
attr_accessor :params
# Initializer
# @param [Hash] attrs request attributes
# @option attrs [GetFitter::] :resource
# @option attrs [Symbol] :method
# @option attrs [String] :uri
# @option attrs [Hash] :params
# @option attrs [String] :as
# @return [GetFitter::Request]
# @example
# data = Request.new(resource: Event.new(id: 1), uri: "/something")
# @api public
def initialize(attrs)
self.resource = attrs.fetch(:resource)
self.method = attrs.fetch(:method) { :get }
self.uri = attrs.fetch(:uri)
self.as = attrs.fetch(:as) { FORMAT }
self.params = attrs.fetch(:params) { {} }
end
#
# Delegate to the Roar client to fetch data from api
# @return [Booking, Event, Organisation, User, Venue]
# @example
# request.perform_request
# @raise [GetFitter::Error]
# @api public
def fetch
params[:page] = 1
full_resource = resource.send(method, uri: build_uri, as: as).dup
while (resource.entries && !resource.entries.empty?) do
params[:page] += 1
full_resource.entries.concat(
resource.send(method, uri: build_uri, as: as).entries)
end
full_resource
rescue Roar::Transport::Error => e
raise_http_errors(e.response.code.to_i, e.response.msg)
end
def first
fetch.entries.first
end
def first_or_create
first || create
end
def create
# Response will be single entry not collection
klass_name = /(.+)s$/.match(resource.class.name)[1].split('::').last
new_resource = GetFitter.const_get("#{klass_name}").new(params)
new_resource.post(uri: uri, as: as) do |req|
req.add_field('Authorization', 'Bearer ' + params[:token])
end
rescue Roar::Transport::Error => e
raise_http_errors(e.response.code.to_i, e.response.msg)
end
private
#
# Check the response code and raise exceptions if needed
# @param status [Integer]
# @param message [String]
# @return [void]
# @api private
def raise_http_errors(status, message)
error_class = GetFitter::Error.errors[status]
fail(error_class.new(message, status)) if error_class
end
def build_uri
path = URI(uri)
path.query = URI.encode_www_form(params)
path
end
end
end