ShiftScheduler/Services/TransportService.cs
Claudio Schaad a1f9f1313e
Fix find best connection with using of local date time offset (#46)
* Add logger
* Change strings to date time offset
* Fix logic for best connection
* Fix parsing shift times
* set time zone
2025-09-03 22:17:53 +02:00

44 lines
No EOL
1.8 KiB
C#

using Microsoft.Extensions.Caching.Memory;
using ShiftScheduler.Shared;
namespace ShiftScheduler.Services
{
public class TransportService(ITransportApiService transportService, IConfigurationService configurationService, IMemoryCache cache) : ITransportService
{
public async Task<TransportConnection?> GetConnectionAsync(DateTimeOffset shiftStartTime)
{
var config = configurationService.GetTransportConfiguration();
var searchDate = shiftStartTime.ToString("yyyy-MM-dd");
var searchTime = shiftStartTime.AddMinutes(config.MaxLateArrivalMinutes).ToString("HH:mm");
// Generate cache key based on request parameters
var cacheKey = GenerateCacheKey(config, searchDate, searchTime);
// Try to get from cache first
if (cache.TryGetValue(cacheKey, out TransportConnection? cachedConnection) && cachedConnection != null)
{
return cachedConnection;
}
// Not in cache, call the underlying transport service
var connection = await transportService.GetConnectionAsync(shiftStartTime);
// Cache the connection result if valid
if (connection != null)
{
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(config.CacheDurationDays)
};
cache.Set(cacheKey, connection, cacheOptions);
}
return connection;
}
private string GenerateCacheKey(TransportConfiguration config, string searchDate, string searchTime)
{
return $"transport_{config.StartStation}_{config.EndStation}_{searchDate}_{searchTime}";
}
}
}