Refactors the update book slice across the stack

This commit is contained in:
BinaryAlley committed 2026-09-12 12:13:18 -07:00
1 parent 9a71a6d32b
commit 001146eefc
27 files changed
+4065 -632

No files matched your search

@@ -14,6 +14,9 @@
- [Get Books Lite](#get-books-lite)
- [Get Books Lite Request](#get-books-lite-request)
- [Get Books Lite Response](#get-books-lite-response)
- [Update Book](#update-book)
- [Update Book Request](#update-book-request)
- [Update Book Response](#update-book-response)
- [Get Reading Availability](#get-reading-availability)
- [Get Reading Availability Request](#get-reading-availability-request)
- [Get Reading Availability Response](#get-reading-availability-response)
@@ -34,13 +37,12 @@
#### Add Book Request
```js
POST api/v1/books
POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books
```
```json
{
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/books/the-fellowship-of-the-ring.pdf",
"path": "/media/libraries/books/the-fellowship-of-the-ring.pdf",
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
@@ -50,7 +52,7 @@ POST api/v1/books
"originalReleaseYear": 1954,
"reReleaseDate": "2001-09-06",
"reReleaseYear": 2001,
"releaseCountry": "uk",
"releaseCountry": "GB",
"releaseVersion": "50th Anniversary Edition"
},
"genres": [
@@ -93,31 +95,27 @@ POST api/v1/books
"appleBooksId": "id395211",
"isbns": [
{
"value": "0395272238",
"format": "Isbn10"
"value": "0395272238",
"format": "Isbn10"
},
{
"value": "9780395272237",
"format": "Isbn13"
"value": "9780395272237",
"format": "Isbn13"
}
],
"contributors": [
{
"name": {
"displayName": "J.R.R. Tolkien"
},
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Author"
},
{
"name": {
"displayName": "Alan Lee"
},
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Illustrator"
}
],
"ratings": [
{
"source": "Goodreads",
"source": "GoogleBooks",
"value": 4.36,
"maxValue": 5,
"voteCount": 2345678
@@ -142,7 +140,7 @@ POST api/v1/books
{
"id": "32b336e8-dafc-4a08-9dec-9454e66dd55d",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/books/the-fellowship-of-the-ring.pdf",
"path": "/media/libraries/books/the-fellowship-of-the-ring.pdf",
"metadata": {
"publisher": "Houghton Mifflin",
"pageCount": 398,
@@ -154,7 +152,7 @@ POST api/v1/books
"originalReleaseYear": 1954,
"reReleaseDate": "2001-09-06",
"reReleaseYear": 2001,
"releaseCountry": "uk",
"releaseCountry": "GB",
"releaseVersion": "50th Anniversary Edition"
},
"language": {
@@ -213,14 +211,19 @@ POST api/v1/books
"format": "Isbn13"
}
],
"contributors": [],
"contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" }
],
"ratings": [
{
"source": "GoogleBooks",
"value": 4.36,
"maxValue": 5,
"voteCount": 2345678
},
{
"source": "Amazon",
"value": 4.7,
"maxValue": 5,
"voteCount": 87654
@@ -230,7 +233,8 @@ POST api/v1/books
"lastMetadataUpdateUtc": null,
"metadataProvider": null,
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null
"updatedOnUtc": null,
"coverPath": null
}
```
@@ -239,7 +243,7 @@ POST api/v1/books
#### Get Book Request
```js
GET api/v1/books/{id}
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}
```
#### Get Book Response
@@ -255,12 +259,11 @@ Returns an empty response. This endpoint is not yet implemented.
#### Get Books Request
```js
GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&currentPage=1&perPage=10&searchTerm=fellowship&sortBy=title&sortOrder=Ascending
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&perPage=10&searchTerm=fellowship&sortBy=title&sortOrder=Ascending
```
| Query Parameter | Type | Description |
| --- | --- | --- |
| `libraryId` | `string` (GUID) | Required. The Id of the media library whose books are retrieved. |
| `currentPage` | `int` | Optional. The page of results to retrieve. |
| `perPage` | `int` | Optional. The maximum number of books to retrieve per page. |
| `searchTerm` | `string` | Optional. The search term used to filter results. |
@@ -279,7 +282,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&currentPage=1&pe
{
"id": "32b336e8-dafc-4a08-9dec-9454e66dd55d",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/books/the-fellowship-of-the-ring.pdf",
"path": "/media/libraries/books/the-fellowship-of-the-ring.pdf",
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
@@ -289,7 +292,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&currentPage=1&pe
"originalReleaseYear": 1954,
"reReleaseDate": "2001-09-06",
"reReleaseYear": 2001,
"releaseCountry": "uk",
"releaseCountry": "GB",
"releaseVersion": "50th Anniversary Edition"
},
"genres": [
@@ -343,6 +346,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&currentPage=1&pe
"contributors": [],
"ratings": [
{
"source": "GoogleBooks",
"value": 4.36,
"maxValue": 5,
"voteCount": 2345678
@@ -367,12 +371,11 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&currentPage=1&pe
#### Get Books Lite Request
```js
GET api/v1/books/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&currentPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&ignoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite?currentPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&ignoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending
```
| Query Parameter | Type | Description |
| --- | --- | --- |
| `libraryId` | `string` (GUID) | Required. The Id of the media library whose books are retrieved. |
| `currentPage` | `int` | Optional. The page of results to retrieve. |
| `perPage` | `int` | Optional. The maximum number of books to retrieve per page. |
| `searchTerm` | `string` | Optional. The search term used to filter results. |
@@ -404,12 +407,217 @@ GET api/v1/books/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&currentPage
}
```
### Update Book
#### Update Book Request
```js
PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}
```
```json
{
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
"description": "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.",
"releaseInfo": {
"originalReleaseDate": "1954-07-29",
"originalReleaseYear": 1954,
"reReleaseDate": "2001-09-06",
"reReleaseYear": 2001,
"releaseCountry": "GB",
"releaseVersion": "50th Anniversary Edition"
},
"genres": [
{ "name": "fantasy" },
{ "name": "adventure" },
{ "name": "classic" }
],
"tags": [
{ "name": "epic fantasy" },
{ "name": "quest" },
{ "name": "middle-earth" }
],
"language": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"originalLanguage": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"publisher": "Houghton Mifflin",
"pageCount": 398
},
"format": "Paperback",
"edition": "50th Anniversary Edition",
"volumeNumber": 1,
"series": {
"title": "The Lord of the Rings"
},
"asin": "B007978NPG",
"goodreadsId": "3",
"lccn": "54009621",
"oclcNumber": "ocm00012345",
"openLibraryId": "OL7603910M",
"libraryThingId": "3203347",
"googleBooksId": "aWZzLPhY4o0C",
"barnesAndNobleId": "1100307790",
"appleBooksId": "id395211",
"isbns": [
{
"value": "0395272238",
"format": "Isbn10"
},
{
"value": "9780395272237",
"format": "Isbn13"
}
],
"contributors": [
{
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Author"
},
{
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Illustrator"
}
],
"ratings": [
{
"source": "GoogleBooks",
"value": 4.36,
"maxValue": 5,
"voteCount": 2345678
},
{
"source": "Amazon",
"value": 4.7,
"maxValue": 5,
"voteCount": 87654
}
]
}
```
#### Update Book Response
```js
200 Ok
```
```json
{
"id": "32b336e8-dafc-4a08-9dec-9454e66dd55d",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/media/libraries/books/the-fellowship-of-the-ring.pdf",
"metadata": {
"publisher": "Houghton Mifflin",
"pageCount": 398,
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
"description": "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.",
"releaseInfo": {
"originalReleaseDate": "1954-07-29",
"originalReleaseYear": 1954,
"reReleaseDate": "2001-09-06",
"reReleaseYear": 2001,
"releaseCountry": "GB",
"releaseVersion": "50th Anniversary Edition"
},
"language": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"originalLanguage": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"tags": [
{
"name": "epic fantasy"
},
{
"name": "quest"
},
{
"name": "middle-earth"
}
],
"genres": [
{
"name": "fantasy"
},
{
"name": "adventure"
},
{
"name": "classic"
}
]
},
"format": "Paperback",
"edition": "50th Anniversary Edition",
"volumeNumber": 1,
"series": null,
"asin": "B007978NPG",
"goodreadsId": "3",
"lccn": "54009621",
"oclcNumber": "ocm00012345",
"openLibraryId": "OL7603910M",
"libraryThingId": "3203347",
"googleBooksId": "aWZzLPhY4o0C",
"barnesAndNobleId": "1100307790",
"appleBooksId": "id395211",
"isbns": [
{
"value": "0395272238",
"format": "Isbn10"
},
{
"value": "9780395272237",
"format": "Isbn13"
}
],
"contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" }
],
"ratings": [
{
"source": "GoogleBooks",
"value": 4.36,
"maxValue": 5,
"voteCount": 2345678
},
{
"source": "Amazon",
"value": 4.7,
"maxValue": 5,
"voteCount": 87654
}
],
"metadataStatus": "Enriched",
"lastMetadataUpdateUtc": "2025-01-01T12:00:00.0000000Z",
"metadataProvider": "GoogleBooks",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-02-01T12:00:00.0000000Z",
"coverPath": "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg"
}
```
### Get Reading Availability
#### Get Reading Availability Request
```js
GET api/v1/books/{bookId}/reading/availability
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/availability
```
Reports whether the book identified by `bookId` can be opened for reading: the book reader that supports the format of the book is resolved and its enablement for the media library of the book is checked, without extracting the book. When the book cannot be read, the response carries the code of the error preventing it, so the client can tell a missing book reader apart from a disabled one.
@@ -434,7 +642,7 @@ Reports whether the book identified by `bookId` can be opened for reading: the b
#### Get Reading Manifest Request
```js
GET api/v1/books/{bookId}/reading/manifest
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/manifest
```
Opens the book identified by `bookId` for reading by extracting its contents through the book reader that is enabled for its media library, and returns the reading manifest: the title and author of the book, its hierarchical table of contents, its ordered spine of reading sections, the keys of its resources, and whether it has extractable text content. A scanned book, whose pages are only images, has no text content and is displayed as page images.
@@ -485,7 +693,7 @@ Opens the book identified by `bookId` for reading by extracting its contents thr
#### Get Reading Section Request
```js
GET api/v1/books/{bookId}/reading/sections/{locationRef}
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/sections/{locationRef}
```
Returns the reading section identified by `locationRef` of the book identified by `bookId`. The section content is sanitized by the host before it is served, and its references to the resources of the book are resolved by the client through the resource endpoint. The `locationRef` of a section is taken from the spine of the reading manifest of the book.
@@ -509,7 +717,7 @@ Returns the reading section identified by `locationRef` of the book identified b
#### Get Reading Resource Request
```js
GET api/v1/books/{bookId}/reading/resources/{resourceKey}
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/resources/{resourceKey}
```
Returns the binary resource identified by `resourceKey` of the book identified by `bookId` (for example an image, a font, or a stylesheet of the book, or a page image of a scanned PDF that is rendered on demand). The `resourceKey` of a resource is taken from the reading manifest of the book.
@@ -1,9 +1,8 @@
PUT {{host}}/api/v1/books/{{$guid}}
PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}
Authorization: Bearer {{ACCESS_TOKEN}}
Content-Type: application/json
{
"id": "{{$guid}}",
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
@@ -66,17 +65,11 @@ Content-Type: application/json
],
"contributors": [
{
"name": {
"displayName": "J.R.R. Tolkien",
"legalName": "John Ronald Reuel Tolkien"
},
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Author"
},
{
"name": {
"displayName": "Alan Lee",
"legalName": "Alan Lee"
},
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Illustrator"
}
],
@@ -1,6 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaContributors;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -11,40 +24,66 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.B
public static class UpdateBookCommandMapping
{
/// <summary>
/// Converts <paramref name="command"/> to <see cref="BookMetadataDto"/>, so that the edited data can be applied to the domain book.
/// Converts <paramref name="command"/> to <see cref="Book"/>, preserving the identity and creation metadata of the stored book identified by <paramref name="existingBook"/>.
/// </summary>
/// <param name="command">The command containing the edited data of the book.</param>
/// <returns>The built metadata.</returns>
public static BookMetadataDto ToBookMetadataDto(this UpdateBookCommand command)
/// <param name="command">The command to be converted.</param>
/// <param name="existingBook">The stored book whose identity, file system path and creation metadata are preserved.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="Book"/>, or an error message.
/// </returns>
public static Result<Book> ToDomainEntity(this UpdateBookCommand command, BookEntity existingBook)
{
return new BookMetadataDto(
Title: command.Metadata!.Title,
OriginalTitle: command.Metadata.OriginalTitle,
Description: command.Metadata.Description,
ReleaseInfo: command.Metadata.ReleaseInfo,
Genres: command.Metadata.Genres,
Tags: command.Metadata.Tags,
Language: command.Metadata.Language,
OriginalLanguage: command.Metadata.OriginalLanguage,
Publisher: command.Metadata.Publisher,
PageCount: command.Metadata.PageCount,
Format: command.Format,
Edition: command.Edition,
VolumeNumber: command.VolumeNumber,
Series: command.Series,
ASIN: command.ASIN,
GoodreadsId: command.GoodreadsId,
LCCN: command.LCCN,
OCLCNumber: command.OCLCNumber,
OpenLibraryId: command.OpenLibraryId,
LibraryThingId: command.LibraryThingId,
GoogleBooksId: command.GoogleBooksId,
BarnesAndNobleId: command.BarnesAndNobleId,
AppleBooksId: command.AppleBooksId,
Isbns: command.ISBNs,
Contributors: command.Contributors,
Ratings: command.Ratings,
CoverImagePath: null
IEnumerable<Result<BookRating>> domainRatingsResult = command.Ratings!.ToDomainEntities();
List<Error> errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors) ?? []];
if (errors.Count > 0)
return errors;
IEnumerable<Result<Isbn>> domainIsbnsResult = command.ISBNs!.ToDomainEntities();
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors) ?? []];
if (errors.Count > 0)
return errors;
Result<WrittenContentMetadata> metadataResult = command.Metadata!.ToDomainEntity();
if (metadataResult.IsFailure)
return metadataResult.Errors;
// TODO: update Api.Books.md documentation when the functionality is fully implemented.
BookSeries? bookSeries = null;
if (command.Series != null)
{
// TODO: add logic to search the book series repository for existing book series, based on the provided title.
// TODO: uncomment integration and unit tests about series.
}
// Map the media contributors referenced by the user to their domain counterparts; a contributor is identified by its id and carries the role it played.
IEnumerable<Result<BookMediaContributor>> domainContributorsResult = command.Contributors!.ToBookDomainEntities();
errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors) ?? []];
if (errors.Count > 0)
return errors;
return Book.Create(
BookId.Create(existingBook.Id),
LibraryId.Create(existingBook.LibraryId),
existingBook.Path,
metadataResult.Value,
Optional<BookFormat>.FromNullable(command.Format),
Optional<string>.FromNullable(command.Edition),
Optional<float>.FromNullable(command.VolumeNumber),
Optional<BookSeries>.FromNullable(bookSeries),
Optional<string>.FromNullable(command.ASIN),
Optional<string>.FromNullable(command.GoodreadsId),
Optional<string>.FromNullable(command.LCCN),
Optional<string>.FromNullable(command.OCLCNumber),
Optional<string>.FromNullable(command.OpenLibraryId),
Optional<string>.FromNullable(command.LibraryThingId),
Optional<string>.FromNullable(command.GoogleBooksId),
Optional<string>.FromNullable(command.BarnesAndNobleId),
Optional<string>.FromNullable(command.AppleBooksId),
existingBook.CreatedOnUtc,
Optional<DateTime>.FromNullable(existingBook.UpdatedOnUtc),
[.. domainIsbnsResult.Select(isbn => isbn.Value)],
[.. domainContributorsResult.Select(domainContributor => domainContributor.Value)],
[.. domainRatingsResult.Select(domainRating => domainRating.Value)]
);
}
}
@@ -15,11 +15,14 @@ public static class UpdateBookRequestMapping
/// Converts <paramref name="request"/> to <see cref="UpdateBookCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="libraryId">The Id of the library the book belongs to, taken from the route.</param>
/// <param name="bookId">The Id of the book to update, taken from the route.</param>
/// <returns>The converted command.</returns>
public static UpdateBookCommand ToCommand(this UpdateBookRequest request)
public static UpdateBookCommand ToCommand(this UpdateBookRequest request, string? libraryId, string? bookId)
{
return new UpdateBookCommand(
Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty,
libraryId,
bookId,
request.Metadata,
request.Format,
request.Edition,
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
@@ -14,7 +14,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Command for updating an existing book.
/// </summary>
/// <param name="Id">The Id of the book to update.</param>
/// <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 update, taken from the route.</param>
/// <param name="Metadata">Written content metadata of the book.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback), if applicable.</param>
/// <param name="Edition">The edition of the book, if applicable.</param>
@@ -34,7 +35,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <param name="Ratings">The list of ratings for this book.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateBookCommand(
Guid Id,
string? LibraryId,
string? BookId,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
@@ -50,6 +52,6 @@ public record UpdateBookCommand(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
) : ICommand;
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -8,12 +8,9 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -70,74 +67,44 @@ public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Resul
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!);
// Get the existing book with all its related data.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, 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 edited 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 update 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;
// Convert the book to a domain object and apply the edited metadata to it.
Result<Book> getDomainBookResult = existingBook.ToDomainEntity();
if (getDomainBookResult.IsFailure)
return getDomainBookResult.Errors;
Book book = getDomainBookResult.Value;
// Media contributors are referenced by Id and are never created implicitly by editing a book, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
Result<Success> applyMetadataResult = book.ApplyMetadata(command.ToBookMetadataDto());
if (applyMetadataResult.IsFailure)
return applyMetadataResult.Errors;
// Link the media contributors typed by the user to the book, finding or creating a single contributor per person.
List<BookContributorEntity> linkedContributors = [];
// A person can be credited under several roles in the same book; each distinct display name must resolve to the same media
// contributor row, otherwise the duplicate inserts would violate the unique display name constraint when the changes are saved.
Dictionary<string, MediaContributorEntity> contributorsByDisplayName = [];
foreach (MediaContributorDto contributor in command.Contributors!)
{
if (contributor.Name?.DisplayName is null)
continue;
if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity))
{
Result<MediaContributorEntity> findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false);
if (findOrCreateResult.IsFailure)
return findOrCreateResult.Errors;
contributorEntity = findOrCreateResult.Value;
contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity);
}
string roleName = contributor.Role?.Name ?? "Contributor";
MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other;
linkedContributors.Add(new BookContributorEntity
{
Id = Guid.NewGuid(),
BookId = existingBook.Id,
MediaContributorId = contributorEntity.Id,
RoleName = roleName,
RoleCategory = roleCategory,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = userId,
UpdatedBy = null
});
}
book.UpdateContributors([.. linkedContributors.Select(linkedContributor => MediaContributorId.Create(linkedContributor.MediaContributorId))]);
// Convert the command to a domain aggregate to enforce invariants, preserving the identity and creation metadata of the stored book.
Result<Book> updateBookResult = command.ToDomainEntity(existingBook);
if (updateBookResult.IsFailure)
return updateBookResult.Errors;
// Map the updated domain book onto a fresh repository entity, ready for the repository to replace the stored data.
BookEntity updatedBook = book.ToRepositoryEntity();
updatedBook.BookContributors = linkedContributors;
updatedBook.UpdatedOnUtc = DateTime.UtcNow;
updatedBook.UpdatedBy = userId;
BookEntity updatedBook = updateBookResult.Value.ToRepositoryEntity();
// The identity, enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that
// backs the response; without this, the response would report the fresh entity defaults (Pending metadata status, no cover path).
updatedBook.CreatedOnUtc = existingBook.CreatedOnUtc;
// The enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that the repository
// replaces the stored data with; without this, the stored artwork would be cleared.
updatedBook.MetadataStatus = existingBook.MetadataStatus;
updatedBook.LastMetadataUpdateUtc = existingBook.LastMetadataUpdateUtc;
updatedBook.MetadataProvider = existingBook.MetadataProvider;
@@ -147,8 +114,40 @@ public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Resul
if (updateResult.IsFailure)
return updateResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return updatedBook.ToResponse() with { Contributors = command.Contributors };
// Returns the book as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save.
Result<BookEntity?> getPersistedBookResult = await _unitOfWork.BookRepository.GetByIdAsync(existingBook.Id, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedBookResult.IsFailure)
return getPersistedBookResult.Errors;
if (getPersistedBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
return getPersistedBookResult.Value.ToResponse();
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(UpdateBookCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. command.Contributors!.Select(contributor => contributor.ContributorId).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return DomainErrors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
}
@@ -18,18 +18,34 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
/// </summary>
public UpdateBookCommandValidator()
{
RuleFor(command => command.Id)
// Validates the identifier of the media library the book belongs to, 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 to update, taken from the route.
RuleFor(command => command.BookId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.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);
// Validates the metadata of the book: title, lengths, release information, languages, genres and tags.
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
@@ -125,7 +141,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
@@ -144,7 +160,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
@@ -171,6 +187,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero);
});
// Validates the physical characteristics of the book: format, edition and volume number.
RuleFor(command => command.Format)
.IsInEnum()
.When(command => command.Format is not null)
@@ -186,6 +203,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.When(command => command.VolumeNumber.HasValue)
.WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero);
// Validates the series the book is part of, when the request carries one.
RuleFor(command => command.Series)
.ChildRules(series =>
series.RuleFor(s => s!.Title)
@@ -195,6 +213,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong))
.When(command => command.Series is not null);
// Validates the external identifiers of the book.
RuleFor(command => command.ASIN)
.Length(10)
.When(command => command.ASIN is not null)
@@ -246,6 +265,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.When(command => command.AppleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat);
// Validates the ISBN list of the book.
RuleFor(command => command.ISBNs)
.NotNull()
.WithError(Errors.WrittenContent.IsbnListCannotBeNull);
@@ -272,48 +292,26 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.WrittenContent.UnknownIsbnFormat);
});
// Validates the media contributors that contributed to the book.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
.WithError(Errors.WrittenContent.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.Name)
.NotNull()
.WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty)
.ChildRules(name =>
{
name.RuleFor(n => n!.DisplayName)
.NotNull()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.NotEmpty()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.MaximumLength(100)
.WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong);
name.RuleFor(n => n!.LegalName)
.MaximumLength(100)
.When(n => n!.LegalName is not null)
.WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong);
});
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.NotNull()
.WithError(Errors.MediaContributor.ContributorRoleCannotBeNull)
.ChildRules(role =>
{
role.RuleFor(r => r!.Name)
.NotEmpty()
.WithError(Errors.MediaContributor.RoleNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
role.RuleFor(r => r!.Category)
.NotEmpty()
.WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
});
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the ratings of the book.
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -12,7 +12,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// <summary>
/// Represents a request to update an existing book.
/// </summary>
/// <param name="Id">The Id of the book to update, taken from the route. Required.</param>
/// <param name="Metadata">Written content metadata of the book. Required.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback). Optional.</param>
/// <param name="Edition">The edition of the book. Optional.</param>
@@ -28,11 +27,10 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// <param name="BarnesAndNobleId">The Barnes & Noble Id of the book. Optional.</param>
/// <param name="AppleBooksId">The Apple Books Id of the book. Optional.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book. Required.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book. Required.</param>
/// <param name="Contributors">The list of media contributors of the book. Required.</param>
/// <param name="Ratings">The list of ratings for this book. Required.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateBookRequest(
string? Id,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
@@ -48,6 +46,6 @@ public record UpdateBookRequest(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
);
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
/// <summary>
/// API endpoint for the <c>/books/{id}</c> route.
/// API endpoint for the <c>/{libraryId}/books/{bookId}</c> route.
/// </summary>
public class UpdateBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
{
@@ -48,12 +48,10 @@ public class UpdateBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken)
{
// The book is identified by the {id} route value, not by the id of the request body, so that a mismatched or malicious id can never
// redirect the update to another book; the raw value is kept as a string, so that an unparseable id reaches the command validator,
// which reports it with a ProblemDetails validation error instead of failing the request binding.
request = request with { Id = HttpContext.Request.RouteValues["id"]?.ToString() };
Result<BookResponse> result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
// take unique identifiers from the route
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString();
Result<BookResponse> result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -30,7 +30,6 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
Summary = "Updates a book.";
Description = "Updates the details of the book identified by the request.";
RequestParam(r => r.Id, "The Id of the book to update. Required.");
RequestParam(r => r.Metadata, "The written content metadata of the book. Required.");
RequestParam(r => r.Metadata!.Title, "The title of the book. Required.");
RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional.");
@@ -57,8 +56,8 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback). Optional.");
RequestParam(r => r.Edition, "The edition of the book. Optional.");
RequestParam(r => r.VolumeNumber, "The volume or book number in the series. Optional.");
RequestParam(r => r.Series, "The series the book is part of. Optional.");
RequestParam(r => r.Series!.Title, "The title of the series the book is part of. Optional.");
RequestParam(r => r.Series, "The series the book is part of. Book series are not yet supported and are ignored. Optional.");
RequestParam(r => r.Series!.Title, "The title of the book series. Book series are not yet supported and are ignored. Optional.");
RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book. Optional.");
RequestParam(r => r.GoodreadsId, "The Goodreads Id of the book. Optional.");
RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book. Optional.");
@@ -73,7 +72,6 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
RequestParam(r => r.Ratings, "The list of ratings of the book. Required.");
ExampleRequest = new UpdateBookRequest(
Id: Guid.NewGuid().ToString(),
Metadata: new WrittenContentMetadataDto(
Title: "The Fellowship of the Ring",
OriginalTitle: "The Fellowship of the Ring",
@@ -139,25 +137,13 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
],
Contributors:
[
new MediaContributorDto(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: MediaContributorRoleCategory.Author
)
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Author
),
new MediaContributorDto(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: MediaContributorRoleCategory.Illustrator
)
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Illustrator
)
],
Ratings:
@@ -206,8 +192,8 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
ResponseParam<BookResponse>(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
ResponseParam<BookResponse>(r => r.Edition, "The edition of the book, if applicable.");
ResponseParam<BookResponse>(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
ResponseParam<BookResponse>(r => r.Series, "The series the book is part of, if applicable.");
ResponseParam<BookResponse>(r => r.Series!.Title, "The title of the series the book is part of.");
ResponseParam<BookResponse>(r => r.Series, "The series the book is part of. Book series are not yet supported and this is always null.");
ResponseParam<BookResponse>(r => r.Series!.Title, "The title of the series the book is part of. Book series are not yet supported and this is always null.");
ResponseParam<BookResponse>(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
ResponseParam<BookResponse>(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
@@ -218,7 +204,7 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
ResponseParam<BookResponse>(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
ResponseParam<BookResponse>(r => r.Contributors, "The list of media contributors starring in this book.");
ResponseParam<BookResponse>(r => r.Contributors, "The list of references to the media contributors that contributed to this book, each with the role they played.");
ResponseParam<BookResponse>(r => r.Ratings, "The list of ratings for the book.");
ResponseParam<BookResponse>(r => r.MetadataStatus, "The status of the metadata enrichment of the book.");
ResponseParam<BookResponse>(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable.");
@@ -297,25 +283,13 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
],
Contributors:
[
new MediaContributorDto(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: MediaContributorRoleCategory.Author
)
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Author
),
new MediaContributorDto(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: MediaContributorRoleCategory.Illustrator
)
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Illustrator
)
],
Ratings:
@@ -343,13 +317,32 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
);
Response(401, "Authentication required.", "application/problem+json",
example: new
example: new[]
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/books/{id}"
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()}"
}
}
);
@@ -360,20 +353,32 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/books/{id}",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the book or its media library does not exist.", "application/problem+json",
example: new
Response(404, "The request failed because the book, its media library, or one of the referenced media contributors does not exist.", "application/problem+json",
example: new[]
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "BookNotFound",
instance = "/api/v1/books/{id}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
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 = "MediaContributorNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
@@ -384,12 +389,13 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books/{id}",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"BookIdCannotBeEmpty",
"MetadataCannotBeNull",
"TitleCannotBeEmpty",
@@ -399,7 +405,6 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
"ReleaseInfoCannotBeNull",
"OriginalReleaseYearMustBeBetween1And9999",
"ReReleaseYearMustBeBetween1And9999",
"CountryCodeMustBe2CharactersLong",
"ReleaseVersionMustBeMaximum50CharactersLong",
"OriginalReleaseDateAndYearMustMatch",
"ReReleaseDateAndYearMustMatch",
@@ -438,14 +443,8 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
"InvalidIsbn10Format",
"UnknownIsbnFormat",
"ContributorsListCannotBeNull",
"ContributorNameCannotBeEmpty",
"ContributorDisplayNameCannotBeEmpty",
"ContributorDisplayNameMustBeMaximum100CharactersLong",
"ContributorLegalNameMustBeMaximum100CharactersLong",
"ContributorRoleCannotBeNull",
"RoleNameCannotBeEmpty",
"RoleNameMustBeMaximum50CharactersLong",
"RoleCategoryCannotBeEmpty",
"MediaContributorIdCannotBeEmpty",
"UnknownMediaContributorRole",
"RatingsListCannotBeNull",
"RatingValueMustBePositive",
"RatingValueCannotBeGreaterThanMaxValue",
@@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.DTO.MediaContributors;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
@@ -18,7 +19,12 @@ public class UpdateBookRequest
/// <summary>
/// Gets or sets the Id of the book to update, taken from the route.
/// </summary>
public string? Id { get; set; }
public string? BookId { get; set; }
/// <summary>
/// Gets or sets the Id of the media library the book belongs to.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the written content metadata of the book.
@@ -96,7 +102,7 @@ public class UpdateBookRequest
public List<IsbnDto>? ISBNs { get; set; }
/// <summary>
/// Gets or sets the list of media contributors of the book.
/// Gets or sets the list of media contributors of the book. Required.
/// </summary>
public List<MediaContributorDto>? Contributors { get; set; }
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
/// <summary>
/// API endpoint for the <c>/{culture}/library/written-content-library/books-library/books/{id}/api-save-book</c> route.
/// API endpoint for the <c>/{culture}/library/written-content-library/books-library/books/{bookId}/api-save-book</c> route.
/// </summary>
public class SaveBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
{
@@ -50,14 +50,14 @@ public class SaveBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken)
{
// The book is identified by the {id} route value, not by the id posted in the form, so that a mismatched id can never redirect
// The book is identified by the {bookId} route value, not by the id posted in the form, so that a mismatched id can never redirect
// the update to another book; the value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted
// route value can never escape its URL segment, and an unparseable id is reported by the API as a missing book id.
string routeId = HttpContext.Request.RouteValues["id"]?.ToString() ?? string.Empty;
request.Id = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString();
string routeId = HttpContext.Request.RouteValues["bookId"]?.ToString() ?? string.Empty;
request.BookId = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString();
BookDetailsDto book = await _apiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(
ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", request.Id), request, cancellationToken).ConfigureAwait(false);
ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess(book);
}
}
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.MediaContributors;
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Web.Common.Enums.Common;
using System;
@@ -28,7 +29,8 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
Summary = "Updates a book.";
Description = "Updates the details of the book identified by the request.";
RequestParam(r => r.Id, "The unique identifier of the book to update. Required.");
RequestParam(r => r.BookId, "The unique identifier of the book to update. Required.");
RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required.");
RequestParam(r => r.Metadata, "The written content metadata of the book. Required.");
RequestParam(r => r.Metadata!.Title, "The title of the book. Required.");
RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional.");
@@ -72,7 +74,8 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
ExampleRequest = new UpdateBookRequest
{
Id = Guid.NewGuid().ToString(),
BookId = Guid.NewGuid().ToString(),
LibraryId = Guid.NewGuid(),
Metadata = new WrittenContentMetadataDto
{
Title = "The Fellowship of the Ring",
@@ -140,12 +143,12 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
new MediaContributorDto
{
Name = new MediaContributorNameDto { DisplayName = "J.R.R. Tolkien", LegalName = "John Ronald Reuel Tolkien" },
Role = new MediaContributorRoleDto { Name = "author", Category = "Author" }
Role = MediaContributorRole.Author
},
new MediaContributorDto
{
Name = new MediaContributorNameDto { DisplayName = "Alan Lee", LegalName = "Alan Lee" },
Role = new MediaContributorRoleDto { Name = "illustrator", Category = "Illustrator" }
Role = MediaContributorRole.Illustrator
}
],
Ratings =
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Contracts.DTO.Common;
@@ -25,13 +25,14 @@ public class UpdateBookCommandFixture
{
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
/// Creates a random valid command to update a book.
/// </summary>
/// <param name="id">Optional. The Id of the book to update.</param>
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
/// <param name="bookId">Optional. The Id of the book to update.</param>
/// <param name="metadata">Optional. The written content metadata of the book.</param>
/// <param name="format">Optional. The format of the book.</param>
/// <param name="edition">Optional. The edition of the book.</param>
@@ -53,7 +54,8 @@ public class UpdateBookCommandFixture
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <returns>The created command to update a book.</returns>
public UpdateBookCommand Create(
Guid? id = null,
string? libraryId = null,
string? bookId = null,
WrittenContentMetadataDto? metadata = null,
BookFormat? format = null,
string? edition = null,
@@ -69,13 +71,14 @@ public class UpdateBookCommandFixture
string? barnesAndNobleId = null,
string? appleBooksId = null,
List<IsbnDto>? isbns = null,
List<MediaContributorDto>? contributors = null,
List<MediaContributorReferenceDto>? contributors = null,
List<BookRatingDto>? ratings = null,
bool includeMetadata = true,
bool includeOptionalProperties = true)
{
return new Faker<UpdateBookCommand>()
.CustomInstantiator(f => new UpdateBookCommand(
default,
default,
default!,
default,
@@ -90,12 +93,13 @@ public class UpdateBookCommandFixture
default,
default,
default,
default,
default!,
default!,
default!,
default!
))
.RuleFor(x => x.Id, id ?? Guid.NewGuid())
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid().ToString())
.RuleFor(x => x.BookId, bookId ?? Guid.NewGuid().ToString())
.RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null)
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
@@ -112,7 +116,7 @@ public class UpdateBookCommandFixture
.RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null))
.RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
}
/// <summary>
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
@@ -24,13 +24,12 @@ public class UpdateBookRequestFixture
{
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
/// Creates a random valid request to update a book.
/// </summary>
/// <param name="id">Optional. The Id of the book to update.</param>
/// <param name="metadata">Optional. The written content metadata of the book.</param>
/// <param name="format">Optional. The format of the book.</param>
/// <param name="edition">Optional. The edition of the book.</param>
@@ -49,11 +48,8 @@ public class UpdateBookRequestFixture
/// <param name="contributors">Optional. The contributors of the book.</param>
/// <param name="ratings">Optional. The ratings of the book.</param>
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <param name="rawId">Optional. The raw string value of the Id of the book to update. Takes precedence over <paramref name="id"/>.</param>
/// <param name="includeId">Whether the Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to update a book.</returns>
public UpdateBookRequest Create(
Guid? id = null,
WrittenContentMetadataDto? metadata = null,
BookFormat? format = null,
string? edition = null,
@@ -69,15 +65,12 @@ public class UpdateBookRequestFixture
string? barnesAndNobleId = null,
string? appleBooksId = null,
List<IsbnDto>? isbns = null,
List<MediaContributorDto>? contributors = null,
List<MediaContributorReferenceDto>? contributors = null,
List<BookRatingDto>? ratings = null,
bool includeOptionalProperties = true,
string? rawId = null,
bool includeId = true)
bool includeOptionalProperties = true)
{
return new Faker<UpdateBookRequest>()
.CustomInstantiator(f => new UpdateBookRequest(
default,
default!,
default,
default,
@@ -96,7 +89,6 @@ public class UpdateBookRequestFixture
default!,
default!
))
.RuleFor(x => x.Id, f => includeId ? (rawId ?? id?.ToString() ?? Guid.NewGuid().ToString()) : null)
.RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create())
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
@@ -113,7 +105,7 @@ public class UpdateBookRequestFixture
.RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null))
.RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
}
/// <summary>
@@ -31,17 +31,20 @@ public class UpdateBookRequestFixture
/// Creates a new <see cref="UpdateBookRequest"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional Id of the book to update.</param>
/// <param name="libraryId">Optional Id of the media library the book belongs to.</param>
/// <param name="metadata">Optional written content metadata of the book.</param>
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="UpdateBookRequest"/> instance.</returns>
public UpdateBookRequest Create(
Guid? id = null,
Guid? libraryId = null,
WrittenContentMetadataDto? metadata = null,
bool includeOptionalProperties = true)
{
return new UpdateBookRequest
{
Id = id?.ToString() ?? Guid.NewGuid().ToString(),
BookId = id?.ToString() ?? Guid.NewGuid().ToString(),
LibraryId = libraryId ?? Guid.NewGuid(),
Metadata = metadata ?? (includeOptionalProperties ? _writtenContentMetadataDtoFixture.Create() : null),
Format = includeOptionalProperties ? _faker.PickRandom<BookFormat>() : null,
Edition = includeOptionalProperties ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null,
@@ -43,9 +43,10 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId);
Guid libraryId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId);
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}", expectedBook);
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}", expectedBook);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(bookId, request);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
@@ -60,7 +61,7 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == bookId.ToString());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == bookId.ToString());
}
[Fact]
@@ -70,9 +71,10 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
_apiFactory.ApiClientStub.Reset();
Guid routeId = Guid.NewGuid();
Guid bodyId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId);
Guid libraryId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId, libraryId: libraryId);
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: routeId);
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{routeId}", expectedBook);
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{routeId}", expectedBook);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(routeId, request);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
@@ -84,8 +86,8 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{routeId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == routeId.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bodyId}");
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{routeId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == routeId.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bodyId}");
}
[Fact]
@@ -103,7 +105,7 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}");
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{request.LibraryId}/books/{bookId}");
}
[Fact]
@@ -2,10 +2,15 @@
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
@@ -39,15 +44,23 @@ public class UpdateBookEndpointTests : IClassFixture<LuminaApiFactory>
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{request.Id}", request);
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/books/{bookId}", problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
@@ -58,10 +71,12 @@ public class UpdateBookEndpointTests : IClassFixture<LuminaApiFactory>
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle));
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{request.Id}", request);
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request);
// Assert
// The injected title is validated and handled by the parameterized update flow: the route book does not exist,
@@ -83,15 +98,16 @@ public class UpdateBookEndpointTests : IClassFixture<LuminaApiFactory>
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}", request);
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{Uri.EscapeDataString(maliciousBookId)}", request);
// Assert
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command
// mapping and becomes Guid.Empty, which the command validator reports as a clean validation error. The response must
// not leak stack traces, database details, or the injected payload, and the body Id never redirects the update.
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
// or the injected payload.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
@@ -105,16 +121,17 @@ public class UpdateBookEndpointTests : IClassFixture<LuminaApiFactory>
}
[Fact]
public async Task UpdateBook_WhenRouteBookDoesNotExistEvenIfBodyIdDiffers_ShouldReturnNotFound()
public async Task UpdateBook_WhenRouteBookDoesNotExist_ShouldReturnNotFound()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{routeId}", request);
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{routeId}", request);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -127,4 +144,39 @@ public class UpdateBookEndpointTests : IClassFixture<LuminaApiFactory>
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task UpdateBook_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
Guid bookId;
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
}
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
UpdateBookRequest request = _updateBookRequestFixture.Create();
// Act
HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
}
@@ -45,10 +45,11 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bodyId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
string normalizedBookId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{normalizedBookId}", _bookDetailsDtoFixture.Create());
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{normalizedBookId}", _bookDetailsDtoFixture.Create());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(maliciousBookId, _updateBookRequestFixture.Create(id: bodyId));
HttpRequestMessage saveRequest = CreateSaveRequest(maliciousBookId, _updateBookRequestFixture.Create(id: bodyId, libraryId: libraryId));
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
@@ -63,8 +64,8 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{normalizedBookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == normalizedBookId);
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bodyId}");
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{normalizedBookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == normalizedBookId);
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bodyId}");
}
[Theory]
@@ -75,11 +76,12 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId);
Guid libraryId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
request.Metadata!.Title = maliciousTitle;
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId);
expectedBook.Metadata!.Title = maliciousTitle;
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}", expectedBook);
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}", expectedBook);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(bookId.ToString(), request);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
@@ -93,7 +95,7 @@ public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle);
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle);
}
[Fact]
@@ -1,8 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -14,45 +23,125 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten
[ExcludeFromCodeCoverage]
public class UpdateBookCommandMappingTests
{
private readonly UpdateBookCommandFixture _commandFixture = new();
private readonly UpdateBookCommandFixture _commandBookFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
[Fact]
public void ToBookMetadataDto_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
{
// Arrange
UpdateBookCommand command = _commandFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookCommand command = _commandBookFixture.Create(libraryId: libraryId.ToString(), bookId: bookId.ToString());
BookEntity existingBook = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: "/books/the-book.epub");
DateTime createdOnUtc = existingBook.CreatedOnUtc;
// Act
BookMetadataDto result = command.ToBookMetadataDto();
Result<Book> result = command.ToDomainEntity(existingBook);
// Assert
Assert.NotNull(result);
Assert.Equal(command.Metadata!.Title, result.Title);
Assert.Equal(command.Metadata.OriginalTitle, result.OriginalTitle);
Assert.Equal(command.Metadata.Description, result.Description);
Assert.Equal(command.Metadata.ReleaseInfo, result.ReleaseInfo);
Assert.Equal(command.Metadata.Genres, result.Genres);
Assert.Equal(command.Metadata.Tags, result.Tags);
Assert.Equal(command.Metadata.Language, result.Language);
Assert.Equal(command.Metadata.OriginalLanguage, result.OriginalLanguage);
Assert.Equal(command.Metadata.Publisher, result.Publisher);
Assert.Equal(command.Metadata.PageCount, result.PageCount);
Assert.Equal(command.Format, result.Format);
Assert.Equal(command.Edition, result.Edition);
Assert.Equal(command.VolumeNumber, result.VolumeNumber);
Assert.Equal(command.Series, result.Series);
Assert.Equal(command.ASIN, result.ASIN);
Assert.Equal(command.GoodreadsId, result.GoodreadsId);
Assert.Equal(command.LCCN, result.LCCN);
Assert.Equal(command.OCLCNumber, result.OCLCNumber);
Assert.Equal(command.OpenLibraryId, result.OpenLibraryId);
Assert.Equal(command.LibraryThingId, result.LibraryThingId);
Assert.Equal(command.GoogleBooksId, result.GoogleBooksId);
Assert.Equal(command.BarnesAndNobleId, result.BarnesAndNobleId);
Assert.Equal(command.AppleBooksId, result.AppleBooksId);
Assert.Equal(command.ISBNs, result.Isbns);
Assert.Equal(command.Contributors, result.Contributors);
Assert.Equal(command.Ratings, result.Ratings);
Assert.Null(result.CoverImagePath);
Assert.False(result.IsFailure);
Assert.Equal(bookId, result.Value.Id.Value);
Assert.Equal(libraryId, result.Value.LibraryId.Value);
Assert.Equal(existingBook.Path, result.Value.Path);
Assert.Equal(createdOnUtc, result.Value.CreatedOnUtc);
Assert.Equal(command.Metadata!.Title, result.Value.Metadata.Title);
Assert.Equal(command.Metadata.ReleaseInfo!.OriginalReleaseYear, result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
Assert.Equal(command.Metadata.Genres!.Count, result.Value.Metadata.Genres.Count);
Assert.Equal(command.Metadata.Tags!.Count, result.Value.Metadata.Tags.Count);
Assert.Equal(command.ISBNs!.Count, result.Value.ISBNs.Count);
Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count);
Assert.Equal(command.Ratings!.Count, result.Value.Ratings.Count);
Assert.True(result.Value.Format.HasValue);
Assert.Equal(command.Format, result.Value.Format.Value);
}
[Fact]
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapRequiredPropertiesCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookCommand command = _commandBookFixture.Create(
libraryId: libraryId.ToString(),
bookId: bookId.ToString(),
isbns: [],
contributors: [],
ratings: [],
includeOptionalProperties: false);
BookEntity existingBook = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: "/books/the-book.epub");
// Act
Result<Book> result = command.ToDomainEntity(existingBook);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(bookId, result.Value.Id.Value);
Assert.Equal(libraryId, result.Value.LibraryId.Value);
Assert.Equal(existingBook.Path, result.Value.Path);
Assert.Empty(result.Value.ISBNs);
Assert.Empty(result.Value.Contributors);
Assert.Empty(result.Value.Ratings);
Assert.False(result.Value.Format.HasValue);
Assert.False(result.Value.Edition.HasValue);
Assert.False(result.Value.VolumeNumber.HasValue);
Assert.False(result.Value.ASIN.HasValue);
Assert.False(result.Value.GoodreadsId.HasValue);
Assert.False(result.Value.LCCN.HasValue);
Assert.False(result.Value.OCLCNumber.HasValue);
Assert.False(result.Value.OpenLibraryId.HasValue);
Assert.False(result.Value.LibraryThingId.HasValue);
Assert.False(result.Value.GoogleBooksId.HasValue);
Assert.False(result.Value.BarnesAndNobleId.HasValue);
Assert.False(result.Value.AppleBooksId.HasValue);
}
[Fact]
public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]);
BookEntity existingBook = _bookEntityFixture.Create();
// Act
Result<Book> result = command.ToDomainEntity(existingBook);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description);
}
[Fact]
public void ToDomainEntity_WhenIsbnCreationFails_ShouldReturnError()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]);
BookEntity existingBook = _bookEntityFixture.Create();
// Act
Result<Book> result = command.ToDomainEntity(existingBook);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description);
}
[Fact]
public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]));
BookEntity existingBook = _bookEntityFixture.Create();
// Act
Result<Book> result = command.ToDomainEntity(existingBook);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
@@ -18,20 +19,23 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten
public class UpdateBookRequestMappingTests
{
private readonly UpdateBookRequestFixture _requestFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
[Fact]
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _requestFixture.Create(id: bookId);
UpdateBookRequest request = _requestFixture.Create();
// Act
UpdateBookCommand result = request.ToCommand();
UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString());
// Assert
Assert.NotNull(result);
Assert.Equal(bookId, result.Id);
Assert.Equal(libraryId.ToString(), result.LibraryId);
Assert.Equal(bookId.ToString(), result.BookId);
Assert.Equal(request.Metadata, result.Metadata);
Assert.Equal(request.Format, result.Format);
Assert.Equal(request.Edition, result.Edition);
@@ -55,15 +59,16 @@ public class UpdateBookRequestMappingTests
public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _requestFixture.Create(id: bookId, includeOptionalProperties: false);
UpdateBookRequest request = _requestFixture.Create(includeOptionalProperties: false);
// Act
UpdateBookCommand result = request.ToCommand();
UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString());
// Assert
Assert.NotNull(result);
Assert.Equal(bookId, result.Id);
Assert.Equal(bookId.ToString(), result.BookId);
Assert.NotNull(result.Metadata);
Assert.Equal(request.Metadata, result.Metadata);
Assert.Null(result.Format);
@@ -88,21 +93,20 @@ public class UpdateBookRequestMappingTests
public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _requestFixture.Create(
isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)],
contributors:
[
new(
new("John Doe", "John Smith Doe"),
new("Author", MediaContributorRoleCategory.Author)
)
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)
],
ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
includeOptionalProperties: false
);
// Act
UpdateBookCommand result = request.ToCommand();
UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString());
// Assert
Assert.NotNull(result);
@@ -112,41 +116,16 @@ public class UpdateBookRequestMappingTests
}
[Fact]
public void ToCommand_WhenMappingRequestWithNullId_ShouldMapEmptyGuid()
public void ToCommand_WhenRouteValuesAreNotParseable_ShouldMapThemAsIs()
{
// Arrange
UpdateBookRequest request = _requestFixture.Create(includeId: false);
UpdateBookRequest request = _requestFixture.Create(includeOptionalProperties: false);
// Act
UpdateBookCommand result = request.ToCommand();
UpdateBookCommand result = request.ToCommand("not-a-library-guid", "not-a-guid");
// Assert
Assert.Equal(Guid.Empty, result.Id);
}
[Fact]
public void ToCommand_WhenMappingRequestWithEmptyId_ShouldMapEmptyGuid()
{
// Arrange
UpdateBookRequest request = _requestFixture.Create(rawId: string.Empty);
// Act
UpdateBookCommand result = request.ToCommand();
// Assert
Assert.Equal(Guid.Empty, result.Id);
}
[Fact]
public void ToCommand_WhenMappingRequestWithUnparseableId_ShouldMapEmptyGuid()
{
// Arrange
UpdateBookRequest request = _requestFixture.Create(rawId: "not-a-guid");
// Act
UpdateBookCommand result = request.ToCommand();
// Assert
Assert.Equal(Guid.Empty, result.Id);
Assert.Equal("not-a-library-guid", result.LibraryId);
Assert.Equal("not-a-guid", result.BookId);
}
}
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
@@ -12,7 +12,10 @@ using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Boo
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -45,11 +48,15 @@ public class UpdateBookCommandHandlerTests
private readonly IValidator<UpdateBookCommand> _mockValidator;
private readonly UpdateBookCommandHandler _sut;
private readonly Guid _userId;
private static readonly Error s_findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor.");
private readonly UpdateBookCommandFixture _commandBookFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCommandHandlerTests"/> class.
@@ -59,6 +66,7 @@ public class UpdateBookCommandHandlerTests
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
@@ -72,10 +80,22 @@ public class UpdateBookCommandHandlerTests
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<UpdateBookCommand>()).Returns([]);
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_mediaContributorEntityFixture.Create()));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Default stub: every referenced media contributor already exists.
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
IReadOnlyCollection<Guid> contributorIds = callInfo.Arg<IReadOnlyCollection<Guid>>();
return Result.From<IReadOnlyList<MediaContributorEntity>>([.. contributorIds.Select(contributorId => new MediaContributorEntity
{
Id = contributorId,
DisplayName = contributorId.ToString(),
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
})]);
});
_sut = new UpdateBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
@@ -85,18 +105,25 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
BookEntity? updatedBook = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
updatedBook = callInfo.Arg<BookEntity>();
return Result.Updated;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(command.Id, result.Value.Id);
Assert.Equal(Guid.Parse(command.BookId!), result.Value.Id);
Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title);
Assert.Equal(command.Contributors, result.Value.Contributors);
Assert.Equal(command.Contributors!.Count, result.Value.Contributors!.Count);
await _mockBookRepository.Received(1).UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -114,7 +141,7 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -131,7 +158,7 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
@@ -139,7 +166,7 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
// Act
@@ -157,7 +184,7 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
@@ -174,8 +201,8 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
@@ -192,34 +219,13 @@ public class UpdateBookCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutSaving()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(s_findOrCreateError);
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(s_findOrCreateError, result.FirstError);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRepositoryUpdateFails_ShouldReturnFailureResultWithoutSaving()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Errors.WrittenContent.BookNotFound);
@@ -234,22 +240,21 @@ public class UpdateBookCommandHandlerTests
}
[Fact]
public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole()
public async Task HandleAsync_WhenContributorsHaveTheSameIdAndRole_ShouldLinkThemOnce()
{
// Arrange
Guid contributorId = Guid.NewGuid();
UpdateBookCommand command = _commandBookFixture.Create(
contributors:
[
_mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator)
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator)
]);
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(contributor));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
BookEntity? updatedEntity = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedEntity));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
@@ -262,34 +267,30 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"John Doe", "John Smith Doe", Arg.Any<CancellationToken>());
Assert.NotNull(updatedEntity);
Assert.Equal(2, updatedEntity!.BookContributors.Count);
Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId));
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author");
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator");
Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorsHaveDistinctDisplayNames_ShouldResolveEachContributorOnce()
public async Task HandleAsync_WhenContributorsHaveDistinctIds_ShouldLinkEachContributor()
{
// Arrange
Guid firstContributorId = Guid.NewGuid();
Guid secondContributorId = Guid.NewGuid();
UpdateBookCommand command = _commandBookFixture.Create(
contributors:
[
_mediaContributorDtoFixture.Create(displayName: "Author One", legalName: "Author One Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(displayName: "Author Two", legalName: "Author Two Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator)
_mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Illustrator)
]);
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create();
MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From(callInfo.ArgAt<string>(0) == "Author One" ? firstContributor : secondContributor));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
BookEntity? updatedEntity = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedEntity));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
@@ -302,14 +303,10 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"Author One", "Author One Legal", Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"Author Two", "Author Two Legal", Arg.Any<CancellationToken>());
Assert.NotNull(updatedEntity);
Assert.Equal(2, updatedEntity!.BookContributors.Count);
Assert.Equal(firstContributor.Id, updatedEntity.BookContributors[0].MediaContributorId);
Assert.Equal(secondContributor.Id, updatedEntity.BookContributors[1].MediaContributorId);
Assert.Equal(firstContributorId, updatedEntity.BookContributors[0].MediaContributorId);
Assert.Equal(secondContributorId, updatedEntity.BookContributors[1].MediaContributorId);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -318,7 +315,7 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
existingBook.MetadataStatus = MetadataStatus.Enriched;
existingBook.LastMetadataUpdateUtc = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc);
existingBook.MetadataProvider = "TestProvider";
@@ -334,10 +331,15 @@ public class UpdateBookCommandHandlerTests
CreatedBy = Guid.NewGuid(),
UpdatedBy = null
});
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
BookEntity? updatedBook = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
.Returns(callInfo =>
{
updatedBook = callInfo.Arg<BookEntity>();
return Result.Updated;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -349,4 +351,145 @@ public class UpdateBookCommandHandlerTests
Assert.Equal(existingBook.MetadataProvider, result.Value.MetadataProvider);
Assert.Equal("/media/covers/cover.jpg", result.Value.CoverPath);
}
[Fact]
public async Task HandleAsync_WhenCalledWithInvalidIsbn_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")]));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.TagNameCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(
originalReleaseDate: new DateOnly(2025, 1, 1),
originalReleaseYear: 2025,
reReleaseDate: new DateOnly(2024, 1, 1),
reReleaseYear: 2024)));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
// The stored book belongs to a different library than the one named by the route.
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.NewGuid());
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -36,7 +36,6 @@ public class UpdateBookRequestTests
// Assert
Assert.NotNull(sut);
Assert.False(string.IsNullOrWhiteSpace(sut.Id));
Assert.NotNull(sut.Metadata);
Assert.NotNull(sut.ISBNs);
Assert.NotEmpty(sut.ISBNs);
@@ -82,10 +81,9 @@ public class UpdateBookRequestTests
UpdateBookRequest sut = _updateBookRequestFixture.Create();
// Act
(string? id, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List<IsbnDto>? isbns, List<MediaContributorDto>? contributors, List<BookRatingDto>? ratings) = sut;
(WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List<IsbnDto>? isbns, List<MediaContributorReferenceDto>? contributors, List<BookRatingDto>? ratings) = sut;
// Assert
Assert.Equal(sut.Id, id);
Assert.Equal(sut.Metadata, metadata);
Assert.Equal(sut.Format, format);
Assert.Equal(sut.Edition, edition);
@@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten
[ExcludeFromCodeCoverage]
public class UpdateBookEndpointTests
{
private readonly Application.Common.CQRS.ICommandHandler<UpdateBookCommand, Result<BookResponse>> _mockHandler;
private readonly Lumina.Application.Common.CQRS.ICommandHandler<UpdateBookCommand, Result<BookResponse>> _mockHandler;
private readonly UpdateBookEndpoint _sut;
private readonly UpdateBookRequestFixture _updateBookRequestFixture = new();
private readonly BookResponseFixture _bookResponseFixture = new();
@@ -34,7 +34,7 @@ public class UpdateBookEndpointTests
/// </summary>
public UpdateBookEndpointTests()
{
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<UpdateBookCommand, Result<BookResponse>>>();
_mockHandler = Substitute.For<Lumina.Application.Common.CQRS.ICommandHandler<UpdateBookCommand, Result<BookResponse>>>();
_sut = Factory.Create<UpdateBookEndpoint>(_mockHandler);
}
@@ -42,13 +42,14 @@ public class UpdateBookEndpointTests
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookResponse expectedResponse = _bookResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
ConfigureRequest(routeId.ToString());
ConfigureRequest(libraryId.ToString(), routeId.ToString());
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -62,13 +63,14 @@ public class UpdateBookEndpointTests
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRequest(routeId.ToString());
ConfigureRequest(libraryId.ToString(), routeId.ToString());
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -88,13 +90,14 @@ public class UpdateBookEndpointTests
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Error.Validation(description: "BookIdCannotBeEmpty");
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRequest(routeId.ToString());
ConfigureRequest(libraryId.ToString(), routeId.ToString());
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -112,15 +115,16 @@ public class UpdateBookEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithMatchingRouteId_ShouldSendUpdateBookCommandToHandler()
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateBookCommandToHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest(routeId.ToString());
ConfigureRequest(libraryId.ToString(), routeId.ToString());
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -128,7 +132,8 @@ public class UpdateBookEndpointTests
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCommand>(command =>
command.Id == routeId &&
command.LibraryId == libraryId.ToString() &&
command.BookId == routeId.ToString() &&
command.Metadata == request.Metadata &&
command.Format == request.Format &&
command.Edition == request.Edition &&
@@ -140,80 +145,40 @@ public class UpdateBookEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldSendCommandWithRouteId()
{
// Arrange
Guid routeId = Guid.NewGuid();
Guid bodyId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest(routeId.ToString());
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCommand>(command => command.Id == routeId && command.Id != bodyId),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId()
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
{
// Arrange
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest("not-a-guid");
ConfigureRequest("not-a-library-guid", "not-a-guid");
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCommand>(command => command.Id == Guid.Empty),
Arg.Is<UpdateBookCommand>(command => command.LibraryId == "not-a-library-guid" && command.BookId == "not-a-guid"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteIdIsEmpty_ShouldSendCommandWithEmptyBookId()
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
{
// Arrange
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest(string.Empty);
ConfigureRequestWithoutIds();
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCommand>(command => command.Id == Guid.Empty),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteIdIsMissing_ShouldSendCommandWithEmptyBookId()
{
// Arrange
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequestWithoutId();
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCommand>(command => command.Id == Guid.Empty),
Arg.Is<UpdateBookCommand>(command => command.LibraryId == null && command.BookId == null),
Arg.Is(cancellationToken));
}
@@ -221,8 +186,9 @@ public class UpdateBookEndpointTests
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
@@ -235,7 +201,7 @@ public class UpdateBookEndpointTests
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_bookResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
ConfigureRequest(routeId.ToString());
ConfigureRequest(libraryId.ToString(), routeId.ToString());
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
@@ -248,19 +214,22 @@ public class UpdateBookEndpointTests
}
/// <summary>
/// Sets the <c>id</c> route value the endpoint reads the book Id from.
/// Sets the <c>libraryId</c> and <c>id</c> route values the endpoint reads the identifiers from.
/// </summary>
/// <param name="routeId">The raw route value of the book Id.</param>
private void ConfigureRequest(string routeId)
/// <param name="libraryId">The raw route value of the library Id.</param>
/// <param name="bookId">The raw route value of the book Id.</param>
private void ConfigureRequest(string libraryId, string bookId)
{
_sut.HttpContext.Request.RouteValues["id"] = routeId;
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId;
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
}
/// <summary>
/// Leaves the <c>id</c> route value unset.
/// Leaves the <c>libraryId</c> and <c>id</c> route values unset.
/// </summary>
private void ConfigureRequestWithoutId()
private void ConfigureRequestWithoutIds()
{
_sut.HttpContext.Request.RouteValues.Remove("id");
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
}
}
@@ -55,8 +55,8 @@ public class SaveBookEndpointTests
// Assert
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)),
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId),
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", routeId)),
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == routeId),
Arg.Any<CancellationToken>());
}
@@ -67,7 +67,7 @@ public class SaveBookEndpointTests
string routeId = Guid.NewGuid().ToString();
string bodyId = Guid.NewGuid().ToString();
UpdateBookRequest request = _updateBookRequestFixture.Create();
request.Id = bodyId;
request.BookId = bodyId;
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
.Returns(expectedBook);
@@ -78,8 +78,8 @@ public class SaveBookEndpointTests
// Assert
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)),
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId && forwardedRequest.Id != bodyId),
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", routeId)),
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == routeId && forwardedRequest.BookId != bodyId),
Arg.Any<CancellationToken>());
}
@@ -100,8 +100,8 @@ public class SaveBookEndpointTests
// Assert
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)),
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId),
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", expectedId)),
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == expectedId),
Arg.Any<CancellationToken>());
}
@@ -121,8 +121,8 @@ public class SaveBookEndpointTests
// Assert
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)),
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId),
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", expectedId)),
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == expectedId),
Arg.Any<CancellationToken>());
}
@@ -153,7 +153,7 @@ public class SaveBookEndpointTests
/// <param name="routeId">The raw route value of the book Id.</param>
private void ConfigureRequest(string routeId)
{
_sut.HttpContext.Request.RouteValues["id"] = routeId;
_sut.HttpContext.Request.RouteValues["bookId"] = routeId;
}
/// <summary>