Skip to content

Commit

Permalink
refactor(helper): ♻️ sort data when stitching it
Browse files Browse the repository at this point in the history
  • Loading branch information
djdembeck committed Aug 26, 2022
1 parent 890dd99 commit 30e769e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
16 changes: 7 additions & 9 deletions src/helpers/books/audible/StitchHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import { AudibleProduct } from '#config/typing/audible'
import { ApiBook, Book, HtmlBook } from '#config/typing/books'
import ApiHelper from '#helpers/books/audible/ApiHelper'
import ScrapeHelper from '#helpers/books/audible/ScrapeHelper'
import SharedHelper from '#helpers/shared'

class StitchHelper {
apiHelper: ApiHelper
apiParsed!: ApiBook
apiResponse!: AudibleProduct
asin: string
helper: SharedHelper
scrapeHelper: ScrapeHelper
scraperParsed: HtmlBook | undefined
scraperResponse: CheerioAPI | undefined
Expand All @@ -18,6 +20,7 @@ class StitchHelper {
this.asin = asin
// Set up helpers
this.apiHelper = new ApiHelper(asin)
this.helper = new SharedHelper()
this.scrapeHelper = new ScrapeHelper(asin)
}

Expand Down Expand Up @@ -70,7 +73,8 @@ class StitchHelper {
*/
async includeGenres(): Promise<Book> {
if (this.scraperParsed?.genres?.length) {
return { ...this.apiParsed, ...this.scraperParsed } as Book
const sortedObject = this.helper.sortBookData({ ...this.apiParsed, ...this.scraperParsed })
return sortedObject
}
return this.apiParsed as Book
}
Expand All @@ -84,14 +88,8 @@ class StitchHelper {
await this.fetchSources()
await this.parseResponses()

// If parsed API response has genres, return it
if (this.apiParsed.genres?.length) {
return this.apiParsed as Book
}

// If no genres in API response, return scraper parsed response
const stitchedGenres = await this.includeGenres()
return stitchedGenres
// Return object with genres attached if it exists
return this.includeGenres()
}
}

Expand Down
8 changes: 8 additions & 0 deletions src/helpers/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,14 @@ class SharedHelper {
getParamString(params: string[]): string {
return params.slice(0, -1).join(',') + '&' + params.slice(-1)
}

sortBookData(bookData: Book) {
const keys = Object.keys(bookData) as Array<keyof Book>
const ordered = keys.sort().reduce((obj, key) => {
return { ...obj, [key]: bookData[key] }
}, {} as Book)
return ordered
}
}

export default SharedHelper

0 comments on commit 30e769e

Please sign in to comment.