dthpp-node/controllers/matchcontroller.js

75 lines
1.9 KiB
JavaScript

const jwt = require('jsonwebtoken');
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
async function getUserIdFromToken(token) {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
return decoded.id;
} catch (err) {
throw new Error('Invalid token');
}
}
async function createMatch(req, res) {
const token = req.headers['authorization']?.split(' ')[1];
if (!token) {
return res.status(403).json({ error: 'Token is required.' });
}
try {
const player1_uid = await getUserIdFromToken(token);
const client = await pool.connect();
try {
const result = await client.query(
'INSERT INTO matches (player1_uid) VALUES ($1) RETURNING match_id;',
[player1_uid]
);
const match_id = result.rows[0].match_id;
return res.status(200).json({ match_id });
} finally {
client.release();
}
} catch (error) {
console.error('Error creating match:', error);
return res.status(400).json({ error: error.message });
}
}
async function createMatch2v2(req, res) {
const token = req.headers['authorization']?.split(' ')[1];
if (!token) {
return res.status(403).json({ error: 'Token is required.' });
}
try {
const player1_uid = await getUserIdFromToken(token);
const client = await pool.connect();
try {
const result = await client.query(
'INSERT INTO matches_2v2 (player1_team1_uid) VALUES ($1) RETURNING match_id;',
[player1_uid]
);
const match_id = result.rows[0].match_id;
return res.status(200).json({ match_id });
} finally {
client.release();
}
} catch (error) {
console.error('Error creating 2v2 match:', error);
return res.status(400).json({ error: error.message });
}
}
module.exports = {
createMatch,
createMatch2v2,
};