Пример #1
0
        /// <summary>
        /// Deposit
        /// </summary>
        /// <param name="transaction"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <GrpcService.Account> Deposit(GrpcService.Transaction transaction, ServerCallContext context)
        {
            _logger.LogDebug("Enter deposit");
            var state = await _daprClient.GetStateEntryAsync <Models.Account>(StoreName, transaction.Id);

            state.Value ??= new Models.Account()
            {
                Id = transaction.Id,
            };
            state.Value.Balance += transaction.Amount;
            await state.SaveAsync();

            return(new GrpcService.Account()
            {
                Id = state.Value.Id, Balance = (int)state.Value.Balance,
            });
        }
Пример #2
0
        /// <summary>
        /// Withdraw
        /// </summary>
        /// <param name="transaction"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <GrpcService.Account> Withdraw(GrpcService.Transaction transaction, ServerCallContext context)
        {
            _logger.LogDebug("Enter withdraw");
            var state = await _daprClient.GetStateEntryAsync <Models.Account>(StoreName, transaction.Id);

            if (state.Value == null)
            {
                throw new Exception($"NotFound: {transaction.Id}");
            }

            state.Value.Balance -= transaction.Amount;
            await state.SaveAsync();

            return(new GrpcService.Account()
            {
                Id = state.Value.Id, Balance = (int)state.Value.Balance,
            });
        }
Пример #3
0
        /// <summary>
        /// implement OnTopicEvent to handle deposit and withdraw event
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task <TopicEventResponse> OnTopicEvent(TopicEventRequest request, ServerCallContext context)
        {
            if (request.PubsubName == "pubsub")
            {
                var input       = JsonSerializer.Deserialize <Models.Transaction>(request.Data.ToStringUtf8(), this.jsonOptions);
                var transaction = new GrpcService.Transaction()
                {
                    Id = input.Id, Amount = (int)input.Amount,
                };
                if (request.Topic == "deposit")
                {
                    await Deposit(transaction, context);
                }
                else
                {
                    await Withdraw(transaction, context);
                }
            }

            return(await Task.FromResult(default(TopicEventResponse)));
        }