Class: Badgrcat::Client

Inherits:
Footrest::Client
  • Object
show all
Defined in:
lib/badgrcat/client.rb,
lib/badgrcat/client/methods.rb

Defined Under Namespace

Modules: Methods

Instance Method Summary collapse

Instance Method Details

#authenticate!Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/badgrcat/client.rb', line 45

def authenticate!
  connection.headers[:authorization] = nil

  auth_url = config[:auth_url]

  tok_params = {
    scope: config[:scope],
    client_id: config[:client_id],
    client_secret: config[:client_secret],
    grant_type: config[:grant_type],
  }

  tok_params.reject! { |_k, v| v.nil? }

  if @refresh_token
    tok_params.merge!({
      grant_type: "refresh_token",
      refresh_token: @refresh_token,
    })
  else
    tok_params.merge!({
      username: config[:username],
      password: config[:password],
    })
  end

  authresp = connection.send(:post, auth_url, tok_params)
  authdata = authresp.body

  @refresh_token = authdata["refresh_token"].presence || @refresh_token
  connection.headers[:authorization] = "#{authdata['token_type']} #{authdata['access_token']}"

  # Set content type as application/json
  connection.headers['Content-Type'] = "application/json"
end

#delete(path, options = {}) ⇒ Object

Modify delete request to send params in body instead of query params



41
42
43
# File 'lib/badgrcat/client.rb', line 41

def delete(path, options = {})
  request_with_params_in_body(:delete, path, options)
end

#request(method, &block) ⇒ Object

Override Footrest request for ApiArray support



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/badgrcat/client.rb', line 14

def request(method, &block)
  response = begin
    connection.send(method, &block)
  rescue Footrest::HttpError::BadRequest, Footrest::HttpError::NotFound => e
    raise e unless connection.headers[:authorization].nil?

    # Reauthenticate and retry if authorization header is nil
    authenticate!
    connection.send(method, &block)
  rescue Footrest::HttpError::Unauthorized
    # Reauthenticate and retry
    authenticate!
    connection.send(method, &block)
  end

  Badgrcat::ApiArray.process_response(response, self)
end

#request_with_params_in_body(method, path, options) ⇒ Object

Override Footrest request for sending params in body as json



33
34
35
36
37
38
# File 'lib/badgrcat/client.rb', line 33

def request_with_params_in_body(method, path, options)
  request(method) do |r|
    r.path = fullpath(path)
    r.body = options.to_json unless options.empty?
  end
end