-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcronJob.js
More file actions
69 lines (65 loc) · 2 KB
/
cronJob.js
File metadata and controls
69 lines (65 loc) · 2 KB
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
const fetch = require('isomorphic-unfetch');
const schedule = require('node-schedule');
const differenceInDays = require('date-fns/difference_in_days');
const endOfToday = require('date-fns/end_of_today');
const config = require('./config/config.json');
const connectDb = require('./utilities/connectDb');
const QUERY = 'New Orleans';
let db;
function makeRequest(findStr, page) {
console.log(findStr, page);
const q = encodeURIComponent(findStr);
const baseUrl = 'https://api.nytimes.com/svc/search/v2/articlesearch.json';
let query = '?api-key=' + config.nytimesAPI.key + '&q=' + q + '&sort=newest&page=' + page;
const urlToFetch = baseUrl + query;
return fetch(urlToFetch)
.then(results => results.json())
.then((response) => {
if (!response.response) {
return response;
}
return response.response.docs;
});
}
function fillDB(query, page) {
connectDb()
.then(db => {
makeRequest(query, page)
.then(articles => {
if (typeof articles !== 'object') {
return [false];
}
const promises = articles.map(article => {
return db.collection('articles').findOne({ web_url: article.web_url, pub_date: new Date(article.pub_date) })
.then(found => {
if (differenceInDays(endOfToday(), new Date(article.pub_date)) > 60 || found || !article.web_url) {
return false;
}
article.pub_date = new Date(article.pub_date);
return db.collection('articles').save(article);
});
});
return Promise.all(promises);
})
.then(results => {
if (results.some(result => !result)) {
console.log('Reached the end');
return false;
}
page += 1;
setTimeout(() => {
fillDB(QUERY, page);
}, 2000);
})
.then(() => {
console.log('connection closed');
db.close();
})
.catch(error => console.log(error));
});
}
fillDB(QUERY, 0);
const j = schedule.scheduleJob('*/3 * * * *', () => {
console.log('running job');
fillDB(QUERY, 0);
});