Sha256: 6c4434584c9fdae5f93733fb993f7a4ff798dad68d7fae0aea409c9fc0db1101

Contents?: true

Size: 1.52 KB

Versions: 4

Compression:

Stored size: 1.52 KB

Contents

require 'http'

require 'flinks/error'

module Flinks
  module Request

    # Performs a HTTP Get request
    #
    # @param path [String]
    # @param params [Hash]
    def get(path, params: {})
      request(:get, URI.parse(api_endpoint).merge(path), params: params)
    end

    # Performs a HTTP Post request
    #
    # @param path [String]
    # @param params [Hash]
    # @param body [Hash]
    def post(path, params: {}, body: {})
      request(:post, URI.parse(api_endpoint).merge(path), params: params, body: body)
    end

    # Performs a HTTP Patch request
    #
    # @param path [String]
    # @param params [Hash]
    # @param body [Hash]
    def patch(path, params: {}, body: {})
      request(:patch, URI.parse(api_endpoint).merge(path), params: params, body: body)
    end


    private

    # @return [HTTP::Client]
    # @raise [Flinks::Error]
    def request(method, path, params: {}, body: {})
      headers = {
        'Accept'     => "application/json",
        'User-Agent' => user_agent
      }

      # Build payload
      payload = body.transform_keys { |k| k.to_s.camelize }

      # Perform request
      response = Http.headers(headers).send(method, path, params: params, json: payload)

      if debug
        p response
      end

      # Pass on errors when HTTP status included in 400 to 599
      if (400..599).include?(response.code)
        raise Error.from_response(response)

        on_error.call(response.code, response.reason, body)
      end

      # Return parsed json body
      response.parse
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
flinks-0.3.0 lib/flinks/request.rb
flinks-0.2.0 lib/flinks/request.rb
flinks-0.1.1 lib/flinks/request.rb
flinks-0.1.0 lib/flinks/request.rb