-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddit.mjs
56 lines (55 loc) · 1.87 KB
/
reddit.mjs
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
import axios from 'axios'
import {sleep} from './utils.mjs'
export default {
async fetchPostsInSubRedditByUser(subreddit, user) {
let pageIndex = 0;
const results = [];
const getParams = {
q: `author:${user}`,
include_over_18: 'on',
sort: 'date',
t: 'all',
restrict_sr: 'on'
};
while(true) {
console.log(`Loading /r/${subreddit} page ${pageIndex + 1}...`);
const url = `https://www.reddit.com/r/${subreddit}/search.json?${new URLSearchParams(getParams).toString()}`;
const response = await axios({
method: 'get',
url,
});
if(response.status !== 200) {
throw new Exception("Reddit failure! Is the API still working or the username correct?");
}
for(let record of response.data.data.children) {
record = record.data;
const post = {
title: record.title,
originalUrl: `https://old.reddit.com${record.permalink}`,
timestampCreated: record.created_utc,
nsfw: record.over_18
};
if(record.selftext == "") {
post.url = record.url;
}
else {
post.selftext = record.selftext;
}
results.push(post);
}
if("after" in response.data.data) {
if(response.data.data.after == null) {
break;
}
getParams.after = response.data.data.after
}
else {
break;
}
pageIndex++;
// To avoid getting rate-limited
await sleep(1000);
}
return results.reverse();
}
};