-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (65 loc) · 2.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
function makeTitleText(title, subtitle) {
if (!title) {
return "";
}
return subtitle ? `${title}: ${subtitle}` : title;
}
function makeAuthorsText(authors) {
return authors ? authors.join(", ") : "";
}
function renderBookList(books) {
if (!books) {
return;
}
let listElm = document.createElement("ul");
listElm.classList = ["book-list"];
for (let i = 0; i <= books.length; i++) {
let book = books[i];
if (book) {
let { title, subtitle, imageLinks, authors } = book.volumeInfo;
let bookElm = document.createElement("li");
bookElm.classList = ["book-list-item"];
let linkElm = document.createElement("a");
linkElm.href = `/book.html?id=${book.id}`;
let coverImageElm = document.createElement("img");
coverImageElm.src =
(imageLinks && imageLinks.thumbnail) || "./default-book-cover.png";
let detailsContainer = document.createElement("div");
detailsContainer.classList = ["book-details"];
let titleElm = document.createElement("h3");
titleElm.innerHTML = makeTitleText(title, subtitle);
let authorElm = document.createElement("p");
authorElm.innerHTML = makeAuthorsText(authors);
detailsContainer.appendChild(titleElm);
detailsContainer.appendChild(authorElm);
linkElm.appendChild(coverImageElm);
linkElm.appendChild(detailsContainer);
bookElm.appendChild(linkElm);
listElm.appendChild(bookElm);
}
}
let listSectionElm = document.getElementById("finder-result-section");
listSectionElm.replaceChildren(listElm);
}
async function handleFinderFormSubmit(event) {
event.preventDefault();
let form = new FormData(event.target);
let formData = Object.fromEntries(form);
let keyword = formData.keyword;
// guard against api call error
if (keyword) {
try {
let listBookResponse = await axios.get(
`https://www.googleapis.com/books/v1/volumes?q=${formData.keyword}`
);
renderBookList(listBookResponse.data.items);
} catch (error) {
console.log(`Error`, error);
}
}
}
async function main() {
let finderForm = document.getElementById("finder-form");
finderForm.addEventListener("submit", handleFinderFormSubmit);
}
main();