using System.Threading; using System.Linq; using System.Threading.Tasks; using MediatR; using HN.Domain; namespace HN.Application { // public static class LinkQueriesExtensions // { // public static IQueryable AllAsDto(this DbSet links) // { // return from link in links // select new LinkDto // { // Id = link.Id, // Url = link.Url, // CreatedAt = link.CreatedAt, // UpVotes = link.Votes.Count(v => v.Type == VoteType.Up), // DownVotes = link.Votes.Count(v => v.Type == VoteType.Down) // }; // } // public static IQueryable ToLinkDto(this IQueryable links) // { // return links.Select(link => new LinkDto // { // Id = link.Id, // Url = link.Url, // CreatedAt = link.CreatedAt, // UpVotes = link.Votes.Count(v => v.Type == VoteType.Up), // DownVotes = link.Votes.Count(v => v.Type == VoteType.Down) // }); // } // } public sealed class ListLinksQueryHandler : IRequestHandler { private readonly IHNContext _context; public ListLinksQueryHandler(IHNContext context) { _context = context; } public Task Handle(ListLinksQuery request, CancellationToken cancellationToken) { var links = from link in _context.Links select new LinkDto { Id = link.Id, Url = link.Url, CreatedAt = link.CreatedAt, UpVotes = link.Votes.Count(v => v.Type == VoteType.Up), DownVotes = link.Votes.Count(v => v.Type == VoteType.Down) }; return Task.FromResult(links.OrderByDescending(l => l.CreatedAt).ToArray()); } } }