require 'http/rest_client' require 'ostruct' module Fluxx # Base endpoint resources class class Resource < OpenStruct extend HTTP::RestClient::DSL extend HTTP::RestClient::CRUD PAGINATION_FIELDS = [ 'total_pages', 'total_entries', 'current_page', 'per_page' ] endpoint ENV['FLUXX_INSTANCE_URL'] content_type 'application/json' # Defines the client endpoint. Thread-safe. # # @param value [String] the endpoint URI. # @return [String] def endpoint(value = nil) return super(value) unless value.nil? Thread.current.thread_variable_get(:FLUXX_INSTANCE_URL) || super end # Updated request handler with the auto-refreshing token authentication # # @param payload [Hash] request payload. # @return [HTTP::Response] instance. def self.request(*args) auth("Bearer #{Token.fresh.access_token}") unless self == Token super(*args) end # Resource constructor wrapper # # @param payload [Hash] response payload to build a resource. # @return [Object] instance or a list of instances. def self.objectify(payload) filtered = payload.reject { |key, _| PAGINATION_FIELDS.include?(key) } data = filtered.values.first if filtered.is_a?(Hash) && filtered.size == 1 data = data.values.first if data.is_a?(Hash) && data.size == 1 super(data || payload) end end end