-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetJson.js
94 lines (79 loc) · 3.05 KB
/
getJson.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
const url = 'https://api.nytimes.com/svc/topstories/v2/travel.json?api-key=cce4958264bc4464b48eae3ce7bf2d63';
const init = {
method: 'GET',
url,
};
const imageType = 'mediumThreeByTwo210';
function createImage(src, height, width, caption) {
return `<img src=${src} height=${height} width=${width} title='${caption}' />`;
}
function getMedia(multimediaArr, flag) {
return multimediaArr.filter(mediaObj => mediaObj.format === flag)[0];
}
function createFooter(footerText) {
return `<footer>${footerText.replace('Copyright (c)', '©')}</footer>`;
}
function calculateDateFrom(seconds, difference, timeArr) {
return timeArr.reduce((result, timeObj) => {
if (result) return result;
const { infoText, numOfSeconds } = timeObj;
const interval = Math.floor(seconds / numOfSeconds);
if (interval >= 1) {
result = difference <= 0 ? `in ${interval} ${infoText}` : `${interval} ${infoText} ago`;
}
return result;
}, '');
}
function timeFrom(date) {
const difference = new Date() - date;
const seconds = Math.floor(Math.abs(difference) / 1000);
const timeArr = [
{ infoText: 'years', numOfSeconds: 60 * 60 * 24 * 365 },
{ infoText: 'months', numOfSeconds: 60 * 60 * 24 * 30 },
{ infoText: 'days', numOfSeconds: 60 * 60 * 24 },
{ infoText: 'hours', numOfSeconds: 60 * 60 },
{ infoText: 'minutes', numOfSeconds: 60 },
];
return calculateDateFrom(seconds, difference, timeArr) || 'Just now';
}
function createSection(objSection) {
const { short_url: shortUrl, title, abstract, multimedia, byline,
published_date: publishedDate } = objSection;
let image = '';
if (multimedia.length > 0) {
const { url: src, height, width, type, caption } = getMedia(multimedia, imageType);
if (type === 'image') {
image = createImage(src, height, width, caption);
}
}
const sectionEl = `<div class="intro-section">
<a href="${shortUrl}" >
<div>
${image}
<div class='text-container'>
<h2>${title}</h2>
<p>${abstract}</p>
<span class='time'>${timeFrom(new Date(publishedDate))}</span>
<span class='author'> ${byline}</span>
</div>
</div>
</a>
</div>`;
return sectionEl;
}
function addSections(json) {
const { section, results: arrSections, copyright } = json;
document.body.innerHTML = `<header>
<h1>The New York Times News</h1>
<h3>${section}</h3></header>
<div class='flexbox-container'>
${arrSections.reduce((result, el) => result + createSection(el),
'')}</div>
${createFooter(copyright)}`;
}
function processJson(json) {
addSections(json);
}
fetch(url, init)
.then(response => response.json())
.then(processJson);