69 lines
1.9 KiB
TypeScript
69 lines
1.9 KiB
TypeScript
import { ReqUrlBuilder } from "../utils/url_builder.ts";
|
|
|
|
export const SAFEBOORU_HOST = "safebooru.org"
|
|
|
|
export type GetSafebooruPostsFunc = (limit: number, pageId: number, tags: string[]) => Promise<SafebooruPostData[]>
|
|
interface SafebooruPostData {
|
|
preview_url: string;
|
|
sample_url: string;
|
|
file_url: string;
|
|
directory: number;
|
|
hash: string;
|
|
width: number;
|
|
height: number;
|
|
id: number;
|
|
image: string;
|
|
change: number;
|
|
owner: string;
|
|
parent_id: number;
|
|
rating: string;
|
|
sample: boolean;
|
|
sample_height: number;
|
|
sample_width: number;
|
|
score: number | null;
|
|
tags: string;
|
|
source: string;
|
|
status: string;
|
|
has_notes: boolean;
|
|
comment_count: number;
|
|
}
|
|
|
|
|
|
const tagsArrToUrlParam = (tags: string[]): string => {
|
|
if (tags.length > 0) {
|
|
let hasNonEmpty = false
|
|
for (let i = 0; i < tags.length; i++) {
|
|
if (tags[i].length > 0) {
|
|
hasNonEmpty = true
|
|
break
|
|
}
|
|
}
|
|
if (!hasNonEmpty) return ""
|
|
|
|
let param: string = "tags="
|
|
tags.forEach((tag, i) => {
|
|
if (i != 0) { param += " " }
|
|
param += tag
|
|
})
|
|
return param
|
|
}
|
|
return ""
|
|
}
|
|
const mkPostsLimitParam = (limit: number): string => `limit=${limit}`
|
|
const mkPageIdParam = (pid: number): string => `pid=${pid}`
|
|
|
|
|
|
export const getSafebooruPosts = async (limit: number, pageId: number, tags: string[]): Promise<SafebooruPostData[]> => {
|
|
const reqURL = new ReqUrlBuilder(`${SAFEBOORU_HOST}`).setProtocol("https").setPath("/index.php")
|
|
.setParams("page=dapi", "s=post", "q=index", "json=1") // Default for safebooru API
|
|
.setParams(mkPostsLimitParam(limit), mkPageIdParam(pageId))
|
|
.setParams(tagsArrToUrlParam(tags)).getReqURL()
|
|
|
|
const resp = await fetch(reqURL)
|
|
if (!resp.ok) { return [] }
|
|
const respData = await resp.text()
|
|
if (respData.length < 3) return []
|
|
const posts: SafebooruPostData[] = JSON.parse(respData)
|
|
return posts
|
|
}
|