Add project files
This commit is contained in:
68
T120B165-ImgBoard/Services/CommentService.cs
Normal file
68
T120B165-ImgBoard/Services/CommentService.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
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 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 pageNumber = 1)
|
||||
{
|
||||
var totalCount = await context.Comments.CountAsync();
|
||||
var items = await context.Comments
|
||||
.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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user