Refactored /api/paypal, /api/permissions, /api/reset /api/sessions, /api/stats
This commit is contained in:
@@ -6,29 +6,25 @@ import {sessionOptions} from "@/lib/session";
|
||||
import {calculateBandScore} from "@/utils/score";
|
||||
import {groupByModule, groupBySession} from "@/utils/stats";
|
||||
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||
import {getAuth} from "firebase/auth";
|
||||
import {collection, doc, getDoc, getDocs, getFirestore, query, updateDoc, where} from "firebase/firestore";
|
||||
import client from "@/lib/mongodb";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {groupBy} from "lodash";
|
||||
import {NextApiRequest, NextApiResponse} from "next";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(update, sessionOptions);
|
||||
|
||||
async function update(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.session.user) {
|
||||
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
||||
if (!docUser.exists()) {
|
||||
const docUser = await db.collection("users").findOne({ id: req.session.user.id });
|
||||
|
||||
if (!docUser) {
|
||||
res.status(401).json(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const q = query(collection(db, "stats"), where("user", "==", req.session.user.id));
|
||||
const stats = (await getDocs(q)).docs.map((doc) => ({
|
||||
...(doc.data() as Stat),
|
||||
id: doc.id,
|
||||
})) as Stat[];
|
||||
const stats = await db.collection("stats").find<Stat>({ user: req.session.user.id }).toArray();
|
||||
|
||||
const groupedStats = groupBySession(stats);
|
||||
const sessionLevels: {[key in Module]: {correct: number; total: number}}[] = Object.keys(groupedStats).map((key) => {
|
||||
@@ -102,9 +98,11 @@ async function update(req: NextApiRequest, res: NextApiResponse) {
|
||||
level: calculateBandScore(levelLevel.correct, levelLevel.total, "level", req.session.user.focus),
|
||||
};
|
||||
|
||||
const userDoc = doc(db, "users", req.session.user.id);
|
||||
await updateDoc(userDoc, {levels});
|
||||
|
||||
await db.collection("users").updateOne(
|
||||
{ id: req.session.user.id},
|
||||
{ $set: {levels} }
|
||||
);
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
} else {
|
||||
res.status(401).json(undefined);
|
||||
|
||||
Reference in New Issue
Block a user