| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- 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);
- }
|