2023-02-27 18:33:32 +00:00
|
|
|
import IReturnResult from "./contracts/IReturnResult.js";
|
|
|
|
import IRedditResult from "./contracts/IRedditResult.js";
|
2023-04-22 13:20:30 +01:00
|
|
|
import fetch from "got-cjs";
|
2022-12-18 15:27:03 +00:00
|
|
|
import { List } from 'linqts';
|
2023-02-27 18:33:32 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-18 15:27:03 +00:00
|
|
|
const data: IFetchResult[] = json.data.children;
|
2023-02-22 18:18:50 +00:00
|
|
|
|
2022-12-18 15:27:03 +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
|
|
|
|
2023-04-22 13:20:30 +01:00
|
|
|
let random = 0;
|
2021-12-01 20:32:20 +00:00
|
|
|
|
2023-04-22 13:20:30 +01:00
|
|
|
if (dataWithImages.length == 0) {
|
2022-12-18 15:27:03 +00:00
|
|
|
return {
|
2023-02-22 18:18:50 +00:00
|
|
|
IsSuccess: false,
|
2022-12-18 15:27:03 +00:00
|
|
|
};
|
2023-05-29 16:48:01 +01:00
|
|
|
} else {
|
|
|
|
random = Math.floor((Math.random() * (dataWithImages.length - 1)) + 0); // Between 0 and (size - 1)
|
2023-04-22 13:20:30 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|