Skip to content

Commit

Permalink
fix - handle single review result
Browse files Browse the repository at this point in the history
When getting reviews from goodreads api, if a single result was
returned, it was not returned as an array. I fixed this by casting the result to an array.
  • Loading branch information
AntoineDrouhin committed Nov 17, 2020
1 parent 8e24697 commit e18e7ee
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/goodreads.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import xml from 'fast-xml-parser'
import he from 'he'
import got from 'got'
import { ensureArray } from './type-utils'

export default class Goodreads {

Expand Down Expand Up @@ -56,8 +57,10 @@ export default class Goodreads {
},
})
.text()

const reviewList: Goodreads.ReviewList = xml.parse(res)
const reviews = reviewList.GoodreadsResponse.reviews.review
// reviews.review can be an array or an item
const reviews = ensureArray(reviewList.GoodreadsResponse.reviews.review)
return reviews
}

Expand Down
7 changes: 7 additions & 0 deletions src/type-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

export function ensureArray<T>(v: T | T[]): T[] {
if (Array.isArray(v)) {
return v
}
return [v]
}
2 changes: 1 addition & 1 deletion src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ declare namespace Goodreads {
interface ReviewList {
GoodreadsResponse: {
reviews: {
review: Review[];
review: Review[] | Review;
};
};
}
Expand Down

0 comments on commit e18e7ee

Please sign in to comment.