53 lines
1.8 KiB
JavaScript
53 lines
1.8 KiB
JavaScript
import { usersPool } from "./pools.js";
|
|
|
|
// ── Schema ────────────────────────────────────────────────────────────────────
|
|
|
|
export async function initUsersSchema() {
|
|
await usersPool.query(`
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id SERIAL PRIMARY KEY,
|
|
username TEXT NOT NULL UNIQUE,
|
|
password_hash TEXT NOT NULL,
|
|
team TEXT NOT NULL CHECK (team IN ('blue', 'red')),
|
|
role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'admin')),
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
`);
|
|
}
|
|
|
|
// ── Queries ───────────────────────────────────────────────────────────────────
|
|
|
|
export async function createUser(username, passwordHash, team) {
|
|
const { rows } = await usersPool.query(
|
|
`INSERT INTO users (username, password_hash, team)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING id, username, team, role`,
|
|
[username, passwordHash, team]
|
|
);
|
|
return rows[0];
|
|
}
|
|
|
|
export async function getUserByUsername(username) {
|
|
const { rows } = await usersPool.query(
|
|
`SELECT id, username, team, role, password_hash FROM users WHERE username = $1`,
|
|
[username]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function getUserById(id) {
|
|
const { rows } = await usersPool.query(
|
|
`SELECT id, username, team, role FROM users WHERE id = $1`,
|
|
[id]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function getTeamPlayerCounts() {
|
|
const { rows } = await usersPool.query(
|
|
`SELECT team, COUNT(*)::int AS count FROM users GROUP BY team`
|
|
);
|
|
const result = { blue: 0, red: 0 };
|
|
for (const row of rows) result[row.team] = row.count;
|
|
return result;
|
|
} |