# frozen_string_literal: true module Qismo class Client include Qismo::Model include Qismo::Api VALID_OPTIONS = [:app_id, :secret_key, :url, :logger, :instrumentation, :timeout, :proxy] attr_accessor(*VALID_OPTIONS) def initialize(**opt) @app_id = opt[:app_id] || ENV["QISCUS_APP_ID"] @secret_key = opt[:secret_key] || ENV["QISCUS_SECRET_KEY"] @url = opt[:url] || ENV["QISCUS_OMNICHANNEL_URL"] || "https://qismo.qiscus.com" @logger = opt[:logger] @instrumentation = opt[:instrumentation] @timeout = opt[:timeout] @proxy = opt[:proxy] end def post(path, body = {}) request(:post, path, json: body) end def post_upload(path, body = {}) request(:post, form: body) end def get(path, **params) request(:get, path, params) end def request(method, path, **opt) res = connection.request(method, @url + path, opt.compact) if res.status.success? return JSON.parse(res.to_s, object_class: Data) end if res.status.server_error? raise InternalServerError.new("Qiscus Omnichannel server error", status_code: res.code, response_body: res.to_s) end if res.status.client_error? body = JSON.parse(res.to_s, object_class: Data) error = body.errors error = error.message if error.is_a?(Hash) error_klass_map = { 400 => BadRequestError, 401 => UnauthorizedError, 402 => PaymentRequiredError, 403 => ForbiddenError, 404 => NotFoundError, 429 => TooManyRequestError, } error_klass = error_klass_map[res.code] || HTTPRequestError raise error_klass.new(error, status_code: res.code, response_body: res.to_s) end end def connection http = HTTP unless @logger.nil? http = http.use(logging: @logger) end unless @instrumentation.nil? http = http.use(instrumentation: @instrumentation) end unless @timeout.nil? http = if @timeout.is_a?(Hash) http.timeout(**@timeout) else http.timeout(@timeout) end end unless @proxy.nil? http = http.via(*@proxy) end http.headers({ "Qiscus-App-Id": @app_id, "Qiscus-Secret-Key": @secret_key, "User-Agent": user_agent.to_json, }) end def user_agent { lib_version: Qismo::VERSION, lang: "ruby", lang_version: RUBY_VERSION, platform: RUBY_PLATFORM, engine: defined?(RUBY_ENGINE) ? RUBY_ENGINE : "", } end end end