/api/evaluate refactor
This commit is contained in:
@@ -1,10 +1,9 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {getFirestore, doc, getDoc, setDoc} from "firebase/firestore";
|
||||
import client from "@/lib/mongodb";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import axios, {AxiosResponse} from "axios";
|
||||
import {app} from "@/firebase";
|
||||
import {Stat} from "@/interfaces/user";
|
||||
import {writingReverseMarking} from "@/utils/score";
|
||||
|
||||
@@ -19,7 +18,8 @@ function delay(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
const db = getFirestore(app);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
@@ -37,8 +37,8 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const correspondingStat = await getCorrespondingStat(req.body.id, 1);
|
||||
|
||||
const solutions = correspondingStat.solutions.map((x) => ({...x, evaluation: backendRequest.data}));
|
||||
await setDoc(
|
||||
doc(db, "stats", (req.body as Body).id),
|
||||
await db.collection("stats").updateOne(
|
||||
{ id: (req.body as Body).id},
|
||||
{
|
||||
solutions,
|
||||
score: {
|
||||
@@ -48,16 +48,17 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
},
|
||||
isDisabled: false,
|
||||
},
|
||||
{merge: true},
|
||||
{upsert: true},
|
||||
);
|
||||
console.log("🌱 - Updated the DB");
|
||||
}
|
||||
|
||||
async function getCorrespondingStat(id: string, index: number): Promise<Stat> {
|
||||
console.log(`🌱 - Try number ${index} - ${id}`);
|
||||
const correspondingStat = await getDoc(doc(db, "stats", id));
|
||||
const correspondingStat = await db.collection("stats").findOne<Stat>({ id: id});
|
||||
|
||||
if (correspondingStat.exists()) return {...correspondingStat.data(), id} as Stat;
|
||||
if (correspondingStat) return correspondingStat;
|
||||
|
||||
await delay(3 * 10000);
|
||||
return getCorrespondingStat(id, index + 1);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user