getBookByISBN method
This function getBookByISBN fetches a book by it's ISBN number
(10 or 13 digits) from OpenLibrary.org.
Always check RuntimeType OLBookBase type is -> OLBook / OLBookError
use loadCover
to indicate if the cover should be loaded, default = true
and coverSite
to define the loaded size, M,S,L
from enum CoverSize, default = L
Implementation
Future<OLBookBase> getBookByISBN(
{required String isbn,
bool loadCover = true,
CoverSize coverSize = CoverSize.L}) async {
// try to fetch the book via isbn from the openlibrary.org isbn api
final APIBookBase book =
await _openLibraryApiService.getBookByISBN(isbn: isbn);
if (book is APIBook) {
// fetch Authors if exist
final List<OLAuthor> authors = [];
if (book.authors.isNotEmpty) {
// each author needs to be fetched from openlibrary.org
await Future.forEach(book.authors, (Map<String, String> element) async {
if (element.keys.contains('key')) {
final String id = element['key'] ?? '';
if (id.isNotEmpty) {
// the api wraps the id so we can remove path elements here
final APIAuthorBase author = await _openLibraryApiService
.getAuthorById(id: id.replaceFirst('/authors/', ''));
if (author is APIAuthor) {
authors.add(OLAuthor.fromJson(author.toJson()));
}
}
}
});
}
// fetch covers if exists
final List<Uint8List> covers = [];
if (book.covers.isNotEmpty && loadCover) {
// each cover needs to be downloaded from the openlibrary.org covers endpoint
await Future.forEach(book.covers, (int coverId) async {
// we will provide byte data as Uint8List so it can be used directly as MemoryImage
final Uint8List cover =
await getCover(coverId: coverId, coverSize: coverSize);
if (cover.isNotEmpty) {
covers.add(cover);
}
});
}
// creates a new OLBook instance to be returned as data copy of
// it's api transfer object APIBook with added authors and covers
return _olBookFromAPIBook(book: book, authors: authors, covers: covers);
}
// in the case of an error return the Error Instance
return const OLBookError();
}