added try-catch statement for requestWorker

This commit is contained in:
fzzinchemical
2025-04-02 16:04:10 +02:00
parent 7bcf64f8e9
commit 20ba603b6a

View File

@@ -1,95 +1,107 @@
import { assert } from "@std/assert/assert"; import { assert } from "@std/assert/assert";
import {requestJSON, postUrl, ImageResponse} from "./api.ts" import { ImageResponse, postUrl, requestJSON } from "./api.ts";
import { Embed, EmbedAuthor, EmbedField, EmbedImage, Field } from "@root/structures/embeds.ts"; import { Embed, EmbedAuthor, EmbedImage } from "@root/structures/embeds.ts";
import { DiscordEmbedAuthor, DiscordEmbedImage } from "npm:discordeno@18.0.1";
const keys = ["limit" , "id" , "pid" , "tags"] as const const keys = ["limit", "id", "pid", "tags"] as const;
type PostKeys = typeof keys[number] type PostKeys = typeof keys[number];
function isKey(key: string): key is PostKeys { function isKey(key: string): key is PostKeys {
return keys.includes(key as any); return keys.includes(key as any);
} }
export async function drop() { export async function drop() {
const response = await requestJSON<ImageResponse[]>(`${postUrl}&limit=1`) const response = await requestJSON<ImageResponse[]>(`${postUrl}&limit=1`);
if (response[0] === undefined) throw Error("Bro, get some sleep") if (response[0] === undefined) throw Error("Bro, get some sleep");
return response[0].file_url return response[0].file_url;
} }
export async function requestWorker(requestString: string){ export async function requestWorker(requestString: string) {
const response = await requestJSON<ImageResponse[]>(generateRequestURL(requestString)) try {
const stack: Embed[] = [] const response = await requestJSON<ImageResponse[]>(
for (const img of response) { generateRequestURL(requestString),
stack.push(new Embed( );
`ID: ${img.id}`, const stack: Embed[] = [];
img.sample_url, for (const img of response) {
new EmbedAuthor(img.owner), stack.push(
// [new EmbedField("Tags", img.tags, true)], new Embed(
new EmbedImage(img.file_url, img.height, img.width) `ID: ${img.id}`,
)) img.sample_url,
} new EmbedAuthor(img.owner),
return stack // [new EmbedField("Tags", img.tags, true)],
new EmbedImage(img.file_url, img.height, img.width),
),
);
}
return stack;
} catch (e) {
console.error((e as Error).message);
return []
}
} }
//TODO: get help in form of a nice beautiful format //TODO: get help in form of a nice beautiful format
export function help() { export function help() {
return "WIP" return "WIP";
} }
export function requestParser(requestString: string) { export function requestParser(requestString: string) {
const res = requestString.match(/\[([\s*w+:\s*[\d+|\w+,]+)\]/g) const res = requestString.match(/\[([\s*w+:\s*[\d+|\w+,]+)\]/g);
const map = new Map<PostKeys, string>() const map = new Map<PostKeys, string>();
if (res !== null) { if (res !== null) {
res[0] res[0]
.split(",") .split(",")
.forEach(param => { .forEach((param) => {
const match = param.match(/\s*(\w+)\s*:\s*([\w+,+]+)/) const match = param.match(/\s*(\w+)\s*:\s*([\w+,+]+)/);
console.debug({match}) console.debug({ match });
if (match !== null) { if (match !== null) {
if (match[1] === undefined || match[2] === undefined) throw Error("Unreachable") if (match[1] === undefined || match[2] === undefined) {
if (!isKey(match[1])) throw Error(`Key: ${match[1]} is not a Key!`) throw Error("Unreachable");
map.set(match[1], match[2]) }
} else { if (!isKey(match[1])) throw Error(`Key: ${match[1]} is not a Key!`);
throw Error(`match returned null in param = ${Deno.inspect(param)}`) map.set(match[1], match[2]);
} } else {
}) throw Error(`match returned null in param = ${Deno.inspect(param)}`);
} else { }
throw Error("Request String had some major issues chief") });
} } else {
console.debug() throw Error("Request String had some major issues chief");
return map }
console.debug();
return map;
} }
// + is replaced with a space... this is pain // + is replaced with a space... this is pain
// see percent code + === 2B // see percent code + === 2B
export function generateRequestURL(requestString: string) { export function generateRequestURL(requestString: string) {
const postCpy = new URL(postUrl.toString()) const postCpy = new URL(postUrl.toString());
for (const [k, v] of requestParser(requestString)){ for (const [k, v] of requestParser(requestString)) {
postCpy.searchParams.append(k, v) postCpy.searchParams.append(k, v);
} }
console.debug(postCpy.searchParams.toString()) console.debug(postCpy.searchParams.toString());
console.debug({postCpy}) console.debug({ postCpy });
return postCpy.href.toString().replaceAll("%2B", '+') return postCpy.href.toString().replaceAll("%2B", "+");
} }
Deno.test("Test Request Parser", () => { Deno.test("Test Request Parser", () => {
assert(requestParser("[limit: 12,tags:bro+likes+bread]"), '{ "limit" => "12", "tags" => "bro+likes+bread" }') assert(
}) requestParser("[limit: 12,tags:bro+likes+bread]"),
'{ "limit" => "12", "tags" => "bro+likes+bread" }',
);
});
Deno.test("Test URL Search Parameters", () => { Deno.test("Test URL Search Parameters", () => {
console.debug(generateRequestURL("[limit:3]")) console.debug(generateRequestURL("[limit:3]"));
}) });
Deno.test("Test Drop", async() => { Deno.test("Test Drop", async () => {
console.debug(await drop()) console.debug(await drop());
}) });
Deno.test("Test Request Workder", async() => { Deno.test("Test Request Workder", async () => {
console.debug(await requestWorker("[limit: 12,tags:sfw]")) console.debug(await requestWorker("[limit: 12,tags:sfw]"));
}) });
Deno.test("Test Request Workder 2", async() => { Deno.test("Test Request Workder 2", async () => {
console.debug(await requestWorker("[limit: 5,tags: AI+catgirl]")) console.debug(await requestWorker("[limit: 5,tags: AI+catgirl]"));
}) });