Browse Source

Generate daily and weekly challenge, add checking to avoid generating multiple challenges

Marcin Jaborski 3 years ago
parent
commit
b3278f78f0

+ 60 - 0
serverless_functions/api/generate-challenge.ts

@@ -0,0 +1,60 @@
+import {VercelRequest, VercelResponse} from '@vercel/node';
+import {initializeApp, cert} from 'firebase-admin/app';
+import {getFirestore} from 'firebase-admin/firestore';
+import {firestore} from "firebase-admin";
+import Timestamp = firestore.Timestamp;
+
+
+export default async function generateChallenge(req: VercelRequest, res: VercelResponse) {
+    const type = req.query.type;
+    const serviceAccountStringified = Buffer.from(process.env.FIREBASE_SERVICE_ACCOUNT!, 'base64').toString('ascii');
+    const serviceAccount = JSON.parse(serviceAccountStringified);
+    initializeApp({
+        credential: cert(serviceAccount)
+    });
+
+    const firestore = getFirestore();
+    const challengeRef = type === 'daily' ? firestore.collection('DailyChallenges') :
+        firestore.collection('WeeklyChallenges');
+
+    if (type === 'daily') {
+        // @ts-ignore
+        const yesterday = new Date(new Date() - 1000 * 3600 * 22);
+
+        const todayChallenge = await challengeRef.where('date', '>', yesterday).get();
+
+        if (!todayChallenge.empty) {
+            res.json({
+                message: `challenge for ${new Date()} is already generated`,
+            })
+        }
+    } else if (type === 'weekly') {
+        // @ts-ignore
+        const weekAgo = new Date(new Date() - 1000 * 3600 * 24 * 7 - 3600);
+
+        const thisWeekChallenge = await challengeRef.where('date', '>', weekAgo).get();
+
+        if (!thisWeekChallenge.empty) {
+            res.json({
+                message: 'challenge for this week already exists',
+                date: new Date(),
+            });
+        }
+    }
+
+    const exercisesSnapshot = await firestore.collection('Exercises').get();
+    const exercises: FirebaseFirestore.DocumentData[] = [];
+    exercisesSnapshot.forEach((exercise) => {
+        exercises.push(firestore.collection('Exercises').doc(exercise.id));
+    });
+    const shuffled = exercises.sort(() => 0.5 - Math.random());
+    const selected = shuffled.slice(0, 3);
+    const bonus = exercises[Math.floor(Math.random() * exercises.length)];
+
+    const firestoreRes = await challengeRef.add({
+        date: Timestamp.fromDate(new Date()),
+        list_exercises: selected,
+        bonus_exercise: bonus,
+    });
+    res.json(firestoreRes);
+}

+ 0 - 32
serverless_functions/api/generate-daily.ts

@@ -1,32 +0,0 @@
-import {VercelRequest, VercelResponse} from '@vercel/node';
-import {initializeApp, cert} from 'firebase-admin/app';
-import {getFirestore} from 'firebase-admin/firestore';
-import {firestore} from "firebase-admin";
-import Timestamp = firestore.Timestamp;
-
-
-export default async function generateDaily(req: VercelRequest, res: VercelResponse) {
-    const serviceAccount = require('./serviceAccountKey.json');
-    initializeApp({
-        credential: cert(serviceAccount)
-    })
-
-    const firestore = getFirestore();
-
-    const exercisesSnapshot = await firestore.collection('Exercises').get();
-    const exercises: FirebaseFirestore.DocumentData[] = [];
-    exercisesSnapshot.forEach((exercise) => {
-        exercises.push(firestore.collection('Exercises').doc(exercise.id));
-    });
-    const shuffled = exercises.sort(() => 0.5 - Math.random());
-    const selected = shuffled.slice(0, 3);
-    const bonus = exercises[Math.floor(Math.random() * exercises.length)];
-
-    const dailyChallengesRef = firestore.collection('DailyChallenges');
-    const firestoreRes = await dailyChallengesRef.add({
-        date: Timestamp.fromDate(new Date()),
-        list_exercises: selected,
-        bonus_exercise: bonus,
-    })
-    res.json(firestoreRes);
-}