DRAB/Drab.Logic/Utils/DbFetcher.cs
2025-07-11 00:18:14 +02:00

62 lines
1.9 KiB
C#

using Drab.Core.Configuration;
using Drab.Logic.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace Drab.Logic.Utils;
public class DbFetcher : BackgroundService
{
private readonly IDrabSettings _drabSettings;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IOrderProcessor _orderProcessor;
private readonly ILogger _logger;
public DbFetcher(IDrabSettings drabSettings, IServiceScopeFactory serviceScopeFactory, IOrderProcessor orderProcessor)
{
_drabSettings = drabSettings;
_serviceScopeFactory = serviceScopeFactory;
_orderProcessor = orderProcessor;
_logger = LogManager.GetCurrentClassLogger();
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
Start();
return Task.CompletedTask;
}
public async Task Start()
{
await Task.Delay(TimeSpan.FromSeconds(2));
while (true)
{
_logger.Info("Fetch database for new orders");
try
{
using var scope = _serviceScopeFactory.CreateScope();
using var orderStore = scope.ServiceProvider.GetService<IOrdersStore>();
var result = await orderStore.FetchOrders();
if (result.IsNotOk)
_logger.Warn($"Fetch orders result failed: {result.Error}");
result.Value.ToList()
.ForEach(x => _orderProcessor.ProcessOrder(x));
}
catch (Exception e)
{
_logger.Error(e, "Error on fetching new orders data:");
}
finally
{
await Task.Delay(TimeSpan.FromSeconds(_drabSettings.DbPollingFrequencyInSeconds));
}
}
}
}