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
@@ -30,7 +30,7 @@ public class BooksService(IDbContextFactory<MidrandBooksDbContext> contextFactor
}
}
public async ValueTask<Result<long>> PublishBookAsync(long authorId, long productId, CancellationToken cancellationToken = default)
public async ValueTask<Result<long>> CreateBookAsync(long authorId, long productId, CancellationToken cancellationToken = default)
{
try
{
@@ -65,7 +65,11 @@ public class BooksService(IDbContextFactory<MidrandBooksDbContext> contextFactor
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var book = await context.Books
.AsNoTracking().FirstOrDefaultAsync(b => b.Id == bookId, cancellationToken);
.AsNoTracking()
.Include(b => b.Author)
.Include(b => b.Product!.Price)
.Include(b => b.Pages)
.FirstOrDefaultAsync(b => b.Id == bookId, cancellationToken);
return book is null
? Result.Fail<AuthorBook>(new Error($"Book with ID {bookId} not found"))
@@ -88,6 +92,8 @@ public class BooksService(IDbContextFactory<MidrandBooksDbContext> contextFactor
var books = await context.Books
.AsNoTracking()
.Include(b => b.Author)
.Include(b => b.Product!.Price)
.OrderByDescending(b => b.CreatedAt)
.Where(b => b.AuthorId == authorId)
.ToListAsync(cancellationToken);
@@ -101,4 +107,34 @@ public class BooksService(IDbContextFactory<MidrandBooksDbContext> contextFactor
return Result.Fail<AuthorBook[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<AuthorBook[]>> GetPublishedBooksAsync(int offset, int limit, CancellationToken cancellationToken = default)
{
try
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var books = await context.Books
.AsNoTracking()
.Include(b => b.Author)
.Include(b => b.Product!.Price)
.Include(b => b.Pages)
.Where(b => b.Enabled && b.Product!.Enabled && b.Author.Enabled)
.OrderByDescending(b => b.Ranking)
.ThenByDescending(b => b.Ranking)
.ThenByDescending(b => b.CreatedAt)
.ThenByDescending(b => b.UpdatedAt)
.Skip(offset).Take(limit)
.AsSplitQuery()
.ToArrayAsync(cancellationToken);
return books?.Length > 0
? Result.Ok(books.Select(b => b.ToModel()).ToArray())
: Result.Fail<AuthorBook[]>(new Error("No published books found."));
}
catch (Exception ex)
{
return Result.Fail<AuthorBook[]>(new Error(ex.Message).CausedBy(ex));
}
}
}