Sha256: f66452c47ef81bd148bdbd5fedba922f473c43832ca507f4587b08a3fb9f6370

Contents?: true

Size: 1.51 KB

Versions: 1

Compression:

Stored size: 1.51 KB

Contents

require "faraday"
require "faraday_middleware"

require "twitch/stream"
require "twitch/user"
require "twitch/game"
require "twitch/video"

module Twitch
  class Client
    API_ENDPOINT = "https://api.twitch.tv/helix".freeze

    def initialize(client_id:, access_token: nil)
      headers = {
        "Client-ID": client_id,
        "User-Agent": "twitch-api ruby client #{Twitch::VERSION}"
      }
      unless access_token.nil?
        headers["Authorization"] = "Bearer #{access_token}"
      end
      
      @conn = Faraday.new(API_ENDPOINT, { headers: headers }) do |faraday|
        faraday.response :json
        faraday.adapter Faraday.default_adapter
      end
    end

    def get_streams(options = {})
      res = get('streams', options)

      streams = res.body['data'].map { |s| Stream.new(s) }
    end

    def get_users(options = {})
      res = get('users', options)

      users = res.body['data'].map { |u| User.new(u) }
    end

    def get_games(options = {})
      res = get('games', options)

      games = res.body['data'].map { |g| Game.new(g) }
    end

    def get_videos(options = {})
      res = get('videos', options)

      videos = res.body['data'].map { |v| Video.new(v) }
    end

    private

      def get(resource, params)
        res = @conn.get(resource, params)

        unless res.status == 200
          msg= %Q{The server returned an error.
#{res.body["error"]}: #{res.body["message"]}
Status: #{res.body["status"]}}

          raise Exception.new(msg)
        end

        res
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
twitch-api-0.0.2 lib/twitch/client.rb