Module: Betsy::Model::ClassMethods

Defined in:
lib/betsy/model.rb

Constant Summary collapse

BASE_ETSY_API_URL =
"https://openapi.etsy.com"

Instance Method Summary collapse

Instance Method Details

#access_credentials(etsy_account) ⇒ Object



42
43
44
45
46
# File 'lib/betsy/model.rb', line 42

def access_credentials()
  header = {x_api_key: Betsy.api_key}
  header[:Authorization] = "Bearer #{.access_token}" if .present?
  header
end

#attribute(name) ⇒ Object



6
7
8
9
10
# File 'lib/betsy/model.rb', line 6

def attribute(name)
  define_method name do
    @result[name.to_s]
  end
end

#build_objects(response) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/betsy/model.rb', line 58

def build_objects(response)
  if response["count"].nil?
    objects = new(response)
  else
    objects = []
    response["results"].each do |data|
      objects.append(new(data))
    end
    objects
  end
end

#check_token_expiration(etsy_account) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/betsy/model.rb', line 26

def check_token_expiration()
  if .last_token_refresh + .expires_in <= DateTime.now
    options = {
      grant_type: "refresh_token",
      refresh_token: .refresh_token,
      client_id: Betsy.api_key
    }
    response = JSON.parse(Faraday.post("https://api.etsy.com/v3/public/oauth/token", options).body)
    .access_token = response["access_token"]
    .expires_in = response["expires_in"]
    .refresh_token = response["refresh_token"]
    .last_token_refresh = DateTime.now
    .save
  end
end

#handle_response(response) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/betsy/model.rb', line 48

def handle_response(response)
  if response.status == 200
    return nil if response.body.empty?
    response = JSON.parse(response.body)
    build_objects(response)
  else
    Betsy::Error.new(JSON.parse(response.body).merge!("status" => response.status))
  end
end

#make_request(request_type, endpoint, options = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/betsy/model.rb', line 12

def make_request(request_type, endpoint, options = {})
  check_token_expiration(options[:etsy_account]) if options[:etsy_account]
  headers = access_credentials(options[:etsy_account])
  options.delete(:etsy_account)

  if [:post, :put, :patch].include?(request_type)
    headers = headers.reverse_merge(content_type: "application/json")
    options = options.to_json
  end

  response = Faraday.send(request_type, "#{BASE_ETSY_API_URL}#{endpoint}", options, headers)
  handle_response(response)
end