Class: Rack::IdempotencyKey::RedisStore
- Inherits:
-
Object
- Object
- Rack::IdempotencyKey::RedisStore
- Defined in:
- lib/rack/idempotency_key/redis_store.rb
Overview
Redis-based store for handling idempotency keys.
This class provides methods to store, retrieve, and delete idempotency keys in a Redis database, ensuring that the same request is not processed multiple times. It supports both direct Redis instances and connection pools.
Constant Summary collapse
- DEFAULT_EXPIRATION =
5 minutes in seconds
300
Instance Method Summary collapse
-
#get(key) ⇒ Object?
Retrieves a value from Redis by key.
-
#initialize(store, expires_in: DEFAULT_EXPIRATION) ⇒ RedisStore
constructor
Initializes a new RedisStore instance.
-
#set(key, value, ttl: expires_in) ⇒ Object?
Stores a value in Redis with an optional time-to-live (TTL).
-
#unset(key) ⇒ Object
Deletes a key from Redis.
Constructor Details
#initialize(store, expires_in: DEFAULT_EXPIRATION) ⇒ RedisStore
Initializes a new RedisStore instance.
31 32 33 34 |
# File 'lib/rack/idempotency_key/redis_store.rb', line 31 def initialize(store, expires_in: DEFAULT_EXPIRATION) @store = store @expires_in = expires_in end |
Instance Method Details
#get(key) ⇒ Object?
Retrieves a value from Redis by key.
The stored value is expected to be JSON-encoded and is automatically parsed.
If the key does not exist, nil is returned.
48 49 50 51 52 53 |
# File 'lib/rack/idempotency_key/redis_store.rb', line 48 def get(key) value = with_redis { |redis| redis.get(key) } JSON.parse(value) unless value.nil? rescue Redis::BaseError => e raise Rack::IdempotencyKey::StoreError, "#{self.class}: #{e.message}" end |
#set(key, value, ttl: expires_in) ⇒ Object?
Stores a value in Redis with an optional time-to-live (TTL).
This method ensures that the key is only set if it does not already exist (NX flag).
If the key is already present, a ConflictError is raised.
71 72 73 74 75 76 77 78 79 80 |
# File 'lib/rack/idempotency_key/redis_store.rb', line 71 def set(key, value, ttl: expires_in) with_redis do |redis| result = redis.set(key, value, nx: true, ex: ttl) raise Rack::IdempotencyKey::ConflictError unless result end get(key) rescue Redis::BaseError => e raise Rack::IdempotencyKey::StoreError, "#{self.class}: #{e.message}" end |
#unset(key) ⇒ Object
Deletes a key from Redis.
This method removes the idempotency key from Redis, allowing the same request to be processed again in the future.
93 94 95 96 97 |
# File 'lib/rack/idempotency_key/redis_store.rb', line 93 def unset(key) with_redis { |redis| redis.del(key) } rescue Redis::BaseError => e raise Rack::IdempotencyKey::StoreError, "#{self.class}: #{e.message}" end |