Files
T120B165/T120B165-ImgBoard/Services/CommentService.cs

70 lines
2.1 KiB
C#

using Microsoft.EntityFrameworkCore;
using T120B165_ImgBoard.Data;
using T120B165_ImgBoard.Models;
using T120B165_ImgBoard.Utils;
namespace T120B165_ImgBoard.Services;
public interface ICommentService
{
Task<Comment> Create(string text, User author, Post post);
Task<Comment?> GetById(int commentId);
Task<PagedList<Comment>> GetAll(int postId, int pageNumber = 1);
Task<bool> Delete(Comment comment);
Task<Comment> Update(Comment comment);
}
public class CommentService(ImgBoardContext context): ICommentService
{
private const int PageSize = 20;
public async Task<Comment> Create(string text, User author, Post post)
{
var entry = new Comment
{
Text = text,
Author = author,
OriginalPost = post,
Created = DateTime.Now,
};
await context.Comments.AddAsync(entry);
await context.SaveChangesAsync();
return entry;
}
public async Task<Comment?> GetById(int commentId)
{
return await context.Comments.Where(t => t.Id == commentId)
.Include(b => b.Author)
.Include(b => b.OriginalPost)
.FirstOrDefaultAsync();
}
public async Task<PagedList<Comment>> GetAll(int postId, int pageNumber = 1)
{
var totalCount = await context.Comments.Where(c => c.OriginalPost.Id == postId).CountAsync();
var items = await context.Comments
.Where(c => c.OriginalPost.Id == postId)
.Skip((pageNumber - 1) * PageSize)
.Take(PageSize)
.Include(b => b.Author)
.Include(b => b.OriginalPost)
.ToListAsync();
return new PagedList<Comment>(items, pageNumber, PageSize, totalCount);
}
public async Task<bool> Delete(Comment comment)
{
context.Comments.Remove(comment);
await context.SaveChangesAsync();
return true;
}
public async Task<Comment> Update(Comment comment)
{
context.Comments.Update(comment);
await context.SaveChangesAsync();
return comment;
}
}