Post-API implemented, testing required.

This commit is contained in:
fzzin
2025-04-10 10:57:13 +02:00
parent 79750ed5cc
commit aa834bda66

View File

@@ -1,5 +1,7 @@
import { requestJSON } from "@root/structures/apiRequest.ts";
import { DiscordEmbed } from "npm:discordeno@18.0.1";
type PostResponse = {
posts: {
id: number;
tags: string;
created_at: string;
@@ -42,5 +44,72 @@ type PostResponse = {
is_note_locked: boolean;
last_noted_at: string;
last_commented_at: string;
}[];
};
}[];
const postSearchkeys = ["limit", "page", "tags"];
function parsePostListArgs(url: URL, args: string) {
const urlCopy: URL = copyObject(url);
const argarr = args.replaceAll(/(\[|\|\ ])/g, "").split(",");
for (const arg of argarr) {
const [k, v] = arg.split(":");
if (k === undefined || v === undefined) {
throw Error(
`undefined key or value in ${parsePostListArgs.name}, got k:${k}, v:${v}`,
);
}
if (k in postSearchkeys) {
urlCopy.searchParams.append(k, v);
} else {
throw Error(
`unknown parameter was given in ${parsePostListArgs.name}, got k:${k}, v:${v}`,
);
}
}
return urlCopy;
}
async function returnDiscordEmbeds(
url: URL,
): Promise<DiscordEmbed[]> {
const response: PostResponse = await requestJSON<PostResponse>(
url.toString(),
);
const embeds: DiscordEmbed[] = [];
for (const post of response) {
embeds.push(
{
url: post.source,
title: post.id.toString(),
author: {
name: post.author,
},
image: {
url: post.file_url,
width: post.width,
height: post.height,
},
},
);
}
return embeds;
}
function copyObject<T>(obj: T) {
return JSON.parse(JSON.stringify(obj));
}
/**
* Post-Request Handler Function, that returns DiscordEmbeds.
* @param url URL Object
* @param search Search string formatted like the following: [tags: something, page: 1, limit: 666], some parameters can miss.
*/
export async function handlePostRequest(url: URL, search?: string): Promise<DiscordEmbed[]> {
const urlCopy = copyObject(url);
//parse
if (search) {
return await returnDiscordEmbeds(parsePostListArgs(urlCopy, search));
} else {
return await returnDiscordEmbeds(urlCopy);
}
}