Skip to content

implement reset last submission route #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/controllers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,35 @@ const userController = {
}
},

resetLastSubmission: async (req: Request, res: Response) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(statusCodes.MISSING_PARAMS).json(
errors.formatWith(errorMessage).array()[0]
);
} else {
try {
const { userId } = req.params;
await userDBInteractions.resetLastSubmission(userId);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"resetLastSubmission" should be called after we make sure that the user exists

const user: IUserModel = await userDBInteractions.find(userId);
if (!user)
res.status(statusCodes.NOT_FOUND).json({
status: statusCodes.NOT_FOUND,
message: "User not found"
});
else {
const updatedUser: IUserModel = await userDBInteractions.update(
userId,
user
);
Comment on lines +248 to +251
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you updating here if the "user" variable is unchanged? I suggest you either call the new resetLastSubmission DB interaction here or you manually update the "user" by setting the lastSubmission to {} then calling the update DB interaction (I prefer the second option since it allows us to reuse an premade DB interaction instead of making a new one).

res.status(statusCodes.SUCCESS).json(updatedUser);
}
} catch (error) {
res.status(statusCodes.SERVER_ERROR).json(error);
}
}
},

resetLastSubmissions: async (req: Request, res: Response) => {
try {
await userDBInteractions.resetLastSubmissions();
Expand Down
9 changes: 9 additions & 0 deletions src/database/interactions/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ export const userDBInteractions = {
return User.findByIdAndDelete(userId).exec();
},

resetLastSubmission: (userId: string): Promise<IUserModel> => {
return User.updateOne(
{ _id: userId },
{
$set: { "platformData.codeforces.lastSubmission": {} }
}
).exec();
},

resetLastSubmissions: (): Promise<IUserModel[]> => {
return User.updateMany(
{},
Expand Down
6 changes: 6 additions & 0 deletions src/routes/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ userRouter.put(
userController.update
);

userRouter.patch(
"/:userId/resetLastSubmission",
userValidator("PATCH /users/:userId/resetLastSubmission"),
userController.resetLastSubmission
);

userRouter.patch("/resetLastSubmissions", userController.resetLastSubmissions);

userRouter.patch(
Expand Down
3 changes: 3 additions & 0 deletions src/validators/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ export function userValidator(method: string): ValidationChain[] {
).custom(validPassword)
];
}
case "PATCH /users/:userId/resetLastSubmission": {
return [param("userId", "Invalid ':userId'").isMongoId()];
}
case "PATCH /users/:userId/problems": {
return [
param("userId", "Invalid ':userId'").isMongoId(),
Expand Down
71 changes: 70 additions & 1 deletion tests/unit/controllers/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ const testUser: IUserModel = new User({
platformData: {
codeforces: {
username: "test",
email: "[email protected]"
email: "[email protected]",
lastSubmission: {
problemId: "6e0d9ca7d2e93b127f941e1566b6253aa48dab48",
isComplete: "true",
status: "OK"
}
}
},
_id: "5ed7505cf09e10001e5084b7"
Expand Down Expand Up @@ -110,6 +115,70 @@ describe("Users controller tests", () => {
});

describe("ResetLastSubmission", () => {
let req;
beforeEach(() => {
req = mockReq({
params: {
userId: testUser._id
}
});
});
it("status 200: resets last submission", async () => {
const updatedUser = JSON.parse(JSON.stringify(testUser));
updatedUser.platformData.codeforces.lastSubmission = {};
stubs.userValidator.validationResult.returns(
emptyValidationError()
);
stubs.userDB.find.returns(testUser);
stubs.userDB.update.returns(updatedUser);
await userController.resetLastSubmission(req, mockRes);
sinon.assert.calledOnce(stubs.userDB.resetLastSubmission);
sinon.assert.calledOnce(stubs.userDB.find);
sinon.assert.calledOnce(stubs.userDB.update);
sinon.assert.calledOnce(stubs.userValidator.validationResult);
sinon.assert.calledWith(mockRes.status, statusCodes.SUCCESS);
sinon.assert.calledWith(mockRes.json, updatedUser);
});

it("status 404: returns an appropriate response if user with given id doesn't exist", async () => {
stubs.userValidator.validationResult.returns(
emptyValidationError()
);
await userController.resetLastSubmission(req, mockRes);
sinon.assert.calledOnce(stubs.userValidator.validationResult);
sinon.assert.calledWith(mockRes.status, statusCodes.NOT_FOUND);
sinon.assert.calledWith(mockRes.json, {
status: statusCodes.NOT_FOUND,
message: "User not found"
});
});

it("status 422: returns an appropriate response with validation error", async () => {
const errorMsg = {
status: statusCodes.MISSING_PARAMS,
message: "params[userId]: Invalid or missing ':userId'"
};
req.params.userId = "not ObjectId";
stubs.userValidator.validationResult.returns(
validationErrorWithMessage(errorMsg)
);
await userController.resetLastSubmission(req, mockRes);
sinon.assert.calledOnce(stubs.userValidator.validationResult);
sinon.assert.calledWith(mockRes.status, statusCodes.MISSING_PARAMS);
sinon.assert.calledWith(mockRes.json, errorMsg);
});

it("status 500: fails to reset last submission", async () => {
stubs.userValidator.validationResult.returns(
emptyValidationError()
);
stubs.userDB.resetLastSubmission.throws();
await userController.resetLastSubmission(req, mockRes);
sinon.assert.calledWith(mockRes.status, statusCodes.SERVER_ERROR);
});
});

describe("ResetLastSubmissions", () => {
it("status 200: resets last submissions", async () => {
await userController.resetLastSubmissions(mockReq, mockRes);
sinon.assert.calledOnce(stubs.userDB.resetLastSubmissions);
Expand Down
5 changes: 5 additions & 0 deletions tests/unit/stubs/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ export const userDBInteractionsStubs = () => {
findByUsername: sinon.stub(userDBInteractions, "findByUsername"),
update: sinon.stub(userDBInteractions, "update"),
delete: sinon.stub(userDBInteractions, "delete"),
resetLastSubmission: sinon.stub(
userDBInteractions,
"resetLastSubmission"
),
resetLastSubmissions: sinon.stub(
userDBInteractions,
"resetLastSubmissions"
Expand All @@ -25,6 +29,7 @@ export const userDBInteractionsStubs = () => {
this.findByUsername.restore();
this.update.restore();
this.delete.restore();
this.resetLastSubmission.restore();
this.resetLastSubmissions.restore();
}
};
Expand Down