From 96ea7417433552902c43be044be9348c5a6a4b12 Mon Sep 17 00:00:00 2001 From: Clumsy-Coder <19594044+Clumsy-Coder@users.noreply.github.com> Date: Tue, 26 Dec 2023 19:33:15 -0700 Subject: [PATCH] feat(api): add endpoint `/api/problems` ## what - add endpoint `/api/problems` ## how ## why - this will fetch all problems from upstream ## where - ./src/app/api/problems/route.ts ## usage --- src/app/api/problems/route.ts | 73 +++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/app/api/problems/route.ts diff --git a/src/app/api/problems/route.ts b/src/app/api/problems/route.ts new file mode 100644 index 0000000..cb9b73b --- /dev/null +++ b/src/app/api/problems/route.ts @@ -0,0 +1,73 @@ +import { uhuntAllProblemsUrl } from "@/utils/constants"; + +/** + * an array of keys that will be used to convert an array of arrays into array of objects + * + * check `https://uhunt.onlinejudge.org/api/p` to view raw data. (each problem stats are presented as an array element) + */ +const arrKey = [ + "pid", + "num", + "title", + "dacu", + "mrun", + "mmem", + "nover", + "sube", + "noj", + "inq", + "ce", + "rf", + "re", + "ole", + "tle", + "mle", + "wa", + "pe", + "ac", + "rtl", + "status", + "rej", +]; + +export const GET = async (_request: Request) => { + const url = uhuntAllProblemsUrl(); + + const response = await fetch(url); + // data returned is an array of array + // ex: + // [ + // [ + // 36, + // 100, + // "The 3n + 1 problem", + // ... + // ], + // ] + const data = await response.json(); + + // convert an array of array into array of problems + // ex: + // convert + // [ + // [1,2,3,...], + // [1,2,3,...], + // ] + // + // into + // [ + // {pid: 1, num: 2, title: 3, ...}, + // {pid: 1, num: 2, title: 3, ...}, + // ] + const converted = data.map((problem: number[]) => { + const initialValue = {}; + return problem.reduce((obj, item, index: number) => { + return { + ...obj, + [arrKey[index]]: item, + }; + }, initialValue); + }); + + return Response.json(converted); +};