Fix rank query syntax and parameterize score SQL
This commit is contained in:
@@ -17,22 +17,23 @@ class ScoreManager{
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createScore(newScoreJson){
|
async createScore(newScoreJson){
|
||||||
const sql = `INSERT INTO scores (user1, user2, score) VALUES (
|
const sql = "INSERT INTO scores (user1, user2, score) VALUES (?, ?, ?)";
|
||||||
${newScoreJson.user1}, ${newScoreJson.user2}, ${newScoreJson.score})`;
|
|
||||||
|
const insertResult = await this.connection
|
||||||
const insertResult = await this.connection.promise().query(sql);
|
.promise()
|
||||||
|
.query(sql, [newScoreJson.user1, newScoreJson.user2, newScoreJson.score]);
|
||||||
const insertId = insertResult[0].insertId;
|
const insertId = insertResult[0].insertId;
|
||||||
|
|
||||||
const selectSql = `SELECT * FROM scores WHERE id = ${insertId}`;
|
const selectSql = "SELECT * FROM scores WHERE id = ?";
|
||||||
const selectResult = await this.connection.promise().query(selectSql);
|
const selectResult = await this.connection.promise().query(selectSql, [insertId]);
|
||||||
|
|
||||||
const rank = await this.getRankById(insertId);
|
const rank = await this.getRankById(insertId);
|
||||||
|
|
||||||
return new Score(selectResult[0][0], rank);
|
return new Score(selectResult[0][0], rank);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getScoreById(id){
|
async getScoreById(id){
|
||||||
const response = await this.connection.promise().query(`SELECT * FROM scores WHERE id = ${id}`);
|
const response = await this.connection.promise().query("SELECT * FROM scores WHERE id = ?", [id]);
|
||||||
|
|
||||||
const rank = await this.getRankById(id);
|
const rank = await this.getRankById(id);
|
||||||
|
|
||||||
@@ -63,12 +64,14 @@ class ScoreManager{
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getRankById(id){
|
async getRankById(id){
|
||||||
const rankSql = `SELECT COUNT(*) + 1 AS rank FROM scores WHERE score > (SELECT score FROM scores WHERE id = ${id})`;
|
const rankSql =
|
||||||
const rankResult = await this.connection.promise().query(rankSql);
|
"SELECT COUNT(*) + 1 AS rank_position FROM scores WHERE score > (SELECT score FROM scores WHERE id = ?)";
|
||||||
const rank = rankResult[0][0].rank;
|
const rankResult = await this.connection.promise().query(rankSql, [id]);
|
||||||
|
|
||||||
|
const rank = rankResult[0][0]?.rank_position ?? null;
|
||||||
|
|
||||||
return rank;
|
return rank;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = ScoreManager;
|
module.exports = ScoreManager;
|
||||||
|
|||||||
Reference in New Issue
Block a user