1 var express = require('express');
3 var expressWs = require('express-ws')(app);
5 var db = require('./db');
8 return new Promise(resolve => setTimeout(resolve, ms));
11 async function pollStatefulChange(ws, session_id) {
16 var res = await db.getMaxUpdatedState(session_id);
17 var newRowCount = res[0].num_rows;
18 var updatedAt = res[0].last_updated;
20 // update board state of client if more moves
21 // have been added since max last timestamp
22 // If more moves have been added in <1 sec,
23 // use the row count for the max last updated timestamp
24 if (updatedAt > lastUpdated || rowCount < newRowCount) {
25 lastUpdated = updatedAt;
26 rowCount = newRowCount;
27 ws.send(JSON.stringify({
29 "data": await db.getBoardState(session_id)
33 console.log(`websocket poll error: ${err}`);
39 app.ws('/ws', async function(ws, req) {
40 // poll for stateful change and notify clients to update their boards
44 // send initial message to draw client board
45 ws.send(JSON.stringify({
47 "data": await db.getBoardState(session_id)
50 ws.on('message', async function(msg) {
53 parsed = JSON.parse(msg);
54 switch (parsed.type) {
56 ws.send(JSON.stringify({
58 "data": await db.deleteSession(parsed.data.session)
68 // fall through and return new board state
70 ws.send(JSON.stringify({
72 "data": await db.getBoardState(parsed.data.session)
76 console.log("ws message: Unknown message type: " + type);
79 console.log(`ws message error: ${err}`);
83 pollStatefulChange(ws, session_id);