# frozen_string_literal: true module PlatformSdk module IdMapper # IdMapper::Client class Client attr_reader :token, :domain, :conn def initialize(secret) @token = secret[:token] @domain = secret[:domain] @token ||= PlatformSdk::IdMapper.token @domain ||= PlatformSdk::IdMapper.domain @conn = Faraday.new("https://#{@domain}") do |faraday| faraday.headers = headers faraday.adapter Faraday.default_adapter faraday.response :json, content_type: /\bjson$/ faraday.response :raise_error end end private def models PlatformSdk::IdMapper::Models end def get(path, params = nil) response = @conn.get(path, params) response.body end def post(path, payload = {}) response = @conn.post(path, payload.to_json, 'Content-Type' => 'application/json') response.body end def headers { "Authorization" => "Token #{@token}" } end def list_of_models(model, list) list.map do |item| model.new(item) end end public def pairs(guid) path = "api/v1/pairs/#{guid}" begin get(path) rescue Faraday::ResourceNotFound raise PlatformSdk::IdMapper::PairNotFoundError, msg = guid end end def create_pair(payload) raise StandardError, "Payload can not be empty." if payload.empty? path = "api/v1/pairs/" post(path, payload) end def domains(**params) path = 'api/v1/domains/' body = get(path, params) list_of_models(models::Domain, body) end def domain_by_name(name) path = "api/v1/domains/#{name}/" body = get(path) models::Domain.new(body) end def domains_by_key(key) path = "api/v1/domains?key=#{key}" body = get(path) list_of_models(models::Domain, body) end def partners(**params) path = 'api/v1/partners/' body = get(path, params) list_of_models(models::Partner, body) end end end end