Google Books API erroneously incrementing totalItems returned

87 views Asked by At

I am working on an asp.net application that uses the Google Books API. I am using the API to return a list of books based on a search query.

public async Task<BookSearchResponseModel> SearchBooks(string query, int startIndex = 0, int maxResults = 10)
{
    var response = await _client.GetAsync($"https://www.googleapis.com/books/v1/volumes?q={query}&startIndex={startIndex}&maxResults={maxResults}&key={_apiKey}");
    response.EnsureSuccessStatusCode();

    var content = await response.Content.ReadAsStringAsync();
    //return data;
    return JsonConvert.DeserializeObject<BookSearchResponseModel>(content);
}

Controller:

    [HttpGet("search")]
    public async Task<IActionResult> SearchBooks(string query, int startIndex = 0, int maxResults = 10)
    {
        var results = await _googleBooksService.SearchBooks(query, startIndex, maxResults);
        return Ok(results);
    }

This search query is then being paginated in the angular app.

Angular Service:

  getBooks(query: string, startIndex: number = 0, pageSize: number = 10): Observable<BookSearchResponseModel> {
    const params = new HttpParams()
      .set('query', query)
      .set('startIndex', startIndex.toString())
      .set('maxResults', pageSize.toString())
    return this.http.get<BookSearchResponseModel>(this.searchUrl, { params: params }).pipe(
      catchError((error) => {
        console.error("Error retrieving books: ", error);
        return throwError(error);
      })
    )
  }

Component:

  updatePage() {
    this.googleBooksService.getBooks(this.query, this.pageIndex * 10, this.pageSize)
      .subscribe((data: BookSearchResponseModel) => {
        if (data && data.items) {
          this.searchResults = data.items;
          console.log('Total items from API', data.totalItems)
          this.totalPages = Math.ceil(data.totalItems / this.pageSize);
        }
      })
  }

  prevPage() {
    if (this.pageIndex > 0) {
      this.pageIndex--;
      this.updatePage();
    }
  }

  nextPage() {
    this.pageIndex++;
    this.updatePage();
  }

The issue I am having is that whenever I hit "next page" the number of "totalItems" from the API jumps, when it should be the same.

For example, a search query of "Brandon Sanderson" has an initial return of "totalItems": 2809. When I hit "next page", the total number of items is "totalItems: 4051".

Please help!

2

There are 2 answers

2
Ohad Cochavi On

Each time you call nextPage() you subscribe again. you can store the google subscribe in Subscription object from the rxjs library the if Subscription is not undefined, unsubscribe and subscribe again. you can check what happens by starting intervals

fetchProducts(category) {
  if (this.productsSub != undefined)
    this.productsSub.unsubscribe();
  let productsList: {[key: string]:ProductData} = {};
  const snapshot = this.db.collection(category).get();
  this.productsSub = snapshot.subscribe(data => {
    data.forEach( doc => {
      console.log(doc.id)
      let product: ProductData = doc.data() as ProductData;
      productsList[doc.id] = product;
   }, e => {
           console.log(e);
      });

    //Update the list
    this.products = productsList;
    //Stream the list
    this.productsList.next(productsList);
    console.log(productsList);
  });
}

this is how I fetch data from firebase, productsSub is Subscription Object

0
Dre On

I'm running into the same issue and this seems to be a bug in the Google API itself. I can reproduce it from their web API console. Look at this example where I use the same query (not shown in the screen due to scrolling limitations) and two different startIndex values.

API request1 API request2