]> Untitled Git - go.git/blob - socket/db.js
Added basic controls, refactored database sync (#2)
[go.git] / socket / db.js
1 const mariadb = require('mariadb');
2 const dsn = {
3     host: 'db', 
4     user: 'socket',
5     password: 'socketpw',
6     connectionLimit: 10
7 };
8 const pool = mariadb.createPool(dsn);
9
10 async function getMaxUpdatedState(session_id) {
11     let conn;
12     try {
13         conn = await pool.getConnection();
14         return await conn.query(`
15 SELECT
16     count(*) AS num_rows,
17     UNIX_TIMESTAMP(max_updated_at) AS last_updated
18 FROM go.state g JOIN (
19     SELECT MAX(updated_at) AS max_updated_at
20     FROM go.state
21     WHERE session_id = ?
22 ) x
23 ON x.max_updated_at = g.updated_at
24             `, [session_id]);
25     } catch (err) {
26         console.log(err);
27     } finally {
28         if (conn) conn.end();
29     }
30 }
31
32 async function deleteSession(session_id) {
33     let conn;
34     try {
35         conn = await pool.getConnection();
36         return await conn.query(
37             "DELETE FROM go.state WHERE session_id = ?",
38             [session_id]
39         );
40     } catch (err) {
41         console.log(err);
42     } finally {
43         if (conn) conn.end();
44     }
45 }
46
47 async function initBoard() {
48     let conn;
49     try {
50         conn = await pool.getConnection();
51         return await conn.query(`
52 CREATE TABLE IF NOT EXISTS
53 go.state (
54     session_id INT UNSIGNED,
55     x TINYINT UNSIGNED,
56     y TINYINT UNSIGNED,
57     state TINYINT UNSIGNED,
58     updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
59         ON UPDATE CURRENT_TIMESTAMP,
60     PRIMARY KEY(session_id, x, y)
61 );
62         `);
63     } catch (err) {
64         console.log(err);
65     } finally {
66         if (conn) conn.end();
67     }
68 }
69
70 async function addMove(session_id, pos_x, pos_y, state) {
71     let conn;
72     try {
73         conn = await pool.getConnection();
74         return await conn.query(`
75 INSERT INTO go.state (session_id, x, y, state)
76 values (?, ?, ?, ?)
77 ON DUPLICATE KEY UPDATE
78 state = VALUES(state);
79         `, [session_id, pos_x, pos_y, state]);
80     } catch (err) {
81         console.log(err);
82     } finally {
83         if (conn) conn.end();
84     }
85 }
86
87 async function getBoardState(session_id) {
88     let conn;
89     try {
90         conn = await pool.getConnection();
91         return await conn.query(`
92 SELECT x, y, state from go.state where session_id = ?
93         `, [session_id]);
94     } catch (err) {
95         console.log(err);
96     } finally {
97         if (conn) conn.end();
98     }
99 }
100
101 exports.getMaxUpdatedState = getMaxUpdatedState;
102 exports.deleteSession = deleteSession;
103 exports.initBoard = initBoard;
104 exports.addMove = addMove;
105 exports.getBoardState = getBoardState;