From 5c65424a049ae37dde65f09a8afd051591832313 Mon Sep 17 00:00:00 2001 From: regalijan Date: Thu, 19 Oct 2023 16:51:14 -0400 Subject: [PATCH] Retrieve self-submitted reports endpoint --- functions/api/me/reports.ts | 49 +++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 functions/api/me/reports.ts diff --git a/functions/api/me/reports.ts b/functions/api/me/reports.ts new file mode 100644 index 0000000..95ab6a0 --- /dev/null +++ b/functions/api/me/reports.ts @@ -0,0 +1,49 @@ +import { jsonError, jsonResponse } from "../../common.js"; + +export async function onRequestGet(context: RequestContext) { + const { + results, + success, + }: { + results: { id: string }[]; + success: boolean; + } = await context.env.D1.prepare( + "SELECT id FROM reports WHERE user = ? ORDER BY created_at LIMIT 50;", + ) + .bind(context.data.current_user.id) + .all(); + + if (!success) return jsonError("Failed to retrieve reports", 500); + + const ids: string[] = []; + results.map((v) => ids.push(v.id)); + + const kvDataPromises = []; + + for (const id of ids) + kvDataPromises.push(context.env.DATA.get(`report_${id}`, { type: "json" })); + + let settledKvPromises; + + try { + settledKvPromises = (await Promise.all( + kvDataPromises, + )) as ReportCardProps[]; + } catch (e) { + console.log(e); + return jsonError("Failed to resolve reports", 500); + } + + return jsonResponse( + JSON.stringify( + settledKvPromises.map((r) => { + return { + created_at: r.created_at, + id: r.id, + open: r.open, + target_usernames: r.target_usernames, + }; + }), + ), + ); +}