Skip to content

Commit 2d4f2be

Browse files
committed
Enforce Strict (userId, roomId) Uniqueness in HistoryEntries
1 parent cf0f017 commit 2d4f2be

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

backend/question-service/controllers/historyController.ts

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export const getUserHistoryEntries = async (req: any, res: Response) => {
2727
title: entry.question.title,
2828
difficulty: entry.question.difficulty,
2929
topics: entry.question.categories.map((cat: any) => cat.name),
30-
attemptCodes: entry.attemptCodes,
30+
attemptCodes: entry.attemptCodes.filter((attemptCode) => attemptCode && attemptCode !== ""),
3131
};
3232
});
3333
res.status(200).json(historyViewModels);
@@ -59,19 +59,23 @@ export const createOrUpdateUserHistoryEntry = async (req: any, res: Response) =>
5959

6060
return res.status(200).json(updatedEntry);
6161
} else if (!existingEntry) {
62-
const newHistoryEntry = new historyEntryModel({
63-
userId,
64-
question: questionId,
65-
roomId,
66-
attemptStartedAt,
67-
attemptCompletedAt,
68-
collaboratorId,
69-
attemptCodes: isInitial ? [attemptCode] : [],
70-
});
71-
72-
const savedEntry = await newHistoryEntry.save();
73-
74-
return res.status(201).json(savedEntry);
62+
try {
63+
const newHistoryEntry = new historyEntryModel({
64+
userId,
65+
question: questionId,
66+
roomId,
67+
attemptStartedAt,
68+
attemptCompletedAt,
69+
collaboratorId,
70+
attemptCodes: isInitial ? [attemptCode] : [],
71+
});
72+
73+
const savedEntry = await newHistoryEntry.save();
74+
75+
return res.status(201).json(savedEntry);
76+
} catch {
77+
return res.status(200).json("Attempt already exists.");
78+
}
7579
} else {
7680
return res.status(200).json("Attempt already exists.");
7781
// To reach here, this must be initial creation and there's an existing entry. No need to create new attempt.

backend/question-service/models/HistoryEntry.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,7 @@ const historyEntrySchema: Schema = new Schema<HistoryEntry>({
2222
attemptCodes: [{ type: String }],
2323
});
2424

25+
historyEntrySchema.index({ userId: 1, roomId: 1 }, { unique: true });
26+
2527
const historyEntryModel = mongoose.model<HistoryEntry>('historyEntry', historyEntrySchema);
2628
export default historyEntryModel;

0 commit comments

Comments
 (0)