2021-10-28 21:41:42 +02:00
|
|
|
const axios = require('axios')
|
|
|
|
const Logger = require('../Logger')
|
|
|
|
|
|
|
|
class GoogleBooks {
|
|
|
|
constructor() { }
|
|
|
|
|
|
|
|
extractIsbn(industryIdentifiers) {
|
|
|
|
if (!industryIdentifiers || !industryIdentifiers.length) return null
|
|
|
|
|
|
|
|
var isbnObj = industryIdentifiers.find(i => i.type === 'ISBN_13') || industryIdentifiers.find(i => i.type === 'ISBN_10')
|
|
|
|
if (isbnObj && isbnObj.identifier) return isbnObj.identifier
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
|
|
|
cleanResult(item) {
|
|
|
|
var { id, volumeInfo } = item
|
|
|
|
if (!volumeInfo) return null
|
2022-12-16 00:54:02 +01:00
|
|
|
const { title, subtitle, authors, publisher, publisherDate, description, industryIdentifiers, categories, imageLinks } = volumeInfo
|
|
|
|
|
|
|
|
let cover = null
|
|
|
|
// Selects the largest cover assuming the largest is the last key in the object
|
|
|
|
if (imageLinks && Object.keys(imageLinks).length) {
|
2022-12-18 00:18:11 +01:00
|
|
|
cover = imageLinks[Object.keys(imageLinks).pop()]
|
|
|
|
cover = cover?.replace(/^http:/, 'https:') || null
|
2022-12-16 00:54:02 +01:00
|
|
|
}
|
2021-10-28 21:41:42 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
id,
|
|
|
|
title,
|
|
|
|
subtitle: subtitle || null,
|
|
|
|
author: authors ? authors.join(', ') : null,
|
|
|
|
publisher,
|
2022-03-14 01:34:31 +01:00
|
|
|
publishedYear: publisherDate ? publisherDate.split('-')[0] : null,
|
2021-10-28 21:41:42 +02:00
|
|
|
description,
|
2022-12-16 00:54:02 +01:00
|
|
|
cover,
|
2022-10-01 23:51:22 +02:00
|
|
|
genres: categories && Array.isArray(categories) ? [...categories] : null,
|
2021-10-28 21:41:42 +02:00
|
|
|
isbn: this.extractIsbn(industryIdentifiers)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async search(title, author) {
|
2021-12-30 10:57:28 +01:00
|
|
|
title = encodeURIComponent(title)
|
2021-10-28 21:41:42 +02:00
|
|
|
var queryString = `q=intitle:${title}`
|
2021-12-30 10:57:28 +01:00
|
|
|
if (author) {
|
|
|
|
author = encodeURIComponent(author)
|
|
|
|
queryString += `+inauthor:${author}`
|
|
|
|
}
|
2021-10-28 21:41:42 +02:00
|
|
|
var url = `https://www.googleapis.com/books/v1/volumes?${queryString}`
|
|
|
|
Logger.debug(`[GoogleBooks] Search url: ${url}`)
|
|
|
|
var items = await axios.get(url).then((res) => {
|
|
|
|
if (!res || !res.data || !res.data.items) return []
|
|
|
|
return res.data.items
|
|
|
|
}).catch(error => {
|
|
|
|
Logger.error('[GoogleBooks] Volume search error', error)
|
|
|
|
return []
|
|
|
|
})
|
|
|
|
return items.map(item => this.cleanResult(item))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = GoogleBooks
|