persistence/Persistence.Repository/Repositories/TimeSeriesDataCachedRepository.cs

67 lines
1.8 KiB
C#

using Mapster;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Persistence.Database.Model;
using Persistence.Models;
namespace Persistence.Repository.Repositories;
public class Test {
}
public class TimeSeriesDataCachedRepository<TEntity, TDto> : TimeSeriesDataRepository<TEntity, TDto>
where TEntity : class, ITimestampedData, new()
where TDto : class, ITimeSeriesAbstractDto, new()
{
public static TDto FirstByDate { get; set; } = null!;
public static CyclicArray<TDto> LastData { get; set; } = null!;
public TimeSeriesDataCachedRepository(DbContext db) : base(db)
{
//Task.Run(async () => {
// //FirstByDate = await base.GetFirstAsync(1, CancellationToken.None);
// //LastData = await base.GetLastAsync(3600, CancellationToken.None);
//}).wait();
}
public override async Task<IEnumerable<TDto>> GetAsync(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
{
var cacheLastData = LastData;
if (cacheLastData[0].Date > dateBegin)
{
var dtos = await base.GetAsync(dateBegin, dateEnd, token);
dtos = dtos.OrderBy(x => x.Date);
FirstByDate = dtos.ElementAt(0);
LastData.AddRange(dtos);
return dtos;
}
var items = cacheLastData
.Where(i => i.Date >= dateBegin && i.Date <= dateEnd);
return items;
}
public override async Task<int> InsertRange(IEnumerable<TDto> dtos, CancellationToken token)
{
var result = await base.InsertRange(dtos, token);
if (result > 0)
{
dtos = dtos.OrderBy(x => x.Date);
FirstByDate = dtos.ElementAt(0);
LastData.AddRange(dtos);
}
return result;
}
}