public async Task <ConvertedCurrencyValue> ConvertCurrencyAsync(PriceConversionRequest priceConversionRequest)
        {
            if (priceConversionRequest == null)
            {
                throw new ArgumentNullException("Price Conversion request is null");
            }
            await _priceConversionRequestValidator.ValidateAndThrowAsync(priceConversionRequest);

            var exchangeRateApiUrlSection = _configuration.GetSection("ExchangeRateApiUrl");

            if (string.IsNullOrEmpty(exchangeRateApiUrlSection?.Value))
            {
                var error = "Exchange rates API not configured";
                _logger.LogError(error);
                throw new Exception(error);
            }
            var exchangeRateApiUrl = $"{exchangeRateApiUrlSection.Value}/{priceConversionRequest.SourceCurrency}.json";
            var cancellationToken  = new CancellationTokenSource().Token;
            var response           = await _clientWrapper.GetAsync <ExchangeRatesResponse>(exchangeRateApiUrl, cancellationToken).ConfigureAwait(false);

            if (!response.Success || response.Data?.Rates == null)
            {
                return(null);
            }
            var    rates = response.Data.Rates;
            double convertedPrice;

            switch (priceConversionRequest.TargetCurrency.ToUpper())
            {
            case "USD":
                convertedPrice = priceConversionRequest.Price * rates.USD;
                break;

            case "EUR":
                convertedPrice = priceConversionRequest.Price * rates.EUR;
                break;

            case "GBP":
                convertedPrice = priceConversionRequest.Price * rates.GBP;
                break;

            default: return(null);
            }

            if (DateTime.TryParse(response.Data.Date, out var lastUpdated))
            {
                var time = new TimeSpan(response.Data.TimeLastUpdated);
                lastUpdated = lastUpdated.Add(time);
            }
            return(new ConvertedCurrencyValue
            {
                NewPrice = convertedPrice,
                ConvertedFromCurrency = priceConversionRequest.SourceCurrency,
                ConvertedToCurrency = priceConversionRequest.TargetCurrency,
                LastUpdated = lastUpdated
            });
        }
Ejemplo n.º 2
0
        public async Task <ActionResult <ConvertedCurrencyValue> > Get(PriceConversionRequest priceConversionRequest)
        {
            try
            {
                var result = await _priceConversionService.ConvertCurrencyAsync(priceConversionRequest)
                             .ConfigureAwait(false);

                if (result == null)
                {
                    return(NotFound("Currency Not Supported"));
                }
                return(Ok(result));
            }
            catch (Exception)
            {
                return(StatusCode(500, "Server Error"));
            }
        }