generate-challenge.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {VercelRequest, VercelResponse} from '@vercel/node';
  2. import {initializeApp, cert} from 'firebase-admin/app';
  3. import {getFirestore} from 'firebase-admin/firestore';
  4. import {firestore} from "firebase-admin";
  5. import Timestamp = firestore.Timestamp;
  6. export default async function generateChallenge(req: VercelRequest, res: VercelResponse) {
  7. const type = req.query.type;
  8. const serviceAccountStringified = Buffer.from(process.env.FIREBASE_SERVICE_ACCOUNT!, 'base64').toString('ascii');
  9. const serviceAccount = JSON.parse(serviceAccountStringified);
  10. initializeApp({
  11. credential: cert(serviceAccount)
  12. });
  13. const firestore = getFirestore();
  14. const challengeRef = type === 'daily' ? firestore.collection('DailyChallenges') :
  15. firestore.collection('WeeklyChallenges');
  16. if (type === 'daily') {
  17. // @ts-ignore
  18. const yesterday = new Date(new Date() - 1000 * 3600 * 22);
  19. const todayChallenge = await challengeRef.where('date', '>', yesterday).get();
  20. if (!todayChallenge.empty) {
  21. res.json({
  22. message: `challenge for ${new Date()} is already generated`,
  23. })
  24. }
  25. } else if (type === 'weekly') {
  26. // @ts-ignore
  27. const weekAgo = new Date(new Date() - 1000 * 3600 * 24 * 7 - 3600);
  28. const thisWeekChallenge = await challengeRef.where('date', '>', weekAgo).get();
  29. if (!thisWeekChallenge.empty) {
  30. res.json({
  31. message: 'challenge for this week already exists',
  32. date: new Date(),
  33. });
  34. }
  35. }
  36. const exercisesSnapshot = await firestore.collection('Exercises').get();
  37. const exercises: FirebaseFirestore.DocumentData[] = [];
  38. exercisesSnapshot.forEach((exercise) => {
  39. exercises.push(firestore.collection('Exercises').doc(exercise.id));
  40. });
  41. const shuffled = exercises.sort(() => 0.5 - Math.random());
  42. const selected = shuffled.slice(0, 3);
  43. const bonus = exercises[Math.floor(Math.random() * exercises.length)];
  44. const firestoreRes = await challengeRef.add({
  45. date: Timestamp.fromDate(new Date()),
  46. list_exercises: selected,
  47. bonus_exercise: bonus,
  48. });
  49. res.json(firestoreRes);
  50. }