Class: CredStash::Repository::DynamoDB

Inherits:
Object
  • Object
show all
Defined in:
lib/cred_stash/repository.rb

Instance Method Summary collapse

Constructor Details

#initialize(client: nil) ⇒ DynamoDB

Returns a new instance of DynamoDB.



15
16
17
# File 'lib/cred_stash/repository.rb', line 15

def initialize(client: nil)
  @client = client || Aws::DynamoDB::Client.new
end

Instance Method Details

#delete(item) ⇒ Object



80
81
82
83
84
85
86
87
88
# File 'lib/cred_stash/repository.rb', line 80

def delete(item)
  @client.delete_item(
    table_name: CredStash.config.table_name,
    key: {
      name: item.name,
      version: item.version
    }
  )
end

#get(name) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/cred_stash/repository.rb', line 19

def get(name)
  select(name, limit: 1).first.tap do |item|
    unless item
      raise CredStash::ItemNotFound, "#{name} is not found"
    end
  end
end

#listObject



70
71
72
73
74
75
76
77
78
# File 'lib/cred_stash/repository.rb', line 70

def list
  @client.scan(
    table_name: CredStash.config.table_name,
    projection_expression: '#name, version',
    expression_attribute_names: { "#name" => "name" },
  ).items.map do |item|
    Item.new(name: item['name'], version: item['version'])
  end
end

#put(item) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/cred_stash/repository.rb', line 55

def put(item)
  @client.put_item(
    table_name: CredStash.config.table_name,
    item: {
      name: item.name,
      version: item.version,
      key: item.key,
      contents: item.contents,
      hmac: item.hmac
    },
    condition_expression: "attribute_not_exists(#name)",
    expression_attribute_names: { "#name" => "name" },
  )
end

#select(name, pluck: nil, limit: nil) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/cred_stash/repository.rb', line 27

def select(name, pluck: nil, limit: nil)
  params = {
    table_name: CredStash.config.table_name,
    consistent_read: true,
    key_condition_expression: "#name = :name",
    expression_attribute_names: { "#name" => "name"},
    expression_attribute_values: { ":name" => name }
  }

  if pluck
    params[:projection_expression] = pluck
  end

  if limit
    params[:limit] = limit
    params[:scan_index_forward] = false
  end

  @client.query(params).items.map do |item|
    Item.new(
      key: item["key"],
      contents: item["contents"],
      name: item["name"],
      version: item["version"]
    )
  end
end