random-bunny/src/index.ts

68 lines
1.8 KiB
TypeScript
Raw Normal View History

import IReturnResult from "./contracts/IReturnResult.js";
import IRedditResult from "./contracts/IRedditResult.js";
import fetch from "got-cjs";
import { List } from 'linqts';
import IFetchResult from "./contracts/IFetchResult.js";
2021-12-01 20:32:20 +00:00
const sortable = [
'new',
'hot',
'top'
];
2023-02-22 18:18:50 +00:00
export default async function randomBunny(subreddit: string, sortBy?: string): Promise<IReturnResult> {
2021-12-01 20:53:45 +00:00
if (!sortBy || !sortable.includes(sortBy)) sortBy = 'hot';
2021-12-01 20:32:20 +00:00
const result = await fetch(`https://reddit.com/r/${subreddit}/${sortBy}.json`);
if (!result) {
return {
IsSuccess: false
}
}
2021-12-01 20:39:02 +00:00
const json = JSON.parse(result.body);
2021-12-01 20:32:20 +00:00
if (!json) {
return {
IsSuccess: false
}
}
const data: IFetchResult[] = json.data.children;
2023-02-22 18:18:50 +00:00
const dataWithImages = new List<IFetchResult>(data)
.Where(x => x!.data.url.includes('.jpg') || x!.data.url.includes('.png'))
.ToArray();
2021-12-01 20:32:20 +00:00
let random = 0;
2021-12-01 20:32:20 +00:00
if (dataWithImages.length == 0) {
return {
2023-02-22 18:18:50 +00:00
IsSuccess: false,
};
} else {
random = Math.floor((Math.random() * (dataWithImages.length - 1)) + 0); // Between 0 and (size - 1)
}
const randomSelect = dataWithImages[random];
2023-02-22 18:18:50 +00:00
const randomData = randomSelect.data;
const redditResult: IRedditResult = {
Archived: randomData['archived'],
Downs: randomData['downs'],
Hidden: randomData['hidden'],
Permalink: randomData['permalink'],
Subreddit: randomData['subreddit'],
SubredditSubscribers: randomData['subreddit_subscribers'],
Title: randomData['title'],
Ups: randomData['ups'],
Url: randomData['url']
};
2021-12-01 20:32:20 +00:00
return {
2023-02-22 18:18:50 +00:00
IsSuccess: true,
Result: redditResult
};
2021-12-01 20:32:20 +00:00
}