UNPKG

justreddit

Version:

A simple package for getting random posts, random images, random SubReddits, and SubReddit info.

42 lines (41 loc) 1.75 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.post = post; exports.randomPost = randomPost; const fetch_1 = __importDefault(require("./utils/fetch")); const IMAGE_EXTENSIONS = ["jpg", "jpeg", "png", "gif", "webp"]; function parsePost({ subreddit, over_18, locked, media_only, pinned, author, id, archived, edited, ups, is_original_content, downs, selftext, title, created, url }) { return { subreddit, id, author, title, body: selftext, image: IMAGE_EXTENSIONS.some((extension) => url.toLowerCase().endsWith(`.${extension}`)) ? url : null, created: new Date(created * 1000), likes: ups, dislikes: downs, over18: over_18, mediaOnly: media_only, pinned, locked, archived, edited, isOriginalContent: is_original_content, }; } async function post(subreddit, postID) { const response = await (0, fetch_1.default)(`${subreddit}/comments/${postID}`); return parsePost(response[0].data.children[0].data); } const sortingOptions = ["hot", "new", "top", "rising"]; async function randomPost(subreddit, sortingOption = "top") { if (!sortingOptions.includes(sortingOption)) throw new TypeError(`Invalid sorting option. Valid options are: ${sortingOptions.join(", ")}`); const response = await (0, fetch_1.default)(subreddit ? `${subreddit}/${sortingOption}` : `best`); const posts = response.data.children.filter((post) => post.kind === "t3"); return parsePost(posts[Math.floor(Math.random() * posts.length)].data); }