Skip to content

Commit

Permalink
Merge pull request #19 from Geen-19/saveRound
Browse files Browse the repository at this point in the history
#9 issue worked on to add saveRound.ts and relates schemas to work with
  • Loading branch information
webdevcody authored Oct 15, 2024
2 parents d02e5b0 + 3bc3c12 commit fda0f68
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
2 changes: 2 additions & 0 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type * as auth from "../auth.js";
import type * as games from "../games.js";
import type * as http from "../http.js";
import type * as messages from "../messages.js";
import type * as saveRound from "../saveRound.js";
import type * as openai from "../openai.js";
import type * as users from "../users.js";

Expand All @@ -35,6 +36,7 @@ declare const fullApi: ApiFromModules<{
games: typeof games;
http: typeof http;
messages: typeof messages;
saveRound: typeof saveRound;
openai: typeof openai;
users: typeof users;
}>;
Expand Down
62 changes: 62 additions & 0 deletions convex/saveRound.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// File: convex/saveRoundMutation.ts

import { mutation } from "./_generated/server";
import { v } from "convex/values";

export const saveRoundMutation = mutation({
args: {
gameId: v.id("games"),
roundId: v.string(),
level: v.number(),
isWin: v.boolean(),
reasoning: v.string(),
},
handler: async (ctx, args) => {
const { gameId, roundId, level, isWin, reasoning } = args;

// 1. Save the round result
const resultId = await ctx.db.insert("results", {
gameId,
roundId,
level,
isWin,
reasoning,
});

// 2. If the game was won, update the score
let updatedScore = null;
if (isWin) {
// Find the game to get the modelId
const game = await ctx.db.get(gameId);

if (game) {
// Get the current score or initialize it
const currentScore = await ctx.db
.query("scores")
.filter((q) => q.eq(q.field("modelId"), game.modelId))
.first();

if (currentScore) {
// Update existing score
updatedScore = await ctx.db.patch(currentScore._id, {
score: currentScore.score + 1,
});
} else {
// Create new score entry
updatedScore = await ctx.db.insert("scores", {
modelId: game.modelId,
score: 1,
...args,
});
}
}
}

return {
success: true,
message: "Round result saved successfully",
resultId,
updatedScore,
};
},
});
8 changes: 8 additions & 0 deletions convex/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,12 @@ export default defineSchema({
score: v.number(),
level: v.number(),
}).index("by_game_and_level", ["gameId", "level"]),
results: defineTable({
gameId: v.id("games"),
roundId: v.string(),
level: v.number(),
isWin: v.boolean(),
reasoning: v.string(),
}),

});

0 comments on commit fda0f68

Please sign in to comment.