rewrite in typescript
This commit is contained in:
parent
a3841f5f37
commit
f673339d90
10 changed files with 211 additions and 129 deletions
6
src/contracts/IFetchResult.ts
Normal file
6
src/contracts/IFetchResult.ts
Normal file
|
@ -0,0 +1,6 @@
|
|||
import IRedditResult from "./IRedditResult";
|
||||
|
||||
export default interface IFetchResult {
|
||||
IsSuccess: boolean;
|
||||
Result?: IRedditResult;
|
||||
}
|
11
src/contracts/IRedditResult.ts
Normal file
11
src/contracts/IRedditResult.ts
Normal file
|
@ -0,0 +1,11 @@
|
|||
export default interface IRedditResult {
|
||||
Archived: boolean,
|
||||
Downs: number,
|
||||
Hidden: boolean,
|
||||
Permalink: string,
|
||||
Subreddit: string,
|
||||
SubredditSubscribers: number,
|
||||
Title: string,
|
||||
Ups: number,
|
||||
Url: string
|
||||
}
|
61
src/index.ts
Normal file
61
src/index.ts
Normal file
|
@ -0,0 +1,61 @@
|
|||
import IFetchResult from "./contracts/IFetchResult";
|
||||
import IRedditResult from "./contracts/IRedditResult";
|
||||
import fetch from "node-fetch";
|
||||
|
||||
const sortable = [
|
||||
'new',
|
||||
'hot',
|
||||
'top'
|
||||
];
|
||||
|
||||
export default async function randomBunny(subreddit: string, sortBy: string, maxTries = 100): Promise<IFetchResult> {
|
||||
if (!sortable.includes(sortBy)) sortBy = 'hot';
|
||||
|
||||
const result = await fetch(`https://reddit.com/r/${subreddit}/${sortBy}.json`);
|
||||
|
||||
if (!result) {
|
||||
return {
|
||||
IsSuccess: false
|
||||
}
|
||||
}
|
||||
|
||||
const json = await result.json() as any;
|
||||
|
||||
if (!json) {
|
||||
return {
|
||||
IsSuccess: false
|
||||
}
|
||||
}
|
||||
|
||||
const data = json.data.children;
|
||||
const size = data.length;
|
||||
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
const random = Math.floor((Math.random() * size - 1) + 0); // Between 0 and (size - 1)
|
||||
|
||||
const randomSelect = data[random].data;
|
||||
|
||||
const redditResult: IRedditResult = {
|
||||
Archived: randomSelect['archived'],
|
||||
Downs: randomSelect['downs'],
|
||||
Hidden: randomSelect['hidden'],
|
||||
Permalink: randomSelect['permalink'],
|
||||
Subreddit: randomSelect['subreddit'],
|
||||
SubredditSubscribers: randomSelect['subreddit_subscribers'],
|
||||
Title: randomSelect['title'],
|
||||
Ups: randomSelect['ups'],
|
||||
Url: randomSelect['url']
|
||||
};
|
||||
|
||||
if (redditResult.Url.includes('.jpg')) {
|
||||
return {
|
||||
IsSuccess: true,
|
||||
Result: redditResult
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
IsSuccess: false
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue