Last active
May 7, 2016 18:52
-
-
Save buurzx/863df206ab0e3739b10add3afa5f011f to your computer and use it in GitHub Desktop.
Name of service is changed to Service =)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ServiceClient | |
class ArgumentError < ::ArgumentError; end | |
class ServiceClientError < StandardError; end | |
class ServiceServerError < ServiceClientError; end | |
class Base | |
require 'httparty' | |
BASE_URL = Rails.application.secrets.service['url'] | |
HEADERS = { | |
'Content-Type' => 'application/json' | |
} | |
cattr_reader :client_id | |
@@client_id = ENV['SERVICE_CLIENT_ID'] | |
cattr_reader :client_secret | |
@@client_secret = ENV['SERVICE_CLIENT_SECRET'] | |
attr_reader :access_token | |
def initialize(access_token = nil) | |
@access_token = access_token | |
end | |
def request(type, url, options = {}) | |
result = send(type, url, options) | |
raise ServiceServerError, 'Service is down' if result.code >= 500 | |
raise ServiceServerError, 'Service, page is not found' if result.code == 404 | |
Result.new(result) | |
end | |
private | |
def post(url, options = {}) | |
HTTParty.post("#{BASE_URL}/#{url}", headers: with_access_token(HEADERS), body: options.to_json) | |
end | |
def get(url, options = {}) | |
HTTParty.get("#{BASE_URL}/#{url}", query: options.merge(access_token: access_token)) | |
end | |
def patch(url, options = {}) | |
HTTParty.patch("#{BASE_URL}/#{url}", body: options.to_json, headers: with_access_token(HEADERS)) | |
end | |
def delete(url, options = {}) | |
HTTParty.delete("#{BASE_URL}/#{url}", body: options.to_json, headers: with_access_token(HEADERS)) | |
end | |
def require_access_token! | |
raise ServiceClient::ArgumentError, 'access_token should be present' if access_token.blank? | |
end | |
def with_access_token(headers) | |
if access_token.present? | |
headers.merge('Authorization' => "Bearer #{access_token}") | |
else | |
headers | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment