Adds a Delete Book API endpoint.

This commit is contained in:
BinaryAlley committed 2026-11-12 11:51:51 +02:00
1 parent 67e60f2330
commit b6af6b238c
15 files changed
+1752

No files matched your search

@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
/// <summary>
/// Command for deleting a book by its Id.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book to delete, taken from the route.</param>
[DebuggerDisplay("BookId: {BookId}")]
public record DeleteBookCommand(
string? LibraryId,
string? BookId
) : ICommand;
@@ -0,0 +1,133 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Domain.Common.Primitives;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
/// <summary>
/// Handler for the command to delete a book by its Id.
/// </summary>
public class DeleteBookCommandHandler : ICommandHandler<DeleteBookCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
private readonly ILogger<DeleteBookCommandHandler> _logger;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteBookCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="bookArtworkService">Injected service for removing the artwork of a book.</param>
/// <param name="logger">Injected logger used to report the issues encountered while removing the stored artwork.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteBookCommandHandler(
IUnitOfWork unitOfWork,
IBookArtworkService bookArtworkService,
ILogger<DeleteBookCommandHandler> logger,
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IValidator<DeleteBookCommand> validator)
{
_unitOfWork = unitOfWork;
_bookArtworkService = bookArtworkService;
_logger = logger;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete a book by its Id.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> HandleAsync(DeleteBookCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
// Only the library of the book is needed to scope the delete, so the book row is read without its aggregate graph and without tracking.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository
.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
BookEntity existingBook = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be deleted through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (existingBook.LibraryId != libraryId)
return DomainErrors.WrittenContent.BookNotFound;
// Admins can delete the books of all libraries; for everyone else, only the books of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// A book can only belong to a library that exists, so a client can never delete a book of a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
LibraryEntity library = getLibraryResult.Value;
// The artwork is stored under the library and author segments, so the author is resolved before the book is removed.
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await _unitOfWork.BookRepository
.GetAuthorsDisplayNamesByBookIdsAsync([existingBook.Id], cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
return getAuthorsResult.Errors;
string authorName = getAuthorsResult.Value.TryGetValue(existingBook.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
// Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed.
Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, existingBook.Id, library.Title, authorName, existingBook.Title);
if (deleteArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", existingBook.Id, existingBook.Path);
// Delete the book, whose stored artwork rows and participations are removed by the database cascade.
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false);
if (deleteBookResult.IsFailure)
return deleteBookResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Deleted;
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteBookCommand"/>.
/// </summary>
public class DeleteBookCommandValidator : AbstractValidator<DeleteBookCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookCommandValidator"/> class.
/// </summary>
public DeleteBookCommandValidator()
{
// Validates the identifier of the media library that owns the book, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the book, taken from the route.
RuleFor(command => command.BookId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(command => command.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(command => command.BookId is not null && command.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string GET_BOOKS_LITE = "/libraries/{libraryId}/books/lite";
public const string ADD_BOOK = "/libraries/{libraryId}/books";
public const string UPDATE_BOOK = "/libraries/{libraryId}/books/{bookId}";
public const string DELETE_BOOK = "/libraries/{libraryId}/books/{bookId}";
public const string UPDATE_BOOK_COVER = "/libraries/{libraryId}/books/{bookId}/cover";
public const string GET_BOOK_READING_MANIFEST = "/libraries/{libraryId}/books/{bookId}/reading/manifest";
public const string GET_BOOK_READING_AVAILABILITY = "/libraries/{libraryId}/books/{bookId}/reading/availability";
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/books/{bookId}</c> route.
/// </summary>
public class DeleteBookEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<DeleteBookCommand, Result<Deleted>> _deleteBookCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
/// <param name="deleteBookCommandHandler">Injected service for handling delete book commands.</param>
public DeleteBookEndpoint(ICommandHandler<DeleteBookCommand, Result<Deleted>> deleteBookCommandHandler)
{
_deleteBookCommandHandler = deleteBookCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.DELETE);
Routes(ApiRoutes.Books.DELETE_BOOK);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Deletes a book by Id.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString();
Result<Deleted> result = await _deleteBookCommandHandler.HandleAsync(new DeleteBookCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Class used for providing a textual description for the <see cref="DeleteBookEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointSummary : Summary<DeleteBookEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointSummary"/> class.
/// </summary>
public DeleteBookEndpointSummary()
{
Summary = "Deletes an existing book.";
Description = "Deletes the book identified by the route, together with its stored artwork. The book is deleted by an Admin, who can delete the books of all libraries, or by the owner of the library of the book.";
Response(200, "The book was successfully deleted.");
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the requested book or its media library does not exist.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "BookNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"BookIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
+1
View File
@@ -245,6 +245,7 @@
<Folder Name="/docs/technical/requests/library/written-content-library/book-library/" />
<Folder Name="/docs/technical/requests/library/written-content-library/book-library/books/">
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/AddBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/DeleteBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http" />