-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
125 lines (91 loc) · 2.48 KB
/
script.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Select items
let searchInput = document.querySelector("#input");
let submitButton = document.querySelector("#submit");
let errorArea = document.querySelector("#error");
let contentResult = document.querySelector("#results");
// Identify endpoint and params
const endPoint = 'https://en.wikipedia.org/w/api.php?';
const params = {
origin: '*',
format: 'json',
action: 'query',
prop: 'extracts',
exchars: 250,
exintro: true,
explaintext: true,
generator: 'search',
gsrlimit: 20,
};
// Change UI disable state
const changeUiState = (isDisabled)=>{
searchInput.disabled = isDisabled;
submitButton.disabled = isDisabled;
}
// Clear input
const clearInput = () => {
searchInput.value = "";
}
// Clear previous results
const clearPreviousResult = () => {
contentResult.innerHTML = "";
errorArea.innerHTML = "";
}
// İs it empty?
const isInputEmpty = (input) => {
if(!input || input === ""){
return true
}else{
return false
}
}
const showError = (err) => {
errorArea.innerHTML = `🚨 ${err} 🚨`
}
const handleKey = (e) => {
if(e.key === "Enter"){
getData();
}
}
const eventHandlers = ()=>{
searchInput.addEventListener("keydown",handleKey);
submitButton.addEventListener("click",getData);
}
const getData = async () => {
const userInput = searchInput.value;
if (isInputEmpty(userInput)) return;
params.gsrsearch = userInput;
clearPreviousResult();
changeUiState(true);
try {
const { data } = await axios.get(endPoint, { params });
if (data.error) throw new Error(data.error.info);
gatherData(data.query.pages);
} catch (error) {
showError(error);
} finally {
changeUiState(false)
}
}
const gatherData = (gatherDataValues) => {
const results = Object.values(gatherDataValues).map(page => ({
pageId: page.pageid,
title: page.title,
intro: page.extract,
}));
showResults(results);
}
const showResults = (results) => {
results.forEach( (result) => {
contentResult.innerHTML +=
`
<div class="results__item">
<a href="https://en.wikipedia.org/?curid=${result.pageId}" target="_blank" class="card animated bounceInUp">
<h2 class="results__item__title">${result.title}</h2>
<p class="results__item__intro">${result.intro}</p>
</a>
</div>
`
})
clearInput();
}
eventHandlers();