Files
T120B165/T120B165-ImgBoard/Services/PostService.cs
2025-10-04 13:27:29 +03:00

101 lines
2.9 KiB
C#

using Microsoft.EntityFrameworkCore;
using T120B165_ImgBoard.Data;
using T120B165_ImgBoard.Models;
using T120B165_ImgBoard.Utils;
using File = T120B165_ImgBoard.Models.File;
namespace T120B165_ImgBoard.Services;
public interface IPostService
{
Task<CreatedPost> Create(
string title, string description, List<Tag> tags, User author,
string fileName, string fileContentType, long fileSize);
Task<Post?> GetById(int postId, bool includeUnfinished = false);
Task<PagedList<Post>> GetAll(int pageNumber = 1);
Task<bool> Delete(Post post);
Task<Post> Update(Post post);
}
public record CreatedPost(Post Post, File File);
public class PostService(ImgBoardContext context): IPostService
{
private const int PageSize = 20;
public async Task<CreatedPost> Create(
string title,
string description,
List<Tag> tags,
User author,
string fileName,
string fileContentType,
long fileSize
)
{
var file = new File
{
OriginalFileName = fileName,
Size = fileSize,
ContentType = fileContentType,
FilePath = Path.GetTempFileName(),
CreatedDate = DateTime.Now,
};
await context.Files.AddAsync(file);
var entry = new Post
{
Title = title,
Description = description,
Author = author,
Created = DateTime.Now,
Tags = tags,
File = file
};
await context.Posts.AddAsync(entry);
await context.SaveChangesAsync();
return new CreatedPost(entry, file);
}
public async Task<Post?> GetById(int postId, bool includeUnfinished = false)
{
var query = context.Posts.Where(t => t.Id == postId);
if (!includeUnfinished)
{
query = query.Where(t => t.File.FinishedDate != null);
}
return await query.Include(b => b.Author)
.Include(b => b.Tags)
.Include(b => b.File)
.FirstOrDefaultAsync();
}
public async Task<PagedList<Post>> GetAll(int pageNumber = 1)
{
var totalCount = await context.Posts.Where(p => p.File.FinishedDate != null).CountAsync();
var items = await context.Posts
.Skip((pageNumber - 1) * PageSize)
.Take(PageSize)
.Where(p => p.File.FinishedDate != null)
.Include(b => b.Author)
.Include(b => b.Tags)
.Include(b => b.File)
.ToListAsync();
return new PagedList<Post>(items, pageNumber, PageSize, totalCount);
}
public async Task<bool> Delete(Post post)
{
context.Posts.Remove(post);
await context.SaveChangesAsync();
return true;
}
public async Task<Post> Update(Post post)
{
context.Posts.Update(post);
await context.SaveChangesAsync();
return post;
}
}