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
- #access_credentials(etsy_account) ⇒ Object
- #attribute(name) ⇒ Object
- #build_objects(response) ⇒ Object
- #check_token_expiration(etsy_account) ⇒ Object
- #handle_response(response) ⇒ Object
- #make_request(request_type, endpoint, options = {}) ⇒ Object
Instance Method Details
#access_credentials(etsy_account) ⇒ Object
42 43 44 45 46 |
# File 'lib/betsy/model.rb', line 42 def access_credentials(etsy_account) header = {x_api_key: Betsy.api_key} header[:Authorization] = "Bearer #{etsy_account.access_token}" if etsy_account.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(etsy_account) if etsy_account.last_token_refresh + etsy_account.expires_in <= DateTime.now = { grant_type: "refresh_token", refresh_token: etsy_account.refresh_token, client_id: Betsy.api_key } response = JSON.parse(Faraday.post("https://api.etsy.com/v3/public/oauth/token", ).body) etsy_account.access_token = response["access_token"] etsy_account.expires_in = response["expires_in"] etsy_account.refresh_token = response["refresh_token"] etsy_account.last_token_refresh = DateTime.now etsy_account.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, = {}) check_token_expiration([:etsy_account]) if [:etsy_account] headers = access_credentials([:etsy_account]) .delete(:etsy_account) if [:post, :put, :patch].include?(request_type) headers = headers.reverse_merge(content_type: "application/json") = .to_json end response = Faraday.send(request_type, "#{BASE_ETSY_API_URL}#{endpoint}", , headers) handle_response(response) end |