-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
92 lines (84 loc) · 2.42 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
83
84
85
86
87
88
89
90
91
92
'use strict';
// replace this 👇 with your API key
const apiKey = 'fa54953a641b4660b4b294dcd93c176c';
const searchURL = 'https://newsapi.org/v2/everything';
/**
* Creates a query string from a params object
* @param {object} params
* @returns {string} query string
*/
function formatQueryParams(params) {
const queryItems = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
return queryItems.join('&');
}
/**
* Performs the fetch call to get news
* @param {string} query
* @param {number} maxResults
*/
function getNews(query, maxResults=10) {
const params = {
q: query,
language: 'en',
};
const queryString = formatQueryParams(params);
const url = searchURL + '?' + queryString;
const options = {
headers: new Headers({'X-Api-Key': apiKey})
};
fetch(url, options)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => displayResults(responseJson, maxResults))
.catch(err => {
$('#js-error-message').text(`Something went wrong: ${err.message}`);
});
}
/**
* Appends formatted HTML results to the page
* @param {object} responseJson
* @param {number} maxResults
*/
function displayResults(responseJson, maxResults) {
console.log('responseJson: ',responseJson);
// clear the error message
$('#js-error-message').empty();
// if there are previous results, remove them
$('#results-list').empty();
// iterate through the articles array, stopping at the max number of results
responseJson.articles.forEach(article => {
// For each object in the articles array:
// Add a list item to the results list with
// the article title, source, author,
// description, and image
$('#results-list').append(
`
<li><h3><a href="${article.url}">${article.title}</a></h3>
<p>${article.source.name}</p>
<p>By ${article.author}</p>
<p>${article.description}</p>
<img src='${article.urlToImage}'>
</li>
`
);
});
// unhide the results section
$('#results').removeClass('hidden');
}
/**
* Handles the form submission
*/
function watchForm() {
$('form').submit(event => {
event.preventDefault();
const searchTerm = $('#js-search-term').val();
const maxResults = $('#js-max-results').val();
getNews(searchTerm, maxResults);
});
}
$(watchForm);