Class: Yookassa::Middleware::Idempotency

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/yookassa/middleware/idempotency.rb

Overview

Faraday middleware that ensures POST and DELETE requests include an idempotency key.

If the Idempotence-Key header is not already set, a UUID v4 is generated automatically. This prevents duplicate operations when requests are retried.

Constant Summary collapse

IDEMPOTENCY_HEADER =

YooKassa idempotency header name.

"Idempotence-Key"

Instance Method Summary collapse

Constructor Details

#initialize(app, idempotency_key: nil) ⇒ Idempotency

Returns a new instance of Idempotency.

Parameters:

  • app (#call)

    the next middleware in the Faraday stack

  • idempotency_key (String, nil) (defaults to: nil)

    optional fixed key (mainly for testing)



17
18
19
20
# File 'lib/yookassa/middleware/idempotency.rb', line 17

def initialize(app, idempotency_key: nil)
  super(app)
  @idempotency_key = idempotency_key
end

Instance Method Details

#on_request(env) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/yookassa/middleware/idempotency.rb', line 22

def on_request(env)
  return unless %i[post delete].include?(env.method)

  headers = env.request_headers
  return if headers[IDEMPOTENCY_HEADER]

  headers[IDEMPOTENCY_HEADER] = @idempotency_key || SecureRandom.uuid
end