fe-middleware/src/services/GelbooruApiService.ts

26 lines
1.1 KiB
TypeScript
Raw Normal View History

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