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
45 ws.send(JSON.stringify({
49 ws.on('message', async function(msg) {
52 parsed = JSON.parse(msg);
53 switch (parsed.type) {
55 session_id = parsed.data.session
57 // send initial message to draw session client board
58 ws.send(JSON.stringify({
60 "data": await db.getBoardState(session_id)
64 ws.send(JSON.stringify({
66 "data": await db.deleteSession(parsed.data.session)
76 // fall through and return new board state
78 ws.send(JSON.stringify({
80 "data": await db.getBoardState(parsed.data.session)
84 console.log("ws message: Unknown message type: " + type);
87 console.log(`ws message error: ${err}`);
91 pollStatefulChange(ws, session_id);