Files

86 lines
2.0 KiB
JavaScript

'use strict';
const fs = require('fs');
const path = require('path');
const initSqlJs = require('sql.js');
const DATA_DIR = path.join(__dirname, 'data');
const DB_PATH = path.join(DATA_DIR, 'games.db');
let db = null;
async function init() {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
const SQL = await initSqlJs();
if (fs.existsSync(DB_PATH)) {
const buf = fs.readFileSync(DB_PATH);
db = new SQL.Database(buf);
} else {
db = new SQL.Database();
db.run(`CREATE TABLE IF NOT EXISTS games (
id TEXT PRIMARY KEY,
token TEXT UNIQUE NOT NULL,
status TEXT NOT NULL DEFAULT 'waiting',
board TEXT NOT NULL DEFAULT 'null',
turn TEXT NOT NULL DEFAULT 'X',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`);
persist();
}
}
function createGame({ id, token }) {
const now = new Date().toISOString();
db.run(
`INSERT INTO games (id, token, status, board, turn, created_at, updated_at)
VALUES (?, ?, 'waiting', 'null', 'X', ?, ?)`,
[id, token, now, now]
);
persist();
}
function getGameByToken(token) {
const stmt = db.prepare(`SELECT * FROM games WHERE token = ?`);
stmt.bind([token]);
if (stmt.step()) {
const row = stmt.getAsObject();
stmt.free();
return row;
}
stmt.free();
return null;
}
function getGameById(id) {
const stmt = db.prepare(`SELECT * FROM games WHERE id = ?`);
stmt.bind([id]);
if (stmt.step()) {
const row = stmt.getAsObject();
stmt.free();
return row;
}
stmt.free();
return null;
}
function updateGame(id, { status, board, turn }) {
const now = new Date().toISOString();
db.run(
`UPDATE games SET status = ?, board = ?, turn = ?, updated_at = ? WHERE id = ?`,
[status, board, turn, now, id]
);
persist();
}
function persist() {
const data = db.export();
fs.writeFileSync(DB_PATH, Buffer.from(data));
}
module.exports = { init, createGame, getGameByToken, getGameById, updateGame, persist };