using System.Collections.Generic;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using RoboforkApp.AWS.Contracts;
using Amazon;
namespace RoboforkApp.AWS.DynamoDb
{
public class DynamoService : ITableDataService
{
const string AWS_ACCESS_KEY = "AKIAI3CHRBBEA5I4WOMA";
const string AWS_SECRET_KEY = "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";
public readonly DynamoDBContext DbContext;
public AmazonDynamoDBClient DynamoClient;
public DynamoService()
{
DynamoClient = new AmazonDynamoDBClient(AWS_ACCESS_KEY, AWS_SECRET_KEY, RegionEndpoint.APNortheast1);
DbContext = new DynamoDBContext(DynamoClient, new DynamoDBContextConfig
{
//Setting the Consistent property to true ensures that you'll always get the latest
ConsistentRead = true,
SkipVersionCheck = true
});
}
///
/// The Store method allows you to save a POCO to DynamoDb
///
///
///
public void Store(T item) where T : new()
{
DbContext.Save(item);
}
///
/// The BatchStore Method allows you to store a list of items of type T to dynamoDb
///
///
///
public void BatchStore(IEnumerable items) where T : class
{
var itemBatch = DbContext.CreateBatchWrite();
foreach (var item in items)
{
itemBatch.AddPutItem(item);
}
itemBatch.Execute();
}
///
/// Uses the scan operator to retrieve all items in a table
/// [CAUTION] This operation can be very expensive if your table is large
///
///
///
public IEnumerable GetAll() where T : class
{
IEnumerable items = DbContext.Scan();
return items;
}
///
/// Retrieves an item based on a search key
///
///
///
///
public T GetItem(string key) where T : class
{
return DbContext.Load(key);
}
///
/// Method Updates and existing item in the table
///
///
///
public void UpdateItem(T item) where T : class
{
T savedItem = DbContext.Load(item);
if (savedItem == null)
{
throw new AmazonDynamoDBException("The item does not exist in the Table");
}
DbContext.Save(item);
}
///
/// Deletes an Item from the table.
///
///
///
public void DeleteItem(T item)
{
var savedItem = DbContext.Load(item);
if (savedItem == null)
{
throw new AmazonDynamoDBException("The item does not exist in the Table");
}
DbContext.Delete(item);
}
}
}