Class: Clarion::Counters::Dynamodb

Inherits:
Base
  • Object
show all
Defined in:
lib/clarion/counters/dynamodb.rb

Instance Method Summary collapse

Constructor Details

#initialize(table_name:, region:) ⇒ Dynamodb

Returns a new instance of Dynamodb.



7
8
9
10
# File 'lib/clarion/counters/dynamodb.rb', line 7

def initialize(table_name:, region:)
  @table_name = table_name
  @region = region
end

Instance Method Details

#dynamodbObject



39
40
41
# File 'lib/clarion/counters/dynamodb.rb', line 39

def dynamodb
  @dynamodb ||= Aws::DynamoDB::Resource.new(region: @region)
end

#get(key) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/clarion/counters/dynamodb.rb', line 12

def get(key)
  item = table.query(
    limit: 1,
    select: 'ALL_ATTRIBUTES',
    key_condition_expression: 'handle = :handle',
    expression_attribute_values: {":handle" => key.handle},
  ).items.first

  item && item['key_counter']
end

#store(key) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/clarion/counters/dynamodb.rb', line 23

def store(key)
  table.update_item(
    key: {
      'handle' => key.handle,
    },
    update_expression: 'SET key_counter = :new',
    condition_expression: 'attribute_not_exists(key_counter) OR key_counter < :new',
    expression_attribute_values: {':new' => key.counter},
  )
rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException
end

#tableObject



35
36
37
# File 'lib/clarion/counters/dynamodb.rb', line 35

def table
  @table ||= dynamodb.table(@table_name)
end