Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'aws-sdk'
class MetricsWriter
def initialize(connection_info)
@client = Aws::DynamoDB::Client.new(connection_info)
ensure_tables
end
def ensure_tables
@client.create_table({
table_name: 'metrics',
attribute_definitions: [
{
attribute_name: 'org',
attribute_type: 'S'
},
{
attribute_name: 'unit',
attribute_type: 'S'
}
],
key_schema: [
{
attribute_name: 'org',
key_type: 'HASH'
},
{
attribute_name: 'unit',
key_type: 'range'
}
],
provisioned_throughput: {
read_capacity_units: 1,
write_capacity_units: 1
}
})
end
def save(records)
records.each do |record|
@client.put_item({
'table_name': 'metrics',
item: record
})
end
end
end
RSpec.describe MetricsWriter do
connection_info = {region: 'us-east-1', endpoint: 'http://localhost:8000'}
dynamodb = Aws::DynamoDB::Client.new(connection_info)
before(:each) do
tables = dynamodb.list_tables.table_names
if tables.include?('metrics')
dynamodb.delete_table({
table_name: 'metrics',
})
end
end
it 'saves metering records' do
metrics_records = [
{
'org': 'my-org-1',
'unit': 'ops',
'at': '2016-02-28T11:21:33+05:30',
'data': [{'id': 'p1', 'result': 'pass'}, {'id': 'p2', 'result': 'fail'}]
},
{
'org': 'my-org-1',
'unit': 'dev',
'at': '2016-02-29T12:22:33+05:30',
'data': [{'id': 'p1', 'result': 'pass'}, {'id': 'p2', 'result': 'fail'}]
},
{
'org': 'my-org-2',
'unit': 'fin',
'at': '2016-02-29T13:23:33+05:30',
'data': [{'id': 'p1', 'result': 'pass'}, {'id': 'p2', 'result': 'fail'}]
}
]
MetricsWriter.new(connection_info).save(metrics_records)
response = dynamodb.query({
table_name: 'metrics',
select: 'COUNT',
key_condition_expression: "org = :v_org",
expression_attribute_values: {
":v_org": 'my-org-1',
},
return_consumed_capacity: 'TOTAL'
})
expect(response.count).to eql(2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment