/
ValuesController.cs
118 lines (101 loc) · 3.58 KB
/
ValuesController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DynamoDbLocalSample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public partial class ValuesController : ControllerBase
{
private const string TableName = "SampleData";
private readonly IAmazonDynamoDB _amazonDynamoDb;
public ValuesController(IAmazonDynamoDB amazonDynamoDb)
{
_amazonDynamoDb = amazonDynamoDb;
}
// GET api/values/init
[HttpGet]
[Route("init")]
public async Task Initialise()
{
var request = new ListTablesRequest
{
Limit = 10
};
var response = await _amazonDynamoDb.ListTablesAsync(request);
var results = response.TableNames;
if (!results.Contains(TableName))
{
var createRequest = new CreateTableRequest
{
TableName = TableName,
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = "Id",
AttributeType = "N"
}
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "Id",
KeyType = "HASH" //Partition key
}
},
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 2,
WriteCapacityUnits = 2
}
};
await _amazonDynamoDb.CreateTableAsync(createRequest);
}
}
// GET api/values/5
[HttpGet("{id}")]
public async Task<ActionResult<string>> Get(int id)
{
var request = new GetItemRequest
{
TableName = TableName,
Key = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = id.ToString() } } }
};
var response = await _amazonDynamoDb.GetItemAsync(request);
if (!response.IsItemSet)
return NotFound();
return response.Item["Title"].S;
}
// POST api/values
[HttpPost]
public async Task Post([FromBody] PostInput input)
{
var request = new PutItemRequest
{
TableName = TableName,
Item = new Dictionary<string, AttributeValue>
{
{ "Id", new AttributeValue { N = input.Id.ToString() }},
{ "Title", new AttributeValue { S = input.Title }}
}
};
await _amazonDynamoDb.PutItemAsync(request);
}
// DELETE api/values/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var request = new DeleteItemRequest
{
TableName = TableName,
Key = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = id.ToString() } } }
};
var response = await _amazonDynamoDb.DeleteItemAsync(request);
return StatusCode((int)response.HttpStatusCode);
}
}
}