hn-dotnet/Application/ListLinks/ListLinksQueryHandler.cs
Julien Leicher 3cd5133f66 add-aspnet-identity (#26)
add exception filter when user not connected
default to needing authentication and apply anonymous to some actions
add user in get requests
add user relation in link, comment and vote
signup and in are ok now!
2020-12-11 17:59:35 +01:00

63 lines
2.0 KiB
C#

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<LinkDto> AllAsDto(this DbSet<Link> 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<LinkDto> ToLinkDto(this IQueryable<Link> 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<ListLinksQuery, LinkDto[]>
{
private readonly IHNContext _context;
public ListLinksQueryHandler(IHNContext context)
{
_context = context;
}
public Task<LinkDto[]> Handle(ListLinksQuery request, CancellationToken cancellationToken)
{
var links = from link in _context.Links
join user in _context.Users on link.CreatedBy equals user.Id
select new LinkDto
{
Id = link.Id,
Url = link.Url,
CreatedByName = user.UserName,
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());
}
}
}