From c1c67cb4d29684d9e874429b64ceec0692829e92 Mon Sep 17 00:00:00 2001 From: Nathan Date: Thu, 17 Oct 2024 15:57:34 +0100 Subject: [PATCH] Add basic DB selects --- database.js | 57 +++++++++++++++++++++++++++++++++++++++++++++++++---- server.js | 5 ++++- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/database.js b/database.js index a048a2f..e209548 100644 --- a/database.js +++ b/database.js @@ -16,14 +16,62 @@ function disconnect(){ con.end(); } -function getCards(additionalData){ +// Is calling a promise in a promise the best way to do this? +// Keeping because this is how I've figured to call other funcs from database +function getCardById(cardId){ + + const dPromise = new Promise((resolve, reject) => { + + getCards(' card.id = '+cardId).then(cards => { + resolve(cards); + }) + .catch(err => { + throw err; reject(new Error(err)); + }); + + }); + return dPromise; +} + +function getCards(whereClause){ const cPromise = new Promise((resolve, reject) => { - let sql = 'SELECT * FROM card'; - if(additionalData){ sql = sql + " WHERE "+additionalData; } + let cards = []; + let sql = `SELECT + card.id AS cardId -- TEMP UNTIL UID + ,cardName + ,cardCost + ,typeName + ,cardAttack + ,rarityName + FROM card + LEFT JOIN type ON type.id = card.id + LEFT JOIN rarity ON rarity.id = card.cardRarity + `; + // TODO: Rewrite this so it's not so insecure!!!! + if(whereClause){ sql = sql + " WHERE "+whereClause; } con.query(sql, function (err, result, fields) { if (err) { throw err; reject(new Error(err)); } - resolve(result); + result.forEach((card) => { + let tempCard = {}; + tempCard.id = card.cardId; + tempCard.name = card.cardName; + tempCard.colour = 'temp'; + tempCard.cost = card.cardCost; + tempCard.type = card.typeName; + tempCard.atk = card.cardAttack; + tempCard.rarity = card.rarityName; + tempCard.effect = 'temp effect'; + // TODO: Will need more SQL statements, or some function/procedure + // class + // colour requirements + // card effects + + cards.push(tempCard); + }); + + //console.log(cards); + resolve(cards); }); }); return cPromise; @@ -32,4 +80,5 @@ function getCards(additionalData){ module.exports = { connect, disconnect , getCards + , getCardById }; diff --git a/server.js b/server.js index 9d5658f..c851f1a 100644 --- a/server.js +++ b/server.js @@ -201,12 +201,15 @@ function requestJoinRoom(socket, playerName, roomId){ } +// Change to Decks, or 'getPlayerDecks' for the game +// Could also be a specific deck if player clicks into one? Although maybe when entering +// decks they get all their decks (maybe just id actually) then load from there? function requestGetCards(socket){ let response = {'success':false, 'message':'Nothing happened'}; response.success = true; // Await promise, once it's done get the data, if errors send err - database.getCards().then(data => { + database.getCardById(1).then(data => { response.message = data; io.to(socket.id).emit('responseGetCards', response); })