using Microsoft.AspNetCore.Mvc.RazorPages; using NetinaShop.Domain.Entities.Blogs; using static Microsoft.EntityFrameworkCore.DbLoggerCategory; namespace NetinaShop.Api.Controller; public class BlogController : ICarterModule { public virtual void AddRoutes(IEndpointRouteBuilder app) { var group = app.NewVersionedApi("Blog") .MapGroup($"api/blog") .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser()); group.MapGet("", GetAllAsync) .WithDisplayName("GetAllBlogs") .HasApiVersion(1.0); group.MapGet("{id}", GetAsync) .WithDisplayName("GetBlog") .HasApiVersion(1.0); group.MapPost("", Post) .HasApiVersion(1.0); group.MapPut("", Put) .HasApiVersion(1.0); group.MapDelete("{id}", Delete) .HasApiVersion(1.0); } // GET:Get All Entity public async Task GetAllAsync([FromQuery] int page, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken) => TypedResults.Ok(await repositoryWrapper.SetRepository().TableNoTracking.OrderByDescending(b=>b.CreatedAt).Skip(page*10).Take(10).ToListAsync(cancellationToken)); // GET:Get An Entity By Id public async Task GetAsync(Guid id, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken) => TypedResults.Ok(await repositoryWrapper.SetRepository().TableNoTracking.Where(b=>b.Id==id).FirstOrDefaultAsync(cancellationToken)); // POST:Create Entity public async Task Post([FromBody] Blog ent, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken) { repositoryWrapper.SetRepository().Add(ent); await repositoryWrapper.SaveChangesAsync(cancellationToken); return TypedResults.Ok(); } // PUT:Update Entity public async Task Put([FromBody] Blog updated, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken) { var ent = await repositoryWrapper.SetRepository().TableNoTracking .FirstOrDefaultAsync(b => b.Id == updated.Id, cancellationToken); if (ent == null) throw new AppException("Blog not found"); repositoryWrapper.SetRepository().Update(updated); await repositoryWrapper.SaveChangesAsync(cancellationToken); return TypedResults.Ok(); } // DELETE:Delete Entity public async Task Delete(Guid id, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken) { var ent = await repositoryWrapper.SetRepository().TableNoTracking .FirstOrDefaultAsync(b => b.Id == id, cancellationToken); if (ent == null) throw new AppException("Blog not found"); repositoryWrapper.SetRepository().Delete(ent); await repositoryWrapper.SaveChangesAsync(cancellationToken); return TypedResults.Ok(); } }