Sha256: 11236332fdc587da1e9050c85ed58cd5bc064e0161d55c2b1acecf703b862372

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

# frozen_string_literal: true

module Lokalise
  module Request
    include Lokalise::BaseRequest
    include Lokalise::Connection

    # Lokalise returns pagination info in special headers
    PAGINATION_HEADERS = %w[x-pagination-total-count x-pagination-page-count x-pagination-limit x-pagination-page].freeze

    def get(path, client, params = {})
      respond_with(
        connection(client).get(prepare(path), params),
        client
      )
    end

    def post(path, client, params = {})
      respond_with(
        connection(client).post(prepare(path), custom_dump(params)),
        client
      )
    end

    def put(path, client, params = {})
      respond_with(
        connection(client).put(prepare(path), custom_dump(params)),
        client
      )
    end

    def patch(path, client, params = {})
      respond_with(
        connection(client).patch(prepare(path), params.any? ? custom_dump(params) : nil),
        client
      )
    end

    def delete(path, client, params = {})
      respond_with(
        # Rubocop tries to replace `delete` with `gsub` but that's a different method here!
        # rubocop:disable Style/CollectionMethods
        connection(client).delete(prepare(path)) do |req|
          # rubocop:enable Style/CollectionMethods
          req.body = custom_dump params
        end,
        client
      )
    end

    private

    def respond_with(response, client)
      body = custom_load response.body
      uri = Addressable::URI.parse response.env.url
      status = response.status
      raise_on_error! status, body
      extract_headers_from(response).
        merge('content' => body,
              'client' => client,
              'path' => uri.path.gsub(%r{/api2/}, ''))
    end

    # Keep only pagination headers
    def extract_headers_from(response)
      response.
        headers.
        to_h.
        keep_if { |k, _v| PAGINATION_HEADERS.include?(k) }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ruby-lokalise-api-5.0.0 lib/ruby-lokalise-api/request.rb