Class: Vox::HTTP::Client

Inherits:
Object
  • Object
show all
Includes:
Routes
Defined in:
lib/vox/http/client.rb

Overview

HTTP Client for interacting with the REST portion of the Discord API

Constant Summary collapse

API_VERSION =

Discord REST API version.

'8'
API_BASE =

Base URL to base endpoints off of.

"https://discord.com/api/v#{API_VERSION}/"
DEFAULT_HEADERS =

Headers that form the base for every request.

{
  'User-Agent': "DiscordBot (https://github.com/swarley/vox, #{Vox::VERSION})"
}.freeze

Instance Method Summary collapse

Methods included from Routes

included

Constructor Details

#initialize(token) {|@conn| ... } ⇒ Client

Returns a new instance of Client.

Yields:

  • (@conn)


46
47
48
49
50
# File 'lib/vox/http/client.rb', line 46

def initialize(token)
  @conn = default_connection
  @conn.authorization('Bot', token.delete_prefix('Bot '))
  yield(@conn) if block_given?
end

Instance Method Details

#request(route, query: nil, data: nil, json: nil, raw: nil, reason: nil) ⇒ Hash?

Run a request

Parameters:

  • query (Hash<String, String>, nil) (defaults to: nil)

    Query string parameters.

  • data (Hash<(String, Integer), (String, #content_type)>, String, nil) (defaults to: nil)

    HTTP body for non-JSON payloads.

  • json (Hash, nil) (defaults to: nil)

    Object that will be serialized to JSON for requests.

  • raw (true, false) (defaults to: nil)

    Whether or not the response body should be parsed from JSON.

  • reason (String, nil) (defaults to: nil)

    Reason for use in paths that support audit log reasons.

Returns:

  • (Hash, nil)

    The response body serialized to a Hash, or nil when a route returns 204.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/vox/http/client.rb', line 60

def request(route, query: nil, data: nil, json: nil, raw: nil, reason: nil)
  req = @conn.build_request(route.verb) do |r|
    setup_basic_request(r, route, query: query, reason: reason)

    if json
      r.body = MultiJson.dump(json)
      r.headers['Content-Type'] = 'application/json'
    elsif data
      r.body = data
    end
  end

  begin
    resp = @conn.builder.build_response(@conn, req)
    handle_response(resp, raw, req.options.context[:trace])
  rescue Error::TooManyRequests
    retry
  end
end