freeCodeCamp/api-server/server/rss/index.js

79 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-05-15 05:12:05 +00:00
import _ from 'lodash';
import compareDesc from 'date-fns/compare_desc';
import debug from 'debug';
import { getLybsynFeed } from './lybsyn';
const log = debug('fcc:rss:news-feed');
const fiveMinutes = 1000 * 60 * 5;
class NewsFeed {
constructor() {
this.state = {
readyState: false,
lybsynFeed: [],
combinedFeed: []
};
this.refreshFeeds();
setInterval(this.refreshFeeds, fiveMinutes);
}
setState = stateUpdater => {
const newState = stateUpdater(this.state);
this.state = _.merge({}, this.state, newState);
return;
};
2018-05-15 05:12:05 +00:00
refreshFeeds = () => {
const currentFeed = this.state.combinedFeed.slice(0);
log('grabbing feeds');
2019-06-15 18:15:30 +00:00
return Promise.all([getLybsynFeed()])
.then(([lybsynFeed]) =>
this.setState(state => ({
2019-02-06 14:19:58 +00:00
...state,
lybsynFeed
}))
)
2019-02-06 14:19:58 +00:00
.then(() => {
log('crossing the streams');
2019-06-15 18:15:30 +00:00
const { lybsynFeed } = this.state;
const combinedFeed = [...lybsynFeed].sort((a, b) => {
2019-02-06 14:19:58 +00:00
return compareDesc(a.isoDate, b.isoDate);
});
this.setState(state => ({
...state,
combinedFeed,
readyState: true
}));
2018-05-15 05:12:05 +00:00
})
2019-02-06 14:19:58 +00:00
.catch(err => {
console.log(err);
this.setState(state => ({
...state,
combinedFeed: currentFeed
}));
2018-05-15 05:12:05 +00:00
});
};
2018-05-15 05:12:05 +00:00
getFeed = () =>
new Promise(resolve => {
2018-05-15 05:12:05 +00:00
let notReadyCount = 0;
function waitForReady() {
log('notReadyCount', notReadyCount);
notReadyCount++;
return this.state.readyState || notReadyCount === 5
? resolve(this.state.combinedFeed)
: setTimeout(waitForReady, 100);
2018-05-15 05:12:05 +00:00
}
log('are we ready?', this.state.readyState);
return this.state.readyState
? resolve(this.state.combinedFeed)
: setTimeout(waitForReady, 100);
});
2018-05-15 05:12:05 +00:00
}
export default NewsFeed;