Created
July 21, 2021 19:19
-
-
Save mekarpeles/44563f2db60a61d29e01b3a27331de5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getBooks(container) { | |
const reISBN = /((978)?[0-9][0-9]{10}[0-9xX])|((978)?[0-9]{9}[0-9Xx])/; | |
const elements = document.getElementsByClassName(container); | |
let isbnElementMap = {}; | |
for (let i=0; i<elements.length; i++) { | |
let e = elements.item(i); | |
let match = e.innerHTML.match(reISBN); | |
if (match) { | |
isbnElementMap[match[0]] = e; | |
} | |
} | |
return isbnElementMap; | |
} | |
async function addBorrowButtons(bookContainer, btnParent) { | |
const apiurl = "https://archive.org/services/availability" | |
isbnElementMap = getBooks(bookContainer); | |
let isbns = Object.keys(isbnElementMap); | |
let url = apiurl + "?isbn=" + isbns.join(","); | |
const response = await fetch(url); | |
const data = await response.json(); | |
return { | |
"container": bookContainer, | |
"btn": btnParent, | |
"isbnElementMap": isbnElementMap, | |
"results": data.responses | |
} | |
} | |
function addOpenLibraryButtons(bookContainer, btnParent) { | |
addBorrowButtons(bookContainer, btnParent).then(data => { | |
let results = data.results; | |
for (let isbn in data.isbnElementMap) { | |
let availability = results[isbn]; | |
if (availability && availability.status !== "error") { | |
let e = data.isbnElementMap[isbn]; | |
let btns = e.getElementsByClassName(data.btn)[0]; | |
btns.innerHTML = `${btns.innerHTML}<div><a class="openlibrary-btn" href="https://openlibrary.org/borrow/ia/${availability.identifier}?ref=">Open Library</a></div>`; | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment