I currently use PHP and AJAX to select the passwords I have saved in my database and them send them back. Depending on the search terms, or if the passwords are being re-encrypted, the request can take a while with no feedback, besides using a spinner. I use a node websocket server on other pages and thought I could migrate it from AJAX/fetch to use websockets so I could send the page a realtime progress report. I have used promises in other scripts but figured I would learn to use async/wait functions on the parts of this that were dependent on the long queries and re-encryption. I am using mysql2/promise module and can get the data out of the DB and print it to the console but am unable to do anything with it outside of an async function (which kind of makes sense to me, wont the rest of the script be ticking away doing its own thing while the await is awaiting?) What I have tried to do is pass the websocket object into the function but it just silently does nothing.
I have tried reading a heap of blogs and tutorials, but most of them end up just printing to console.
my current code attempt is:
(async function main(){
try{
const mysql2 = require('mysql2/promise');
const fs = require('fs');
const http = require('http');
const WebSocket = require('ws');
const { v4: uuidv4 } = require('uuid');
const url = require('url');
const token = *******************;
const dbConfig = ***************;
clients = {};
// create the webserver and websocket
const server = await http.createServer()
.listen(6);
const wss = new WebSocket.Server({ server});
// set up the database pool
const poolConfig = {
host: "127.0.0.1",
user: "arealuser",
password: "qwertyuiop",
database: "example"
}
const pool = mysql2.createPool(poolConfig);
console.log("started web socket server...")
wss.on('connection', function connection(ws, req) {
const tokenMatch = url.parse(req.url, true).query.token; //load the saved token from the URI token parameter
const service = url.parse(req.url, true).query.service; //load the service requested from the URI service parameter
if(tokenMatch == token && service == "encryption") {
//check if the client has the correct token, close connection
//if no match
ws.id = uuidv4();
ws.ip = ws._socket.remoteAddress;
console.log(`UUID ${ws.id} has connected for Encryption: ${ws.ip}`);
clients[ws.id] = ws;
ws.send("connected"); // appears on client console
clients[ws.id].send('test 1'); // appears on client console
(async function(){
let result = await selectRows(4,pool);
console.log(result[0]); // row results appear on server console
clients[ws.id].send('test result'); // does not get sent to client
})();
////// test code - deleteMe ////
let resultFail = selectRows(4,pool);
// console.log(result[0]); // this line fails with ReferenceError
clients[ws.id].send('test resultFail'); // appears on client console
/////////////////////////////////
}
async function selectRows(uid,pool){
const sql = "SELECT idpasswords, password, salt, (SELECT ops_memlimit FROM users WHERE idusers =?) AS ops_memlimit FROM passwords WHERE uid = ?";
try {
const [rows, fields] = await pool.query(sql,[uid,uid]);
return rows;
} catch (err) {
console.log(err);
}
}
// other, unrelated webscket services
} catch(error){
console.log(error);
}
})();
I have also tried sending the the ws
object like this to send data to the clients, but cant get it to work. (mysql2 was a working database connection and selectPasswords returned a valid resultset, this was just testing sending to clients)
async function reEncryptDb(ws,uid,mysql2){
try{
ws.send("starting the function");
console.log("starting the function");
const result = await selectPasswords(uid, mysql2);
console.log("after await");
ws.send("after await");
ws.send(result[0].idpasswords);
ws.send("after result");
}
catch(error){
console.log(`there has been an error: ${error}`);
ws.send(`there has been an error:}`);
}
}
I am at a loss as to where to go now to get this to work. I just dont underrstand how to get the data out of the async function, or the websocket object into the function so I can use it (I feel this is probably what I want). Any pointers or links to reading material would be helpful as everything I have read so far is really good at getting me to print to the console.
Thanks.
Your code run just fine even on multiple instances, I tested it. Double-check the websocket connection, is it closed during the database query? Or maybe you messed up the clients object somewhere else in your code?
Also your approach with async/await is good, especially the 2nd one, I see no problem with it.