Skip to content

Commit

Permalink
fix(helper): 🐛 improve key check so empty objects don't pass
Browse files Browse the repository at this point in the history
  • Loading branch information
djdembeck committed Aug 17, 2022
1 parent f0e431e commit 0bcea5f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/helpers/books/audible/ApiHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,21 @@ class ApiHelper {
}

hasRequiredKeys() {
if (!this.inputJson) throw new Error(`No input data`)
const isValidKey = (key: string): boolean => {
if (!this.inputJson) throw new Error(`No input data`)
// Make sure key exists in inputJson
if (!Object.hasOwnProperty.call(this.inputJson, key)) return false
// Get value of key
const value = this.inputJson[key as keyof typeof this.inputJson]
// Make sure key is not falsy
if (!value) return false
// Make sure key is not an empty object
if (typeof value === 'object' && Object.entries(value).length === 0) return false

return true
}

// Create new const for presence check within forloop
const json = this.inputJson
const requiredKeys = [
'asin',
'authors',
Expand All @@ -50,7 +62,7 @@ class ApiHelper {
'title'
]

return requiredKeys.every((key) => Object.keys(json).includes(key))
return requiredKeys.every((key) => isValidKey(key))
}

isParentCategory(category: Category): boolean {
Expand Down
10 changes: 10 additions & 0 deletions tests/helpers/books/audible/ApiHelper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ describe('ApiHelper edge cases should', () => {
const data = await helper.fetchBook()
expect(data).toEqual(apiResponse)
})

test('not pass key check when on empty image object', () => {
helper.inputJson.product_images = {}
expect(helper.hasRequiredKeys()).toBe(false)
})

test('not pass key check when on falsy value', () => {
helper.inputJson.asin = ''
expect(helper.hasRequiredKeys()).toBe(false)
})
})

describe('ApiHelper should throw error when', () => {
Expand Down

0 comments on commit 0bcea5f

Please sign in to comment.