redditimage
Version:
Gets a random image from a subreddit
24 lines (23 loc) • 809 B
JavaScript
/**
*
* @param subreddit {string} Name of the subreddit
*/
const sf = require('snekfetch');
const red = (subreddit) => {
if (!subreddit || typeof subreddit !== 'string') throw Error('Please give a valid subreddit');
return new Promise((resolve, reject) => {
sf.get(`https://www.reddit.com/r/${subreddit}/random.json?limit=1`).then(res => {
let image;
try {
image = res.body[0].data.children[0].data.preview.images[0].source.url;
} catch (e) {
image = res.body.data.children[0].data.preview.images[0].source.url;
}
if (!image) red(subreddit);
return resolve(image);
}).catch((err) => {
reject(err);
});
});
};
module.exports = red;