Sha256: ab8ee345f73172f06615b8886c3b37e0816392ee796dba6d833b7e75e6e9a70f
Contents?: true
Size: 1.84 KB
Versions: 5
Compression:
Stored size: 1.84 KB
Contents
# frozen_string_literal: true require 'request_store' require 'rest_client' require 'json-api-vanilla' module JsonApiToolbox class Service attr_reader :http_method, :url, :body, :extra_headers def initialize(http_method, url, body, extra_headers = {}) @http_method = http_method @url = url @body = body @extra_headers = extra_headers end def execute Service.parse_response(request) end def request RestClient::Request.execute( method: http_method, url: url, payload: build_body, headers: build_header ) end def build_header headers = { 'Authorization' => RequestStore.store[:token], 'Content-Type' => 'application/json' } headers[:params] = body if http_method == :get headers.merge(extra_headers) end def build_body return if http_method == :get body.is_a?(Hash) ? body.to_json : body end class << self def get(url: nil, includes: nil, query_string: nil, headers: {}) body = build_query_string(includes, query_string) new(:get, url, body, headers).execute end def post(url: nil, body: nil, headers: {}) new(:post, url, body, headers).execute end def patch(url: nil, body: nil, headers: {}) new(:patch, url, body, headers).execute end def put(url: nil, body: nil, headers: {}) new(:put, url, body, headers).execute end def parse_response(response) response_parsed = JSON::Api::Vanilla.parse(response.body) response_parsed.data || response_parsed.errors end def build_query_string(includes, query_string) params = {} params[:includes] = includes if includes params.merge!(query_string) if query_string params end end end end
Version data entries
5 entries across 5 versions & 1 rubygems