Ejemplo n.º 1
0
        public async Task <Responses.Watcher> AddWatcher(AddWatcher request)
        {
            // Get currency
            var currency = await _mainDbContext.Currencies.FindAsync(request.CurrencyId);

            // Watcher not found
            if (currency == null)
            {
                throw new NotFoundException(CurrencyMessage.CurrencyNotFound);
            }

            // Get user
            var user = await _mainDbContext.Users.FindAsync(request.UserId);

            // User not found
            if (user == null)
            {
                throw new NotFoundException(UserMessage.UserNotFound);
            }

            // Get indicator
            var indicator = await _mainDbContext.Indicators.FindAsync(request.IndicatorId);

            // Indicator not found
            if (indicator == null)
            {
                throw new NotFoundException(IndicatorMessage.IndicatorNotFound);
            }

            // Get watcher
            var watcher = await _mainDbContext.Watchers.FirstOrDefaultAsync(WatcherExpression.Unique(request.UserId, request.CurrencyId, indicator.UserId, indicator.IndicatorId));

            // Watcher already exists
            if (watcher != null)
            {
                throw new ConflictException(new Conflict <AddWatcherConflictReason>(AddWatcherConflictReason.WATCHER_ALREADY_EXISTS, WatcherMessage.WatcherAlreadyExists));
            }

            // Get default watcher
            var defaultWatcher = await _mainDbContext.Watchers.FirstOrDefaultAsync(WatcherExpression.DefaultWatcher(request.CurrencyId, request.IndicatorId));

            // Add watcher
            watcher = new Watcher(
                request.UserId,
                request.CurrencyId,
                indicator.IndicatorId,
                defaultWatcher?.Value,
                null,
                null,
                null,
                defaultWatcher?.AverageBuy,
                defaultWatcher?.AverageSell,
                defaultWatcher?.Price,
                request.Enabled,
                DateTime.UtcNow.StripSeconds());

            // Add
            _mainDbContext.Watchers.Add(watcher);

            // Save
            await _mainDbContext.SaveChangesAsync();

            // Response
            var response = _mapper.Map <Responses.Watcher>(watcher);

            // Log
            _logger.LogInformation("{@Event}, {@UserId}, {@Request}, {@Response}", "WatcherAdded", request.UserId, request, response);

            // Return
            return(response);
        }