DylanDevD
Convex Community10mo ago
14 replies
DylanDev

Patching two values in a document causes functions to be re triggered

I have a function called checkGuess which checks the user's guess and returns data relating to their guess. Additionally, it updates a the "level" document in my levels table by adding 1 to times played and adding 1 to correctguesses if they got it right. However, when I add this patch code, it is triggering my original function again that pulls down 5 random levels and is causing the game to loop indefinitely?

export const checkGuess = mutation({
  args: { levelId: v.id("levels"), selectedImageId: v.id("images") },
  handler: async(ctx, args) => {
    const level = await ctx.db.get(args.levelId);

    if(!level) {
      throw new Error("No levels exist");
    }

    let AIGeneratedImageId;
    let AIGeneratedImagePrompt;

    for (const imageId of level.images) {
      const image = await ctx.db.get(imageId);
      if (image && image.isAIGenerated) {
        AIGeneratedImageId = image;
        AIGeneratedImagePrompt = image.AIGeneratedPrompt;
        break;
      }
    }

    if(!AIGeneratedImageId) {
      throw new Error("No AI-generated image found.");
    }

    let score = 0;
    let correct = false;

    if(args.selectedImageId === AIGeneratedImageId._id) {
      score = 50;
      correct = true;
    } else {
      score = 0;
      correct = false;
    }

    const totalPlays = level.totalPlays + 1n;
    const correctAnswers = correct ? (level.correctAnswers + 1n) : level.correctAnswers;
    const globalAccuracy = totalPlays > 0n ? ((correctAnswers * 100n) / totalPlays) : 0n;

    await ctx.db.patch(level._id, {
      totalPlays,
      correctAnswers
    });

    return {
      correct,
      correctImageId: AIGeneratedImageId._id,
      groupName: level.groupName,
      classification: level.classification,
      hints: level.hints,
      aiImagePrompt: AIGeneratedImagePrompt,
      score,
      globalAccuracy: globalAccuracy
    };
  }
});
Was this page helpful?