Class: TVDBAPIMiddleware

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/tvdb_api/tvdb_api_middleware.rb

Constant Summary collapse

URL =
'https://api4.thetvdb.com/v4/login'

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



7
8
9
10
11
# File 'lib/tvdb_api/tvdb_api_middleware.rb', line 7

def call(env)
  env[:request_headers]['Authorization'] = "Bearer #{fetch_bearer_token}"

  @app.call(env)
end

#fetch_bearer_tokenObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/tvdb_api/tvdb_api_middleware.rb', line 13

def fetch_bearer_token
  api_token = ENV['TVDB_API_TOKEN']
  pin = ENV['TVDB_PIN']

  raise "TVDB_API_TOKEN environment variable is missing" if api_token.nil?
  raise "TVDB_PIN environment variable is missing" if pin.nil?

  return @bearer_token if @bearer_token

  response = Faraday.post(URL) do |req|
    req.headers['Content-Type'] = 'application/json'
    req.body = JSON.generate({
      'apikey': api_token,
      'pin': pin
    })
  end

  raise "Failed to login: #{response.body}" unless response.success?

  @bearer_token = JSON.parse(response.body)['data']['token']
end