fe-middleware/src/services/gelbooruApiService.ts

29 lines
956 B
TypeScript

import { env } from "bun";
import logger from "src/logger";
import GelbooruApiResponse from "src/types/GelbooruApiResponse";
import GelbooruServiceResponse from "src/types/GelbooruServiceResponse";
export const LIMIT = env.GELBOORU_IMAGES_PER_REQUEST || 100;
export const TAGS = encodeURIComponent(env.GELBOORU_TAGS || "");
export async function get(): Promise<GelbooruServiceResponse> {
const url: string = `https://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=${LIMIT}&json=1&tags=${TAGS}`;
const response: GelbooruApiResponse = (await fetch(url).then(
async (res) => {
if (!res.ok) {
logger.error(`${res.status}: ${res.statusText}, ${await res.text()}`);
throw new Error("Error fetching images");
} else {
return res.json();
}
}
)) as GelbooruApiResponse;
return {
posts: response.post.map((post) => ({
url: post.file_url,
tags: post.tags.split(" "),
})),
};
}