Skip to content

Instantly share code, notes, and snippets.

@anishshobithps
Last active January 19, 2021 15:08
Show Gist options
  • Save anishshobithps/e469d568aec853ee93e8eb1fe6d7c37e to your computer and use it in GitHub Desktop.
Save anishshobithps/e469d568aec853ee93e8eb1fe6d7c37e to your computer and use it in GitHub Desktop.
Fetching content from subbreddits via using node-fetch . Implementation in typescript
/**
*@copyright 2021 Anish Shobith P S
*/
import * as fetch from 'node-fetch';
export type subRedditType = "top" | "hot" | "controversial" | "new" | "rising";
/**
* Fetchs a subreddit with a limit to 100 responses
* @param {string} subreddit - subreddit you wanna fetch.
* @param {?string} type - The type you wanna fetch.
* @returns Promise<RedditResult>
*/
export async function fetchSubreddit(subreddit: string, type?: subRedditType): Promise<RedditResult> {
const res: RedditResult = await fetch(`https://www.reddit.com/r/${subreddit}${type?.length ? `/${type}` : ""}/.json?limit=100`);
return res;
}
/**
* Gets a random response from the above fetch.
* @param {string} subreddit - subreddit you wanna fetch.
* @param {?string} type - The type you wanna fetch.
* @returns Promise<RedditResultItem>
*/
export async function randomSubredditItem(subreddit: string, type?: subRedditType): Promise<RedditResultItem> {
const res: RedditResult = await fetchSubreddit(subreddit, type);
const random: RedditResultItem = res.data.children[~~(Math.random() * res.data.children.length)];
return random;
}
// Note: This is not all the data that reddit returns.
interface RedditResult {
kind: string
data: RedditResultData;
}
interface RedditResultData {
modhash: string;
dist: number;
children: RedditResultItem[];
}
interface RedditResultItem {
kind: RedditResultItemKind;
data: RedditResultItemData;
}
type RedditResultItemKind = "t1" | "t2" | "t3" | "t4" | "t5" | "t6";
type subType = "public" | "private";
interface RedditResultItemData {
subreddit: string;
selftext: string;
author_fullname: string;
title: string;
hidden: boolean;
name: string;
quarantine: boolean;
upvote_ratio: number;
subreddit_type: subType;
ups: number;
is_original_content: boolean;
is_reddit_media_domain: boolean;
created: Date;
over_18: boolean;
media_only: boolean;
author: string;
permalink: string;
url: string;
created_utc: Date;
thumbnail?: string;
url_overridden_by_dest?: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment