Class: NoyoFulfillment::ApiResource

Inherits:
BaseModel
  • Object
show all
Includes:
HTTParty, NoyoApi::Client::UserAgent
Defined in:
lib/noyo_fulfillment/models/api_resource.rb

Constant Summary collapse

@@PAGE_SIZE =
20
@@MAX_AUTH_ATTEMPTS =
5

Class Method Summary collapse

Instance Method Summary collapse

Methods included from NoyoApi::Client::UserAgent

included

Methods inherited from BaseModel

#==, #attributes, class_name, #excluded_attributes, #inspect, #synced_attributes, #to_h, #update_attrs

Constructor Details

#initialize(params = {}) ⇒ ApiResource

Returns a new instance of ApiResource.



14
15
16
17
18
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 14

def initialize(params={})
  super(params)
  # Get the latest config value, in case it changed
  self.class.base_uri(NoyoApi::Api.config.fulfillment_base_uri)
end

Class Method Details

.all(**args) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 126

def self.all(**args)
  page_number = args[:page_number] || 1
  base_uri(NoyoApi::Api.config.fulfillment_base_uri)

  offset = (page_number - 1) * @@PAGE_SIZE
  query = { offset: offset, page_size: @@PAGE_SIZE }
  response = perform_request_authenticated(:get, resource_url(args), query: query)
  api_response = ApiResponse.new(response)
  response_body = api_response.response
  if response_body.empty?
    nil
  else
    if response_body.is_a?(Array)
      results = response_body.map{ |response_item| new(response_item) }
      NoyoFulfillment::ApiResourceCollection.new(results, page_number)
    else
      new(response_body)
    end
  end
end

.authenticateObject



118
119
120
121
122
123
124
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 118

def self.authenticate
  client_id = NoyoApi::Api.config.client_id
  client_secret = NoyoApi::Api.config.client_secret
  service = NoyoAccounts::Client::Services::AuthService.new
  access_token = service.authorize(client_id, client_secret)
  NoyoApi::Api.config.access_token = access_token
end

.find(id, **args) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 147

def self.find(id, **args)
  self.base_uri(NoyoApi::Api.config.fulfillment_base_uri)

  response = perform_request_authenticated(:get, single_resource_url(id, args))
  body = get_body(response)

  if body.nil? || body.empty?
    nil
  else
    new(body)
  end
end

.get_body(response) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 91

def self.get_body(response)
  if response.nil?
    return {}
  end

  body = response.parsed_response
  if body.is_a? String
    parsed_body = JSON.parse(body)
    if parsed_body.is_a?(Hash)
      body = parsed_body.with_indifferent_access
    elsif parsed_body.is_a?(Array)
      body = parsed_body.map(&:with_indifferent_access)
    end
  else
    body
  end
end

.handle_unauthenticated(body) ⇒ Object



160
161
162
163
164
165
166
167
168
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 160

def self.handle_unauthenticated(body)
  if body&.[]('code') == 16
    puts 'Need to reauth' if NoyoApi::Api.config.verbose
    # returns the access token
    return authenticate
  end

  false
end

.headersObject



109
110
111
112
113
114
115
116
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 109

def self.headers
  {
    'Authorization': "Bearer #{NoyoApi::Api.config.access_token}",
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'User-Agent' => user_agent,
  }
end

.perform_request_authenticated(*args) ⇒ Object



40
41
42
43
44
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
80
81
82
83
84
85
86
87
88
89
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 40

def self.perform_request_authenticated(*args)
  if args.length > 2 && !args[2].nil?
    options = args[2]
  else
    options = {}
  end
  recursion_depth = options[:recursion_depth] || 0

  if NoyoApi::Api.config.access_token.nil?
    authenticate
  end

  if !NoyoApi::Api.config.access_token.nil?
    options[:headers] ||= {}
    options[:headers] = options[:headers].merge(headers)

    if NoyoApi::Api.config.verbose
      puts "Calling API with action: #{args[0]}"
      puts "Calling API with URL: #{args[1]}"
      puts "Calling API with options: #{options.to_json}"
    end

    response = send(args[0], args[1], options)
    body = get_body(response)

    case response.code
    when 401
      reauthenticated = handle_unauthenticated(body)
      if reauthenticated
        recursion_depth += 1
        if recursion_depth < @@MAX_AUTH_ATTEMPTS
          options[:recursion_depth] = recursion_depth
          perform_request_authenticated(args[0], args[1], options)
        else
          puts "Couldn't successfully reauthenticate." if NoyoApi::Api.config.verbose
          nil
        end
      end
    when 422
      if NoyoApi::Api.config.verbose
        puts "Body of response: #{body}"
      end
      response
    else
      response
    end
  elsif access_token.nil?
    raise 'Could not log in. Please try again later.'
  end
end

.resource_path_nameObject



20
21
22
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 20

def self.resource_path_name
  class_name.underscore.pluralize
end

.resource_url(**_) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 24

def self.resource_url(**_)
  if self == ApiResource
    message = 'ApiResource is an abstract class. You should perform actions on its subclasses.'
    raise NotImplementedError, message
  end
  "/api/v1/#{resource_path_name}"
end

.single_resource_url(id, **_) ⇒ Object



32
33
34
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 32

def self.single_resource_url(id, **_)
  "#{resource_url}/#{id}"
end

Instance Method Details

#createObject



174
175
176
177
178
179
180
181
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 174

def create
  options = { body: create_hash.to_json }
  response = self.class.perform_request_authenticated(:post, create_url, options)
  body = self.class.get_body(response)
  update_attrs(self.class.new(body))

  self
end

#create_hashObject



170
171
172
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 170

def create_hash
  attributes
end

#create_urlObject



187
188
189
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 187

def create_url
  resource_url
end

#resource_urlObject



183
184
185
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 183

def resource_url
  self.class.resource_url
end

#single_resource_urlObject



36
37
38
# File 'lib/noyo_fulfillment/models/api_resource.rb', line 36

def single_resource_url
  self.class.single_resource_url(self&.id)
end