-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStateManagementController.cs
More file actions
85 lines (76 loc) · 2.87 KB
/
StateManagementController.cs
File metadata and controls
85 lines (76 loc) · 2.87 KB
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
using Dapr.Sample.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Dapr.Sample.WebApi.Controllers
{
/// <summary>
/// Sample showing Dapr State management with controller.
/// </summary>
[ApiController]
public class StateManagementController : ControllerBase
{
/// <summary>
/// State client to interact with Dapr runtime.
/// </summary>
StateClient _stateClient;
/// <summary>
/// State store name.
/// </summary>
const string StoreName = "statestore";
/// <summary>
/// Controller Constructor
/// </summary>
/// <param name="stateClient"></param>
public StateManagementController([FromServices] StateClient stateClient)
{
_stateClient = stateClient;
}
/// <summary>
/// Gets the account information as specified by the id.
/// </summary>
/// <param name="account">Account information for the id from Dapr state store.</param>
/// <returns>Account information.</returns>
[HttpGet("{account}")]
public ActionResult<Account> Get([FromState(StoreName)]StateEntry<Account> account)
{
if (account.Value is null)
{
return NotFound();
}
return account.Value;
}
/// <summary>
/// Method for depositing to account as specified in transaction.
/// </summary>
/// <param name="transaction">Transaction info.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[Topic("deposit")]
[HttpPost("deposit")]
public async Task<ActionResult<Account>> Deposit(Transaction transaction)
{
var state = await _stateClient.GetStateEntryAsync<Account>(StoreName, transaction.Id);
state.Value ??= new Account() { Id = transaction.Id, };
state.Value.Balance += transaction.Amount;
await state.SaveAsync();
return state.Value;
}
/// <summary>
/// Method for withdrawing from account as specified in transaction.
/// </summary>
/// <param name="transaction">Transaction info.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[Topic("withdraw")]
[HttpPost("withdraw")]
public async Task<ActionResult<Account>> Withdraw(Transaction transaction)
{
var state = await _stateClient.GetStateEntryAsync<Account>(StoreName, transaction.Id);
if (state.Value == null)
{
return NotFound();
}
state.Value.Balance -= transaction.Amount;
await state.SaveAsync();
return state.Value;
}
}
}