Permalink
Browse files

Refactor database calls.

  • Loading branch information...
roncli committed May 11, 2018
1 parent 815cbef commit 82c584b37599f38e2feb911944dc81b9d1b0b0ed
Showing with 95 additions and 167 deletions.
  1. +0 −4 .eslintrc.json → .eslintrc
  2. +21 −29 commands.js
  3. +55 −64 database.js
  4. +1 −1 discord.js
  5. +14 −65 event.js
  6. +4 −4 package.json
@@ -1,13 +1,9 @@
{
"env": {
"es6": true,
"node": true
},
"parserOptions": {
"ecmaFeatures": {
"impliedStrict": true
},
"sourceType": "module",
"ecmaVersion": 6
},
@@ -277,8 +277,8 @@ class Commands {
return;
}
Db.query("SELECT Home FROM tblHome WHERE DiscordID = @discordId", {discordId: {type: Db.VARCHAR(50), value: user.id}}).then((data) => {
if (!data || !data.recordsets[0] || data.recordsets[0].length < 3) {
Db.getHomesForDiscordId(user.id).then((homes) => {
if (homes.length < 3) {
commands.service.queue(`Sorry, ${user}, but you have not yet set all 3 home maps. Please use the \`!home\` command to select 3 home maps, one at a time, for example, \`!home Logic x2\`.`, channel);
reject(new Error("Pilot has not yet set 3 home maps."));
return;
@@ -287,7 +287,7 @@ class Commands {
if (player) {
delete player.withdrawn;
} else {
Event.addPlayer(user.id, data.recordsets[0].map((m) => m.Home));
Event.addPlayer(user.id, homes);
}
Discord.addEventRole(user);
@@ -379,35 +379,27 @@ class Commands {
return;
}
Db.query("SELECT COUNT(Home) Homes FROM tblHome WHERE DiscordID = @discordId", {discordId: {type: Db.VARCHAR(50), value: user.id}}).then((countData) => {
let homes = countData && countData.recordsets[0] && countData.recordsets[0][0] && countData.recordsets[0][0].Homes || 0;
if (homes >= 3) {
Db.getHomeCountForDiscordId(user.id).then((homeCount) => {
if (homeCount >= 3) {
commands.service.queue(`Sorry, ${user}, but you have already set 3 home maps. If you haven't played a match yet, you can use \`!resethome\` to reset your home map selections.`, channel);
reject(new Error("Player already has 3 homes."));
return;
}
Db.query(
"INSERT INTO tblHome (DiscordID, Home) VALUES (@discordId, @home)",
{
discordId: {type: Db.VARCHAR(50), value: user.id},
home: {type: Db.VARCHAR(50), value: message}
}
).then(() => {
homes++;
Db.addHome(user.id, message).then(() => {
homeCount++;
const player = Event.getPlayer(user.id);
if (homes < 3 || !player) {
if (homeCount < 3 || !player) {
resolve(true);
return;
}
Db.query("SELECT Home FROM tblHome WHERE DiscordID = @discordId", {discordId: {type: Db.VARCHAR(50), value: user.id}}).then((homeData) => {
commands.service.queue(`You have successfully set one of your home maps to \`${message}\`. You may set ${3 - homes} more home map${3 - homes === 1 ? "" : "s"}. You can use \`!resethome\` at any point prior to playing a match to reset your home maps.`, user);
Db.getHomesForDiscordId(user.id).then((homes) => {
commands.service.queue(`You have successfully set one of your home maps to \`${message}\`. You may set ${3 - homes.length} more home map${3 - homes.length === 1 ? "" : "s"}. You can use \`!resethome\` at any point prior to playing a match to reset your home maps.`, user);
Event.setHomes(user.id, homeData.recordsets[0].map((m) => m.Home));
Event.setHomes(user.id, homes);
resolve(true);
}).catch((err) => {
@@ -447,20 +439,20 @@ class Commands {
return;
}
Db.query("SELECT TOP 1 Locked FROM tblHome WHERE DiscordID = @discordId ORDER BY Locked DESC", {discordId: {type: Db.VARCHAR(50), value: user.id}}).then((data) => {
if (data && data.recordsets[0] && data.recordsets[0].length === 0) {
Db.getResetStatusForDiscordId(user.id).then((status) => {
if (!status.hasHomes) {
commands.service.queue(`Sorry, ${user}, but you haven't set any home maps yet. Please use the \`!home\` command to select 3 home maps, one at a time, for example, \`!home Logic x2\`.`, channel);
reject(new Error("Player has no home maps."));
return;
}
if (data && data.recordsets[0] && data.recordsets[0][0].Locked) {
if (status.locked) {
commands.service.queue(`Sorry, ${user}, but your home maps are set for the season.`, channel);
reject(new Error("Player's home maps are locked."));
return;
}
Db.query("DELETE FROM tblHome WHERE DiscordID = @discordId", {discordId: {type: Db.VARCHAR(50), value: user.id}}).then(() => {
Db.deleteHomesForDiscordId(user.id).then(() => {
commands.service.queue("You have successfully cleared your home maps. Please use the `!home` command to select 3 home maps, one at a time, for example, `!home Logic x2`.", user);
resolve(true);
}).catch((err) => {
@@ -496,16 +488,16 @@ class Commands {
return;
}
Db.query("SELECT DiscordID, Home FROM tblHome", {}).then((data) => {
if (!data || !data.recordsets[0] || data.recordsets[0].length === 0) {
Db.getHomeList().then((homeList) => {
if (!homeList || homeList.length === 0) {
commands.service.queue(`Sorry, ${user}, but no one has set their home map yet.`, channel);
reject(new Error("No home maps set yet."));
return;
}
const homes = {};
data.recordsets[0].forEach((row) => {
homeList.forEach((row) => {
const name = Discord.getGuildUser(row.DiscordID);
if (!homes[name]) {
@@ -998,14 +990,14 @@ class Commands {
return;
}
Db.query("SELECT Home FROM tblHome WHERE DiscordID = @discordId", {discordId: {type: Db.VARCHAR(50), value: addedUser.id}}).then((data) => {
if (!data || !data.recordsets[0] || data.recordsets[0].length < 3) {
Db.getHomesForDiscordId(addedUser.id).then((homes) => {
if (homes.length < 3) {
commands.service.queue(`Sorry, ${user}, but this player has not added all 3 home maps yet.`, channel);
reject(new Error("Pilot has not yet set 3 home maps."));
return;
}
Event.addPlayer(addedUser.id, data.recordsets[0].map((m) => m.Home));
Event.addPlayer(addedUser.id, homes);
commands.service.queue(`You have successfully added ${addedUser.displayName} to the event.`, channel);
Discord.queue(`${Discord.getGuildUser(user).displayName} has added you to the next event! I assume you can host games, but if you cannot please issue the \`!host\` command to toggle this option.`, addedUser);
@@ -1,6 +1,6 @@
const sql = require("mssql"),
settings = require("./settings");
const Db = require("node-database"),
settings = require("./settings"),
db = new Db(settings.database);
// #### # #
// # # # #
@@ -13,77 +13,68 @@ const sql = require("mssql"),
* Defines the database class.
*/
class Database {
// ### # # ## ### # #
// # # # # # ## # # # #
// # # # # ## # # #
// ### ### ## # #
// # #
/**
* Executes a query.
* @param {string} sqlStr The SQL query.
* @param {object} params The parameters of the query.
* @return {Promise} A promise that resolves when the query is complete.
*/
static query(sqlStr, params) {
return new Promise((resolve, reject) => {
if (!params) {
params = {};
}
static getHomesForDiscordId(discordId) {
return db.query("SELECT Home FROM tblHome WHERE DiscordID = @discordId", {discordId: {type: Db.VARCHAR(50), value: discordId}}).then((data) => data && data.recordsets && data.recordsets[0] && data.recordsets[0].map((row) => row.Home));
}
const conn = new sql.ConnectionPool(settings.database, (errPool) => {
static getHomeCountForDiscordId(discordId) {
return db.query("SELECT COUNT(Home) Homes FROM tblHome WHERE DiscordID = @discordId", {discordId: {type: Db.VARCHAR(50), value: discordId}}).then((data) => data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].Homes || 0);
}
if (errPool) {
reject(errPool);
return;
}
static addHome(discordId, home) {
return db.query("INSERT INTO tblHome (DiscordID, Home) VALUES (@discordId, @home)", {
discordId: {type: Db.VARCHAR(50), value: discordId},
home: {type: Db.VARCHAR(50), value: home}
});
}
const ps = new sql.PreparedStatement(conn);
/**
*
* @param {string[]} discordIds
*/
static lockHomeLevelsForDiscordIds(discordIds) {
const players = discordIds.map((discordId, index) => ({index: `player${index}`, discordId}));
Object.keys(params).forEach((key) => {
ps.input(key, params[key].type);
});
ps.multiple = true;
ps.prepare(sqlStr, (errPrepare) => {
const paramList = {};
return db.query(`UPDATE tblHome SET Locked = 1 WHERE DiscordID IN (${players.map((p) => p.index).join(", ")})`, players.reduce((accumulator, player) => {
accumulator[player.index] = {type: Db.VARCHAR(50), value: player.discordId};
return accumulator;
}, {}));
}
if (errPrepare) {
reject(errPrepare);
return;
}
static updatePlayerRating(name, discordId, rating, ratingDeviation, volatility, playerId) {
return db.query(`
MERGE tblPlayer p
USING (VALUES (@name, @discordID, @rating, @ratingDeviation, @volatility)) AS v (Name, DiscordID, Rating, RatingDeviation, Volatility)
ON p.PlayerID = @playerID
WHEN MATCHED THEN
UPDATE SET Name = v.Name, DiscordID = v.DiscordID, Rating = v.Rating, RatingDeviation = v.RatingDeviation, Volatility = v.Volatility
WHEN NOT MATCHED THEN
INSERT (Name, DiscordID, Rating, RatingDeviation, Volatility) VALUES (v.Name, v.DiscordID, v.Rating, v.RatingDeviation, v.Volatility);
`, {
name: {type: Db.VARCHAR(50), value: name},
discordId: {type: Db.VARCHAR(50), value: discordId},
rating: {type: Db.FLOAT, value: rating},
ratingDeviation: {type: Db.FLOAT, value: ratingDeviation},
volatility: {type: Db.FLOAT, value: volatility},
playerId: {type: Db.INT, value: playerId || -1}
});
}
const paramMap = Object.keys(params).map((key) => [key, params[key].value]);
static getResetStatusForDiscordId(discordId) {
return db.query("SELECT TOP 1 Locked FROM tblHome WHERE DiscordID = @discordId ORDER BY Locked DESC", {discordId: {type: Db.VARCHAR(50), value: discordId}}).then((data) => ({hasHomes: data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && true, locked: data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].Locked}));
}
for (let i = 0, {length} = Object.keys(paramMap); i < length; i++) {
paramList[paramMap[i][0]] = paramMap[i][1];
}
static deleteHomesForDiscordId(discordId) {
return db.query("DELETE FROM tblHome WHERE DiscordID = @discordId", {discordId: {type: Db.VARCHAR(50), value: discordId}});
}
ps.execute(paramList, (errExecute, data) => {
if (errExecute) {
reject(errExecute);
return;
}
static getHomeList() {
Db.query("SELECT DiscordID, Home FROM tblHome").then((data) => data && data.recordsets && data.recordsets[0]);
}
ps.unprepare((errUnprepare) => {
if (errUnprepare) {
reject(errUnprepare);
return;
}
resolve(data);
});
});
});
});
});
static getPlayers() {
Db.query("SELECT PlayerID, Name, DiscordID, Rating, RatingDeviation, Volatility from tblPlayer").then((data) => data && data.recordsets && data.recordsets[0]);
}
}
({TYPES: Database.TYPES} = sql);
Object.keys(sql.TYPES).forEach((key) => {
const {TYPES: {[key]: value}} = sql;
Database[key] = value;
Database[key.toUpperCase()] = value;
});
module.exports = Database;
@@ -138,7 +138,7 @@ class Discord {
resultsChannel = obsGuild.channels.find("name", "match-results");
eventRole = obsGuild.roles.find("name", "In Current Event");
seasonRole = obsGuild.roles.find("name", "Season 7 Participant");
seasonRole = obsGuild.roles.find("name", "Season 9 Participant");
});
discord.on("disconnect", (ev) => {
Oops, something went wrong.

0 comments on commit 82c584b

Please sign in to comment.