# frozen_string_literal: true require 'faraday_middleware' module ErpIntegration module Clients # The `FulfilClient` is a simple HTTP client configured to be used for API # requests to the Fulfil endpoints. class FulfilClient attr_reader :api_key, :merchant_id attr_writer :connection, :faraday_adapter def initialize(api_key:, merchant_id:) @api_key = api_key @merchant_id = merchant_id end # Generates the url prefix for the Faraday connection client. # @return [String] The base url for the Fulfil HTTP client def base_url "https://#{merchant_id}.fulfil.io/" end # Sets the default adapter for the Faraday Connection. # @return [Symbol] The default Faraday adapter def faraday_adapter @faraday_adapter ||= Faraday.default_adapter end # Sets up the Faraday connection to talk to the Fulfil API. # @return [Faraday::Connection] The configured Faraday connection def connection @connection ||= Faraday.new(url: base_url) do |faraday| faraday.headers = default_headers faraday.request :json # Encode request bodies as JSON faraday.request :retry # Retry transient failures faraday.response :follow_redirects faraday.response :json # Decode response bodies as JSON # Custom error handling for the error response faraday.use ErpIntegration::Middleware::ErrorHandling # Adapter definition should be last in order to make the json parsers be loaded correctly faraday.adapter faraday_adapter end end %i[delete get patch put post].each do |action_name| define_method(action_name) do |path, options = {}| connection.public_send(action_name, "api/#{version}/#{path}", options).body end end # Sets the default version for the Fulfil API endpoints. # @return [String] The Fulfil API version to be used def version @version ||= 'v2' end private def default_headers { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-API-KEY': api_key } end end end end