summaryrefslogtreecommitdiff
path: root/src/twitch/rest.cr
blob: 1de8d6f26b509e4a63feb0192711f8a40436becd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require "http"
require "json"
require "./mappings/*"

module Twitcr::REST
  # Mixin for interacting with Twitch's REST API
  SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
  API_BASE    = "https://api.twitch.tv/helix"

  EMPTY_RESULT = Exception.new("Empty Result")

  # Executes an HTTP request against the API_BASE url
  def request(method : String, route : String, version = "5", headers = HTTP::Headers.new, body : String? = nil)
    headers["Authorization"] = @token
    headers["Client-ID"] = @client_id

    response = HTTP::Client.exec(
      method,
      API_BASE + route,
      headers,
      tls: SSL_CONTEXT
    )

    response.body
  end

  def get_user_by_login(login : String)
    response = request(
      "GET",
      "/users?login=" + login
    )

    list = UserList.from_json(response)
    raise EMPTY_RESULT if list.data.empty?

    list.data.first
  end

  def get_user_by_id(id : Int64)
    response = request(
      "GET",
      "/users?id=" + id.to_s
    )

    list = UserList.from_json(response)
    raise EMPTY_RESULT if list.data.empty?

    list.data.first
  end
end