]> Untitled Git - go.git/blob - socket/server.js
52ce170658c99f81d17e154b9f9fb92d8cad56b4
[go.git] / socket / server.js
1 var express = require('express');
2 var app = express();
3 var expressWs = require('express-ws')(app);
4
5 var db = require('./db');
6
7 function sleep(ms) {
8   return new Promise(resolve => setTimeout(resolve, ms));
9 }
10
11 async function pollStatefulChange(ws, session_id) {
12     var lastUpdated  = 0;
13     var rowCount = 0;
14     while (true) {
15         try {
16             var res = await db.getMaxUpdatedState(session_id);
17             var newRowCount = res[0].num_rows;
18             var updatedAt = res[0].last_updated;
19
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({
28                     "type": "board",
29                     "data": await db.getBoardState(session_id)
30                 }));
31             }
32         } catch(err) {
33             console.log(`websocket poll error: ${err}`);
34         }
35         await sleep(1000);
36     }
37 }
38
39 app.ws('/ws', async function(ws, req) {
40     // poll for stateful change and notify clients to update their boards
41     var session_id = 0;
42     db.initBoard();
43
44     // send initial message to draw client board
45     ws.send(JSON.stringify({
46         "type": "board",
47         "data": await db.getBoardState(session_id)
48     }));
49
50     ws.on('message', async function(msg) {
51         let parsed;
52         try {
53             parsed = JSON.parse(msg);
54             switch (parsed.type) {
55                 case "new":
56                     ws.send(JSON.stringify({
57                         "type": "new",
58                         "data": await db.deleteSession(parsed.data.session)
59                     }));
60                     break;
61                 case "move":
62                     await db.addMove(
63                         parsed.data.session,
64                         parsed.data.x,
65                         parsed.data.y,
66                         parsed.data.state,
67                         );
68                     // fall through and return new board state
69                 case "board":
70                     ws.send(JSON.stringify({
71                         "type": "board",
72                         "data": await db.getBoardState(parsed.data.session)
73                     }));
74                     break;
75                 default:
76                     console.log("ws message: Unknown message type: " + type);
77             }
78         } catch(err) {
79             console.log(`ws message error: ${err}`);
80         }
81     });
82
83     pollStatefulChange(ws, session_id);
84 });
85
86 app.listen(3000);