Class: LucidShopify::SendRequest

Inherits:
Object
  • Object
show all
Defined in:
lib/lucid_shopify/send_request.rb

Defined Under Namespace

Classes: NetworkError

Instance Method Summary collapse

Constructor Details

#initialize(http: Container[:http], strategy: ->(*, &block) { block.() }) ⇒ SendRequest

Returns a new instance of SendRequest.

Parameters:

  • http (HTTP::Client) (defaults to: Container[:http])
  • strategy (#call, nil) (defaults to: ->(*, &block) { block.() })

    unthrottled by default



18
19
20
21
22
# File 'lib/lucid_shopify/send_request.rb', line 18

def initialize(http: Container[:http],
               strategy: ->(*, &block) { block.() })
  @http = http
  @strategy = strategy
end

Instance Method Details

#call(request, attempts: default_attempts) ⇒ Hash

Returns the parsed response body.

Parameters:

  • request (Request)
  • attempts (Integer) (defaults to: default_attempts)

    additional request attempts on client error

Returns:

  • (Hash)

    the parsed response body

Raises:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/lucid_shopify/send_request.rb', line 34

def call(request, attempts: default_attempts)
  req = request

  log_request(req)

  res = @strategy.(req) do
    res = send(req)

    Response.new(req, res.code, res.headers.to_h, res.to_s)
  end

  log_response(req, res)

  res.assert!
rescue HTTP::ConnectionError,
       HTTP::ResponseError,
       HTTP::TimeoutError => e
  raise NetworkError.new(e), e.message if attempts.zero?

  call(req, attempts: attempts - 1)
rescue Response::ClientError => e
  raise e unless e.response.status_code == 429

  sleep(e.response.headers['Retry-After']&.to_f || 0)

  call(req, attempts: attempts)
end

#log_request(request) ⇒ Object

Parameters:



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/lucid_shopify/send_request.rb', line 76

def log_request(request)
  req = request

  LucidShopify.config.logger.info('<%s> [%i] %s %s %s' % [
    self.class.to_s,
    req.object_id,
    req.http_method.to_s.upcase,
    req.url,
    req.options[:params]&.to_json || '{}',
  ])
end

#log_response(request, response) ⇒ Object

Parameters:



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/lucid_shopify/send_request.rb', line 92

def log_response(request, response)
  req = request
  res = response

  LucidShopify.config.logger.info('<%s> [%i] %i (%s)' % [
    self.class.to_s,
    req.object_id,
    res.status_code,
    res.headers['X-Shopify-Shop-Api-Call-Limit'],
  ])
end