Included navigation fields in get queries

This commit is contained in:
Khwezi Mngoma
2026-05-25 23:00:17 +02:00
parent d55bf4f82f
commit 4a85d01d1a
8 changed files with 73 additions and 22 deletions
@@ -1,4 +1,5 @@
using LiteCharms.Features.MidrandBooks.Authors.Models;
using LiteCharms.Features.MidrandBooks.AuthorBooks.Models;
using LiteCharms.Features.MidrandBooks.Authors.Models;
using LiteCharms.Features.MidrandBooks.Extensions;
using LiteCharms.Features.MidrandBooks.Postgres;
using LiteCharms.Features.MidrandBooks.Products.Models;
@@ -8,7 +9,7 @@ namespace LiteCharms.Features.MidrandBooks.Authors;
public class AuthorService(IDbContextFactory<MidrandBooksDbContext> contextFactory)
{
public async ValueTask<Result<Product[]>> GetAuthorBooksAsync(long authorId, CancellationToken cancellationToken)
public async ValueTask<Result<AuthorBook[]>> GetAuthorBooksAsync(long authorId, CancellationToken cancellationToken)
{
try
{
@@ -17,21 +18,24 @@ public class AuthorService(IDbContextFactory<MidrandBooksDbContext> contextFacto
var author = await context.Authors.FirstOrDefaultAsync(a => a.Id == authorId, cancellationToken);
if (author is null)
return Result.Fail<Product[]>(new Error($"Author with ID {authorId} not found"));
return Result.Fail<AuthorBook[]>(new Error($"Author with ID {authorId} not found"));
var books = await context.Books.AsNoTracking()
var books = await context.Books
.AsNoTracking()
.Include(b => b.Author)
.Include(b => b.Product!.Price)
.OrderByDescending(b => b.CreatedAt)
.Where(p => p.AuthorId == authorId)
.Select(p => p.Book.ToModel())
.AsSplitQuery()
.ToArrayAsync(cancellationToken);
return books?.Length > 0
? Result.Ok(books)
: Result.Fail<Product[]>(new Error($"No books found for author with ID {authorId}"));
? Result.Ok(books.Select(b => b.ToModel()).ToArray())
: Result.Fail<AuthorBook[]>(new Error($"No books found for author with ID {authorId}"));
}
catch (Exception ex)
{
return Result.Fail<Product[]>(new Error(ex.Message).CausedBy(ex));
return Result.Fail<AuthorBook[]>(new Error(ex.Message).CausedBy(ex));
}
}