Class: Lucid::Shopify::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



17
18
19
20
21
# File 'lib/lucid/shopify/send_request.rb', line 17

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:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/lucid/shopify/send_request.rb', line 31

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:



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/lucid/shopify/send_request.rb', line 69

def log_request(request)
  req = request

  Shopify.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:



83
84
85
86
87
88
89
90
91
92
93
# File 'lib/lucid/shopify/send_request.rb', line 83

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

  Shopify.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