Implement remote fetch newest books
Data Layer
Summary
This lesson covers the implementation of the fetchNewestBooks method within the Remote Data Source. By reusing existing logic and extracting a mapping helper method from the previous featured books implementation, the process is streamlined to avoid code duplication. The primary change involves modifying the Google Books API query string to include the &Sorting=newest parameter. The lesson concludes the Remote Data Source implementation for this feature and briefly touches upon the importance of testing, though actual unit tests are deferred to keep the focus on architectural wiring.
Key Ideas
- fetchNewestBooks method implementation is nearly identical to fetchFeaturedBooks, promoting code reuse.
- getBooksList helper method extracts the mapping logic (JSON to BookEntity list), keeping the main data fetching methods concise.
- Google Books API endpoint is modified with the &Sorting=newest query parameter to fetch the most recent publications.
- Remote Data Source layer implementation for the Home feature is officially completed.
- Testing is crucial when writing code without immediate UI execution to catch bugs early in the development cycle.
Code Snippets
class HomeRemoteDataSourceImpl extends HomeRemoteDataSource {
final ApiService apiService;
HomeRemoteDataSourceImpl(this.apiService);
@override
Future<List<BookEntity>> fetchFeaturedBooks() async {
var data = await apiService.get(
endPoint: 'volumes?Filtering=free-ebooks&q=programming');
List<BookEntity> books = getBooksList(data);
return books;
}
@override
Future<List<BookEntity>> fetchNewestBooks() async {
var data = await apiService.get(
endPoint: 'volumes?Filtering=free-ebooks&Sorting=newest&q=programming');
List<BookEntity> books = getBooksList(data);
return books;
}
List<BookEntity> getBooksList(Map<String, dynamic> data) {
List<BookEntity> books = [];
for (var bookMap in data['items']) {
books.add(BookModel.fromJson(bookMap));
}
return books;
}
}My Notes
The instructor extracts the JSON-to-Entity mapping loop into a helper method (getBooksList) to keep the data source methods DRY. This is a good refactor that keeps the fetching methods focused purely on the network call. [Editor's note] The endpoint string "volumes?Filtering=free-ebooks&Sorting=newest&q=programming" is entirely hardcoded. In a production Flutter app, query parameters should be passed as a dedicated map (Map<String, dynamic> queryParameters) down to the ApiService (and eventually to Dio/http) rather than concatenated manually into the path string. This guarantees proper URL encoding and easier scaling. [Editor's note] The instructor defers testing. However, writing unit tests for HomeRemoteDataSourceImpl right now would be trivial by mocking the ApiService. Verifying isolated logic like this without needing the UI is exactly why we use Clean Architecture in the first place.