using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data; using AsbCloudApp.Repositories; using AsbCloudApp.Requests; using AsbCloudDb; using AsbCloudDb.Model; using Mapster; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; namespace AsbCloudInfrastructure.Repository; public class NotificationRepository : CrudCacheRepositoryBase, INotificationRepository { private static IQueryable MakeQueryNotification(DbSet dbSet) => dbSet.Include(n => n.NotificationCategory) .Include(n => n.User) .AsNoTracking(); public NotificationRepository(IAsbCloudDbContext dbContext, IMemoryCache memoryCache) : base(dbContext, memoryCache, MakeQueryNotification) { } public async Task> GetNotificationsAsync(int idUser, NotificationRequest request, CancellationToken cancellationToken) { var skip = request.Skip ?? 0; var take = request.Take ?? 10; var query = BuildQuery(idUser, request); var result = new PaginationContainer() { Skip = skip, Take = take, Count = await query.CountAsync(cancellationToken), }; if (result.Count < skip) return result; result.Items = await query .SortBy(request.SortFields) .Skip(skip) .Take(take) .AsNoTracking() .Select(x => x.Adapt()) .ToArrayAsync(cancellationToken); return result; } private IQueryable BuildQuery(int idUser, NotificationRequest request) { var query = dbContext.Notifications .Include(x => x.NotificationCategory) .Where(n => n.IdUser == idUser); if (request.IsSent.HasValue) { if(request.IsSent.Value) query = query.Where(n => n.SentDate != null); else query = query.Where(n => n.SentDate == null); } if (request.IdTransportType.HasValue) query = query.Where(n => n.IdTransportType == request.IdTransportType); return query; } }