九、Abp vNext 基礎篇丨評論聚合功能

初久的私房菜發表於2021-09-18

介紹

評論本來是要放到標籤裡面去講的,但是因為上一章東西有點多了,我就沒放進去,這一章單獨拿出來,內容不多大家自己寫寫就可以,也算是對前面講解的一個小練習吧。

相關注釋我也加在程式碼上面了,大家看看程式碼都可以理解。

評論倉儲介面和實現

   public interface ICommentRepository : IBasicRepository<Comment, Guid>
    {
        /// <summary>
        /// 根據文章Id 獲取評論
        /// </summary>
        /// <param name="postId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<List<Comment>> GetListOfPostAsync(Guid postId, CancellationToken cancellationToken = default);
        /// <summary>
        /// 根據文章Id 獲取評論數量
        /// </summary>
        /// <param name="postId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<int> GetCommentCountOfPostAsync(Guid postId, CancellationToken cancellationToken = default);
        /// <summary>
        /// 根據評論Id 下面的子獲取評論
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<List<Comment>> GetRepliesOfComment(Guid id, CancellationToken cancellationToken = default);

        Task DeleteOfPost(Guid id, CancellationToken cancellationToken = default);
    }



    public class EfCoreCommentRepository:EfCoreRepository<CoreDbContext, Comment, Guid>,ICommentRepository
    {
        public EfCoreCommentRepository(IDbContextProvider<CoreDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<Comment>> GetListOfPostAsync(Guid postId, CancellationToken cancellationToken = default)
        {
            return await (await GetDbSetAsync())
                .Where(a => a.PostId == postId)
                .OrderBy(a => a.CreationTime)
                .ToListAsync(GetCancellationToken(cancellationToken));
        }

        public async Task<int> GetCommentCountOfPostAsync(Guid postId, CancellationToken cancellationToken = default)
        {
            return await (await GetDbSetAsync())
                .CountAsync(a => a.PostId == postId, GetCancellationToken(cancellationToken));
        }

        public async Task<List<Comment>> GetRepliesOfComment(Guid id, CancellationToken cancellationToken = default)
        {
            return await (await GetDbSetAsync())
                .Where(a => a.RepliedCommentId == id).ToListAsync(GetCancellationToken(cancellationToken));
        }

        public async Task DeleteOfPost(Guid id, CancellationToken cancellationToken = default)
        {
            var recordsToDelete = await (await GetDbSetAsync()).Where(pt => pt.PostId == id).ToListAsync(GetCancellationToken(cancellationToken));
            (await GetDbSetAsync()).RemoveRange(recordsToDelete);
        }
    }


評論介面和Dto

    public interface ICommentAppService : IApplicationService
    {
        Task<List<CommentWithRepliesDto>> GetHierarchicalListOfPostAsync(Guid postId);

        Task<CommentWithDetailsDto> CreateAsync(CreateCommentDto input);

        Task<CommentWithDetailsDto> UpdateAsync(Guid id, UpdateCommentDto input);

        Task DeleteAsync(Guid id);
    }

    public class CommentWithRepliesDto
    {
        public CommentWithDetailsDto Comment { get; set; }

        public List<CommentWithDetailsDto> Replies { get; set; } = new List<CommentWithDetailsDto>();
    }

    public class CommentWithDetailsDto : FullAuditedEntityDto<Guid>
    {
        public Guid? RepliedCommentId { get; set; }

        public string Text { get; set; }

        public BlogUserDto Writer { get; set; }
    }

    public class CreateCommentDto
    {
        public Guid? RepliedCommentId { get; set; }

        public Guid PostId { get; set; }

        [Required]
        public string Text { get; set; }
    }

    public class UpdateCommentDto
    {
        [Required]
        public string Text { get; set; }
    }

介面實現


   public class CommentAppService : CoreAppService, ICommentAppService
    {
        private IUserLookupService<IdentityUser> UserLookupService { get; }

        private readonly ICommentRepository _commentRepository;
        private readonly IGuidGenerator _guidGenerator;

        public CommentAppService(ICommentRepository commentRepository, IGuidGenerator guidGenerator, IUserLookupService<IdentityUser> userLookupService)
        {
            _commentRepository = commentRepository;
            _guidGenerator = guidGenerator;
            UserLookupService = userLookupService;
        }

        public async Task<List<CommentWithRepliesDto>> GetHierarchicalListOfPostAsync(Guid postId)
        {
            // 獲取評論資料
            var comments = await GetListOfPostAsync(postId);

            #region 對評論的作者進行賦值

            var userDictionary = new Dictionary<Guid, BlogUserDto>();

            foreach (var commentDto in comments)
            {
                if (commentDto.CreatorId.HasValue)
                {
                    var creatorUser = await UserLookupService.FindByIdAsync(commentDto.CreatorId.Value);

                    if (creatorUser != null && !userDictionary.ContainsKey(creatorUser.Id))
                    {
                        userDictionary.Add(creatorUser.Id, ObjectMapper.Map<IdentityUser, BlogUserDto>(creatorUser));
                    }
                }
            }

            foreach (var commentDto in comments)
            {
                if (commentDto.CreatorId.HasValue && userDictionary.ContainsKey((Guid)commentDto.CreatorId))
                {
                    commentDto.Writer = userDictionary[(Guid)commentDto.CreatorId];
                }
            }

            #endregion

            var hierarchicalComments = new List<CommentWithRepliesDto>();

            #region 包裝評論資料格式

            // 評論包裝成2級(ps:前面的查詢根據時間排序,這裡不要擔心子集在父級前面)

            foreach (var commentDto in comments)
            {
                var parent = hierarchicalComments.Find(c => c.Comment.Id == commentDto.RepliedCommentId);

                if (parent != null)
                {
                    parent.Replies.Add(commentDto);
                }
                else
                {
                    hierarchicalComments.Add(new CommentWithRepliesDto() { Comment = commentDto });
                }
            }

            hierarchicalComments = hierarchicalComments.OrderByDescending(c => c.Comment.CreationTime).ToList();


            #endregion
          

            return hierarchicalComments;

        }

        public async Task<CommentWithDetailsDto> CreateAsync(CreateCommentDto input)
        {
            // 也可以使用這種方式(這裡只是介紹用法) GuidGenerator.Create()
            var comment = new Comment(_guidGenerator.Create(), input.PostId, input.RepliedCommentId, input.Text);

            comment = await _commentRepository.InsertAsync(comment);

            await CurrentUnitOfWork.SaveChangesAsync();

            return ObjectMapper.Map<Comment, CommentWithDetailsDto>(comment);
        }

        public async Task<CommentWithDetailsDto> UpdateAsync(Guid id, UpdateCommentDto input)
        {
            var comment = await _commentRepository.GetAsync(id);

            comment.SetText(input.Text);

            comment = await _commentRepository.UpdateAsync(comment);

            return ObjectMapper.Map<Comment, CommentWithDetailsDto>(comment);
        }

        public async Task DeleteAsync(Guid id)
        {
            await _commentRepository.DeleteAsync(id);

            var replies = await _commentRepository.GetRepliesOfComment(id);

            foreach (var reply in replies)
            {
                await _commentRepository.DeleteAsync(reply.Id);
            }
        }


        private async Task<List<CommentWithDetailsDto>> GetListOfPostAsync(Guid postId)
        {
            var comments = await _commentRepository.GetListOfPostAsync(postId);

            return new List<CommentWithDetailsDto>(
                ObjectMapper.Map<List<Comment>, List<CommentWithDetailsDto>>(comments));
        }

    }


 CreateMap<Comment, CommentWithDetailsDto>().Ignore(x => x.Writer);

結語

說明:

  • 1.整個評論的實現非常簡單,我們只是實現了一個2層的巢狀。
  • 2.下一章我們講授權和策略大家應該會比較喜歡,加油

聯絡作者:加群:867095512 @MrChuJiu

公眾號

相關文章