-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (80 loc) · 2.39 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
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env node
const configed = require('dotenv').config();
// file system
const fs = require('fs');
// Use the unofficial Node.js client library to integrate News API into your Node.js application
// without worrying about what's going on under the hood.
// https://newsapi.org/docs/client-libraries/node-js
const NewsAPI = require('newsapi');
const MAX_PAGE_SIZE = 100;
const apiKey = process.env.NEWS_API_KEY;
if(apiKey === undefined) {
console.error('no News API key defined in environment variable NEWS_API_KEY');
process.exit(1);
}
// expects the NEWS_API_KEY environment variable to be set to the value of your API key.
const newsapi = new NewsAPI(apiKey);
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === null || obj[propName] === undefined) {
delete obj[propName];
}
}
}
class News {
everything(params) {
return this._query('everything', params);
}
topHeadlines(params) {
return this._query('topHeadlines', params);
}
sources(params) {
return newsapi.v2.sources(params);
}
_query(endpoint, params) {
return new Promise((resolve, reject) => {
this._paginatedEndpoint(endpoint, params).then((result) => {
resolve(this._paginatedResponse(result));
})
.catch(function(e) {
reject(e);
});
});
}
_paginatedEndpoint(name, params) {
// remove undefined values so they are not coerced to strings
clean(params);
// assume first page if no page param supplied
const { page = 1 } = params;
// make a single request if we know there's only one page
if (page === 1) {
return newsapi.v2[name](params);
} else if (page > 1) {
let promises = [];
for(let i = 0; i < pages; i++) {
apiParams = Object.assign({ page: (i + 1), pageSize }, params);
delete params. pages;
const req = newsapi.v2[name](apiParams);
promises.push(req);
}
return Promise.all(promises);
}
}
_paginatedResponse(result, verbose, write) {
let merged = result;
if(Array.isArray(result)) {
merged = {
status: 'ok',
totalResults: result[0].totalResults,
articles: []
};
result.reduce((acc, { articles }) => {
acc.articles = acc.articles.concat(articles);
return acc;
}, merged);
}
return merged;
}
}
// export an instantiated singleton
module.exports = new News();