-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit-app-data.js
58 lines (42 loc) · 1.91 KB
/
init-app-data.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
const axios = require('axios');
const MongoClient = require('mongodb').MongoClient
const initApp = {}
const hackerNewsBaseUrl = 'https://hacker-news.firebaseio.com/v0/';
const mongoUrl = 'mongodb://localhost:27017/hacker-news'
initApp.getHackerNewsData = async () => {
console.log('START...', performance.now());
const topItems = await getTopItems();
const storiesData = await getStoriesForTopItems(topItems.data);
const stories = storiesData
.filter(story => story.status === 'fulfilled')
.map(story => story.value.data);
await saveAllToMongo('stories', stories);
console.log('END...', performance.now());
const storyComments = stories.flatMap(story => story.kids);
const commentsData = await getCommentsForStories(storyComments);
const comments = commentsData
.filter(comment => comment.status === 'fulfilled')
.map(comment => comment.value.data);
await saveAllToMongo('comments', comments);
}
const getTopItems = async () => {
return await axios.get(`${hackerNewsBaseUrl}/topstories.json`);
};
const getStoriesForTopItems = async (topItems) => {
return await Promise.allSettled(topItems.map(itemId => axios.get(`${hackerNewsBaseUrl}/item/${itemId}.json`)));
};
const getCommentsForStories = async (comments) => {
return await Promise.allSettled(comments.map(commentId => axios.get(`${hackerNewsBaseUrl}/item/${commentId}.json`)));
};
const saveAllToMongo = async (collectionName, documentsList) => {
const client = await MongoClient.connect(mongoUrl);
let dbo = client.db();
const collections = await dbo.listCollections().toArray();
const collectionNames = collections.map(item => item.name);
if (collectionNames.includes(collectionName)) {
const drop = await dbo.collection(collectionName).drop();
}
await dbo.collection(collectionName).insertMany(documentsList);
await client.close();
}
module.exports = initApp