|
@@ -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);
|
|
|
|
|
+}
|