Google books api returns missing parameters

ⅰ亾dé卋堺 提交于 2021-02-11 12:46:31

问题


I am making a react app that searches for a book by title and returns the results.

It's mostly working fine, but for some titles searched (such as "hello") it can't get the results because the parameters are missing.

Specially, the "amount" value is missing, and it can get me e-books that are not for sale even if I add the filter=paid-ebooks param while fetching the api. Using projection=full doesn't help either.

For example, when I call the api with

https://www.googleapis.com/books/v1/volumes?printType=books&filter=paid-ebooks&key=${APIKEY}

and use the fetched data inside books array in reactjs:

this.props.books.map((book, index) => {
         return (
              <CardItem
                 key={index}
                 title={book.volumeInfo.title}
                 authors={book.volumeInfo.authors ? 
                 book.volumeInfo.authors.join(', ') : 
                 "Not provided"}
                 price={book.saleInfo.listPrice.amount}
                 publisher={book.volumeInfo.publisher}
                 addToCart={() => 
                 this.props.addItem(this.props.books[index])}
                  />
                            )
                        })

One of the results it gets is like this:

"saleInfo": {
    "country": "TR",
    "saleability": "NOT_FOR_SALE",
    "isEbook": false
   }

While it should be like, what's expected is :

"saleInfo": {
    "country": "TR",
    "saleability": "FOR_SALE",
    "isEbook": true,
    "listPrice": {
     "amount": 17.23,
     "currencyCode": "TRY"
    }

And trying to search with this api answer throws the error :

TypeError: Cannot read property 'amount' of undefined

price={book.saleInfo.listPrice.amount}

As you can see in react code's authors, this issue comes up with authors parameter too, which I've bypassed as seen in the code. But I cannot do the same with amount. Is this a known error in Google Books API or is there a way to prevent this? I don't understand why it still returns me e-books that are not for sale even with filter=paid-ebooks param.


回答1:


I have not dug into the API documentation. An ideal solution would be a query param that only sends back books with a list price (like you tried with filter=paid-ebooks). Because that's not working, a simple fix would be to filter your results once you get them.

Assuming the response contains an array of book objects, it would look something like this:

const paidBooks = apiResponse.data.filter(book => book.listPrice)

This code will take the response from the API, and filter out all books that do not contain a truthy value for listPrice




回答2:


That totally right, actually i never used react but the same logic try using try{ }catch(error){} for those missing data



来源:https://stackoverflow.com/questions/52545795/google-books-api-returns-missing-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!