Skip to content

Commit

Permalink
Made tests for the new endpoint and removed some unnecessary code
Browse files Browse the repository at this point in the history
  • Loading branch information
IyanRobles committed Mar 14, 2024
1 parent 7131405 commit 5d75d84
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 19 deletions.
31 changes: 12 additions & 19 deletions users/userservice/src/controllers/history-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,16 @@ const getLeaderboard = async (req: Request, res: Response) => {
let size = DEFAULT_LEADERBOARD_SIZE; // Default size if no parameter is received
if (sizeParam) {
size = parseInt(sizeParam as string, 10);
if (size <= 0) {
throw new Error('The size must be a positive value.');
}
}

const users = await User.find({})
const leaderboard = await User.find({})
.sort({ 'history.points': -1 }) // Sort in descending order of points
.limit(size) // Only take the first (size) users
.select('username history'); // Select only username and history (no password, date, etc.)

const leaderboard = users.map(user => user.toJSON());

res.json({
status: 'success',
data: {
Expand All @@ -71,17 +72,13 @@ const updateHistory = async (req: Request, res: Response) => {
try {
const user = req.user;

if (!user) {
throw new Error('Unknown error. User does not appear.');
}

validateRequiredFields(req, ['history']);
validateHistoryBody(req, user);
validateHistoryBody(req, user!);

user.history = { ...user.history, ...req.body.history };
await user.save();
user!.history = { ...user!.history, ...req.body.history };
await user!.save();

res.json({ status: 'success', data: user.history });
res.json({ status: 'success', data: user!.history });
} catch (error) {
res.status(400).json({
status: 'fail',
Expand All @@ -96,20 +93,16 @@ const incrementHistory = async (req: Request, res: Response) => {
try {
const user = req.user;

if (!user) {
throw new Error('Unknown error. User does not appear.');
}

validateRequiredFields(req, ['history']);
validateHistoryBody(req, user);
validateHistoryBody(req, user!);

Object.keys(req.body.history).forEach(key => {
(user.history as any)[key] += req.body.history[key];
(user!.history as any)[key] += req.body.history[key];
});

await user.save();
await user!.save();

res.json({ status: 'success', data: user.history });
res.json({ status: 'success', data: user!.history });
} catch (error) {
res.status(400).json({
status: 'fail',
Expand Down
69 changes: 69 additions & 0 deletions users/userservice/test/user-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,73 @@ describe('User Service', () => {
expect(getResponse.statusCode).toBe(200);
expect(JSON.stringify(getResponse.body.data.history)).toMatch(JSON.stringify(expectedHistory.history));
});

// GET /history/leaderboard with size param
it('should obtain n users with the highest scores', async () => {
const newUserData = {
username: 'highestscoreuser',
password: 'testpassword',
};
// Add a new user to test leaderboard
await request(app).post('/adduser').send(newUserData);

// The new user will have 100000 points
const increment = {
history: {
points: 100000,
},
};
const newUser = await User.findOne({ username:'highestscoreuser' });
// Generates a temporary token for this test
const testToken2 = jwt.sign({ userId: newUser!._id }, 'your-secret-key', {
expiresIn: '2m',
});

await request(app)
.post('/history/increment')
.send(increment)
.set('Authorization', `Bearer ${testToken2}`);

// The old user will have 99999 points
const newHistory = {
history: {
points: 99999,
},
};
await request(app)
.post('/history')
.send(newHistory)
.set('Authorization', `Bearer ${testToken}`);

const response = await request(app)
.get('/history/leaderboard?size=2');

expect(response.statusCode).toBe(200);
expect(response.body.data.leaderboard.length).toBe(2);
expect(response.body.data.leaderboard[0].username).toEqual('highestscoreuser');
expect(response.body.data.leaderboard[0].history.points).toBe(100000);
expect(response.body.data.leaderboard[1].username).toEqual('testuser');
expect(response.body.data.leaderboard[1].history.points).toBe(99999);
});

// GET /history/leaderboard without param
it('should obtain users with the highest scores', async () => {
// If a request is made without the parameter it will return an amount of users
// specified by a constant in the controller (DEFAULT_LEADERBOARD_SIZE)
const response = await request(app)
.get('/history/leaderboard');

expect(response.statusCode).toBe(200);
expect(response.body.data.leaderboard).not.toBeUndefined();
});

// GET /history/leaderboard negative param
it('should obtain users with the highest scores', async () => {
// If a request is made with a negative size, it will throw an exception
const response = await request(app)
.get('/history/leaderboard?size=-1');

expect(response.statusCode).toBe(400);
expect(response.body.data.leaderboard).toBeUndefined();
});
});

0 comments on commit 5d75d84

Please sign in to comment.