-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (34 loc) · 1.15 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
const request = require('request')
module.exports = (keyword, ops, cb) => {
// Preprocess arguments
if (!cb) {
cb = ops
ops = {}
}
if (keyword) keyword = keyword.trim()
ops.subreddit = ops.subreddit || 'dankmemes'
ops.sort = ops.sort || 'relevance'
if (!keyword || keyword == "") keyword = "meme"
// Generate the URI containing the meme posts from Reddit
let uri = encodeURI(
`https://www.reddit.com/r/${ops.subreddit}/search.json?q=${keyword}&restrict_sr=1&sort=${ops.sort}`
)
request({
method: 'GET',
uri
}, (err, response, body) => {
if (err) return cb(err)
if (response.status >= 400) return cb(new Error('Status code: ' + response.statusCode))
let data = JSON.parse(body)
let posts = data.data.children
let memes = []
for (var post of posts) {
if (post.data.post_hint != "image") continue // Ignore posts that aren't images
memes.push({
title: post.data.title,
image_url: post.data.url
})
}
cb(null, memes)
}).on('error', cb)
}