Sha256: 4670f39307c739b61820b3c60b4d2b38898195db26783dd419f6c531866fd098

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

# typed: strict
# frozen_string_literal: true

module DearInventory
  class Resource
    extend T::Sig
    extend DearInventory::IsASubclass

    sig do
      params(
        action: Symbol,
        model: T.class_of(DearInventory::Model),
        endpoint: T.nilable(String),
        params: T::Hash[Symbol, T.untyped]
      ).returns(DearInventory::Response)
    end
    def request(action, model:, endpoint: nil, params: {})
      url = resource_url(endpoint)
      params = DearInventory::Parameters.convert(self.class, endpoint, params)
      options = request_params(action, params)

      response = HTTP.headers(headers).public_send(action, url, options)
      DearInventory::Response.new(response: response, model: model)
    end

    private

    URL_BASE = "https://inventory.dearsystems.com/ExternalApi/v2"

    sig { params(endpoint: T.nilable(String)).returns(String) }
    def resource_url(endpoint)
      resource = T.must(self.class.name).split("::").last
      url = "#{URL_BASE}/#{T.must(resource).downcase}"
      url += "/#{endpoint}" unless endpoint.nil?
      url
    end

    sig { returns(T::Hash[Symbol, String]) }
    def headers
      {
        "Content-Type": "application/json",
        "api-auth-accountid": DearInventory.config.require(:account_id),
        "api-auth-applicationkey": DearInventory.config.require(:key),
      }
    end

    sig do
      params(action: Symbol, params: DearInventory::Parameters).
        returns(T::Hash[Symbol, T.untyped])
    end
    def request_params(action, params)
      if action == :get
        { params: params.to_h }
      else
        { json: params.to_h }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dear_inventory-0.2.0 lib/dear_inventory/resource.rb