module Dialog::Request

Public Instance Methods

get(path, params: {}) click to toggle source

Performs a HTTP Get request

@param path [String] @param params [Hash]

# File lib/dialog-api/request.rb, line 10
def get(path, params: {})
  request(:get, URI.parse(api_endpoint).merge(path), params: params)
end
patch(path, params: {}, body: {}) click to toggle source

Performs a HTTP Patch request

@param path [String] @param params [Hash] @param body [Hash]

# File lib/dialog-api/request.rb, line 28
def patch(path, params: {}, body: {})
  request(:patch, URI.parse(api_endpoint).merge(path), params: params, body: body)
end
post(path, params: {}, body: {}) click to toggle source

Performs a HTTP Post request

@param path [String] @param params [Hash] @param body [Hash]

# File lib/dialog-api/request.rb, line 19
def post(path, params: {}, body: {})
  request(:post, URI.parse(api_endpoint).merge(path), params: params, body: body)
end

Private Instance Methods

request(method, path, params: {}, body: {}) click to toggle source

@return [HTTP::Client] @raise [ArgumentError]

# File lib/dialog-api/request.rb, line 37
def request(method, path, params: {}, body: {})
  raise ArgumentError, ("Please configure Dialog.api_token first") if api_token.nil? || api_token.empty?
  raise ArgumentError, ("Please configure Dialog.bot_id first") if bot_id.nil? || bot_id.empty?

  headers = {
    'Accept'        => "application/json",
    'Authorization' => "Token #{api_token}",
    'User-Agent'    => Dialog.user_agent
  }

  response = Http.headers(headers).send(method, path, params: params, json: body)

  if debug
    p response
  end

  # Pass on errors when HTTP status included in 400 to 599
  if (400..599).include?(response.code)
    begin
      body = response.parse['error']
    rescue HTTP::Error
      body = nil
    end

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

  # Return parsed json body
  response.parse
end