Next up is the createBook method. This is the most complicated one.
First of all, implement all the required validations:
createBook(collectionIdentifier: string): void {
if (!collectionIdentifier) {
throw new Error("The collection identifier is required to
create a new book!");
}
console.log("Retrieving the details about the new book to
create...");
const bookDetailsResult =
this._view.getNewBookDetails(collectionIdentifier);
if (bookDetailsResult.error) {
console.error("Failed to retrieve the book details: ",
bookDetailsResult.error);
return;
}
if (!this._bookCollections.has(collectionIdentifier) ||
!this._bookCollections.get(collectionIdentifier)) {
console.error("Tried to add a book to an unknown collection.
Identifier: ", collectionIdentifier);
this._view.displayErrorMessage("Failed to create the new
book!");
return;
}
const existingCollection =
this._bookCollections.get(collectionIdentifier);
if (!existingCollection || !bookDetailsResult.book) {
throw new Error("The collection couldn't be retrieved or we
could not get the book details from the view!");
}
// add the rest of the code here
}
Then add the following:
const newBook: Readonly<Book> = bookDetailsResult.book;
existingCollection.addMedia(newBook);
this._bookService.saveMediaCollection(existingCollection)
.then(() => {
console.log(`Book collection called
"${existingCollection.name}" updated successfully.`);
this._view.clearNewBookForm(collectionIdentifier);
this._view.renderBook(existingCollection.identifier, newBook); // here we are sure that the book property is set
})
.catch(error => {
console.error("Error while updating an existing book
collection: ", error);
this._view.displayErrorMessage(`Failed to update the existing
book collection called ${existingCollection.name}`);
});
In this second part of the method, we have added our new book to the existing collection and then asked the service to persist the updated collection.
Again, in the event of an error, the view is asked to display an error message.