Merge pull request #2 from Degulleo/DO-17-서버-리더보드-조화-기능-추가

리더보드 조회 기능 추가
This commit is contained in:
Fiore 2025-03-12 17:40:32 +09:00 committed by GitHub
commit 2b16048333
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 41 additions and 13 deletions

View File

@ -1,4 +1,5 @@
var express = require('express');
const {ObjectId} = require("mongodb");
var router = express.Router();
// 랭킹 조회
@ -11,20 +12,44 @@ router.get("/", async function (req, res, next) {
var database = req.app.get('database');
var users = database.collection('users');
var allUsers = await users
.find({ }, { projection: { username:1, nickname: 1, score: 1 } })
.sort({ score: -1 }) // 점수가 높은 순으로 정렬
// 요청 유저 정보 확인
var userId = req.session.userId;
const user = await users.findOne({_id: ObjectId.createFromHexString(userId) });
var userRating = user.rating;
// 동일한 rating을 가진 유저들만 필터링
var sameRatingUsers = await users
.find({ rating: userRating }, { projection: { nickname: 1, score: 1, win: 1, lose: 1, profileImageIndex:1, rating: 1 } })
.toArray();
var result = allUsers.map((user) => (
{
username: user.username,
// 승률 계산 및 정렬
var result = sameRatingUsers.map((user) => {
const totalGames = (user.win || 0) + (user.lose || 0);
const winRate = totalGames > 0 ? ((user.win || 0) / totalGames * 100) : 0;
return {
nickname: user.nickname,
score: user.score || 0,
}
))
win: user.win || 0,
lose: user.lose || 0,
winRate: parseFloat(winRate.toFixed(2)), // 소수점 2자리까지 표시
totalGames: totalGames,
imageindex: user.profileImageIndex,
};
})
.sort((a, b) => {
// 승률이 같은 경우 총 게임 수가 많은 사람이 위에 오도록 정렬
if (b.winRate === a.winRate) {
return b.totalGames - a.totalGames;
}
return b.winRate - a.winRate; // 승률 내림차순 정렬
});
res.json({ leaderboardDatas : result ?? [] });
res.json({
rating: userRating,
leaderboardDatas : result ?? []
});
} catch(err) {
console.error(err);
res.status(500).send("서버 오류가 발생했습니다.");

View File

@ -5,7 +5,7 @@ const {ObjectId} = require("mongodb");
var saltRounds = 10;
var ResponseType = {
INVALID_USERNAME: 0,
INVALID_EMAIL: 0,
INVALID_PASSWORD: 1,
SUCCESS: 2
}
@ -37,7 +37,7 @@ router.post('/signup', async function (req, res, next) {
var database = req.app.get('database');
var users = database.collection('users');
const existingUser = await users.findOne({username: email})
const existingUser = await users.findOne({email: email})
if(existingUser){
return res.status(409).send("이미 존재하는 사용자입니다.")
}
@ -55,7 +55,8 @@ router.post('/signup', async function (req, res, next) {
rating: 18,
score:0,
win:0,
lose:0
lose:0,
coin: 1000
});
res.status(201).send("사용자가 성공적으로 생성되었습니다.");
@ -90,18 +91,20 @@ router.post("/signin", async function (req, res, next) {
req.session.profileImageIndex = existingUser.profileImageIndex || 0;
req.session.rating = existingUser.rating;
req.session.score = existingUser.score;
req.session.coin = existingUser.coin;
res.json({
result: ResponseType.SUCCESS,
imageindex: existingUser.imageindex,
rating: existingUser.rating,
score: existingUser.score,
coin: existingUser.coin,
});
} else {
res.json({result : ResponseType.INVALID_PASSWORD});
}
} else {
res.json({result : ResponseType.INVALID_USERNAME});
res.json({result : ResponseType.INVALID_EMAIL});
}
}catch (err){
console.log("로그인 중 오류 발생 : ", err);