2024-04-17 17:48:56 +00:00
|
|
|
import { env } from "bun";
|
2024-04-17 18:02:24 +00:00
|
|
|
import logger from "src/logger";
|
2024-04-17 17:23:39 +00:00
|
|
|
import GelbooruApiResponse from "src/types/GelbooruApiResponse";
|
|
|
|
import GelbooruServiceResponse from "src/types/GelbooruServiceResponse";
|
2024-03-28 10:41:36 +00:00
|
|
|
|
|
|
|
class GelbooruApiService {
|
2024-04-17 18:04:43 +00:00
|
|
|
async get(): Promise<GelbooruServiceResponse> {
|
|
|
|
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
|
|
|
|
2024-04-17 18:04:43 +00:00
|
|
|
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;
|
2024-03-28 10:41:36 +00:00
|
|
|
|
2024-04-17 18:04:43 +00:00
|
|
|
return {
|
|
|
|
posts: response.post.map((post) => ({
|
|
|
|
url: post.file_url,
|
|
|
|
tags: post.tags.split(" "),
|
|
|
|
})),
|
|
|
|
};
|
|
|
|
}
|
2024-03-28 10:41:36 +00:00
|
|
|
}
|
|
|
|
|
2024-04-17 18:04:43 +00:00
|
|
|
export default new GelbooruApiService();
|