Sha256: fb0023bdbc28d7960628acfa2d73fe31e9bc1a62f934339ec70b807941095024

Contents?: true

Size: 1.71 KB

Versions: 1

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

require 'request_store'
require 'rest_client'
require 'json-api-vanilla'

module JsonApiToolbox
  class Service
    attr_reader :method, :url, :body

    def initialize(method, url, body)
      @method = method
      @url = url
      @body = body
    end

    def execute
      response = request
      return if response.code == 404
      Service.parse_response(response)
    end

    def request
      RestClient::Request.execute(
        method: method,
        url: url,
        payload: build_body,
        headers: build_header
      )
    rescue RestClient::ExceptionWithResponse => e
      e.response
    end

    def build_header
      headers = {
        'Authorization' => RequestStore.store[:token],
        'Content-Type' => 'application/json'
      }
      headers[:params] = body if method == :get
      headers
    end

    def build_body
      return body if method != :get
    end

    class << self
      def get(url: nil, includes: nil, query_string: nil)
        body = build_query_string(includes, query_string)
        new(:get, url, body).execute
      end

      def post(url: nil, body: nil)
        new(:post, url, body).execute
      end

      def patch(url: nil, body: nil)
        new(:patch, url, body).execute
      end

      def put(url: nil, body: nil)
        new(:put, url, body).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

1 entries across 1 versions & 1 rubygems

Version Path
json_api_toolbox-0.16.0 lib/service.rb