// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
namespace ControllerSample.Controllers
{
using System;
using System.Threading.Tasks;
using Dapr;
using Dapr.Client;
using Microsoft.AspNetCore.Mvc;
///
/// Sample showing Dapr integration with controller.
///
[ApiController]
public class SampleController : ControllerBase
{
///
/// State store name.
///
public const string StoreName = "statestore";
///
/// Gets the account information as specified by the id.
///
/// Account information for the id from Dapr state store.
/// Account information.
[HttpGet("{account}")]
public ActionResult Get([FromState(StoreName)]StateEntry account)
{
if (account.Value is null)
{
return this.NotFound();
}
return account.Value;
}
///
/// Method for depositing to account as specified in transaction.
///
/// Transaction info.
/// State client to interact with Dapr runtime.
/// A representing the result of the asynchronous operation.
/// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
[Topic("pubsub", "deposit")]
[HttpPost("deposit")]
public async Task> Deposit(Transaction transaction, [FromServices] DaprClient daprClient)
{
Console.WriteLine("Enter deposit");
var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
state.Value ??= new Account() { Id = transaction.Id, };
state.Value.Balance += transaction.Amount;
await state.SaveAsync();
return state.Value;
}
///
/// Method for withdrawing from account as specified in transaction.
///
/// Transaction info.
/// State client to interact with Dapr runtime.
/// A representing the result of the asynchronous operation.
/// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
[Topic("pubsub", "withdraw")]
[HttpPost("withdraw")]
public async Task> Withdraw(Transaction transaction, [FromServices] DaprClient daprClient)
{
Console.WriteLine("Enter withdraw");
var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
if (state.Value == null)
{
return this.NotFound();
}
state.Value.Balance -= transaction.Amount;
await state.SaveAsync();
return state.Value;
}
}
}