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