Class: Leetcoder::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/leetcoder/leetcoder/client.rb

Defined Under Namespace

Classes: ApiError, AuthenticationError, InvalidCookie

Instance Method Summary collapse

Constructor Details

#initialize(_args = {}) ⇒ Client

Returns a new instance of Client.



13
14
15
# File 'lib/leetcoder/leetcoder/client.rb', line 13

def initialize(_args = {})
  @cookie = ENV.fetch('LEETCODE_COOKIE', nil) || read_cookie
end

Instance Method Details

#call(request_type, endpoint, payload: {}, params: {}) ⇒ Object

request_type: [get, post, put, delete] endpoint: part of the url after base url payload: request body payload params: filter params



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/leetcoder/leetcoder/client.rb', line 22

def call(request_type, endpoint, payload: {}, params: {})
  response = connection.public_send(request_type, endpoint) do |req|
    req.body = payload
    req.params = params
    req.headers['Cookie'] = cookie
    req.headers['Referer'] = BASE_URL
    req.headers['X-csrftoken'] = x_csrftoken
  end

  return response if valid_response?(response)

  client_error_handler(response)
end

#connectionObject



36
37
38
39
40
41
42
43
44
# File 'lib/leetcoder/leetcoder/client.rb', line 36

def connection
  @connection ||= Faraday.new(url: Leetcoder::BASE_URL) do |f|
    f.request :json
    f.response :json, content_type: /\bjson$/, parser_options: { symbolize_names: true }
    f.request :multipart
    f.adapter :net_http
    f.request :retry, retry_options
  end
end