import express from 'express' import { pool } from '../../config/index.js' const router = express.Router() // Create a new role router.post('/', async (req, res) => { const { name } = req.body const client = await pool.connect() try { await client.query('BEGIN') const result = await client.query( 'INSERT INTO roles (name, created_at, updated_at) VALUES ($1, NOW(), NOW()) RETURNING *', [name] ) await client.query('COMMIT') res.status(201).json(result.rows[0]) } catch (err) { await client.query('ROLLBACK') res.status(500).json({ error: err.message }) } }) // Get all roles router.get('/', async (req, res) => { try { const result = await pool.query('SELECT * FROM roles') res.json(result.rows) } catch (err) { res.status(500).json({ error: err.message }) } }) // Get a single role by id router.get('/:id', async (req, res) => { const { id } = req.params try { const result = await pool.query('SELECT * FROM roles WHERE id = $1', [id]) if (result.rows.length === 0) return res.status(404).json({ error: 'Role not found' }) res.json(result.rows[0]) } catch (err) { res.status(500).json({ error: err.message }) } }) // Update a role by id router.put('/:id', async (req, res) => { const { id } = req.params const { name } = req.body const client = await pool.connect() try { await client.query('BEGIN') const result = await client.query( 'UPDATE roles SET name = $1, updated_at = NOW() WHERE id = $2 RETURNING *', [name, id] ) if (result.rows.length === 0) return res.status(404).json({ error: 'Role not found' }) await client.query('COMMIT') res.json(result.rows[0]) } catch (err) { await client.query('ROLLBACK') res.status(500).json({ error: err.message }) } }) // Delete a role by id router.delete('/:id', async (req, res) => { const { id } = req.params const client = await pool.connect() try { await client.query('BEGIN') const result = await client.query('DELETE FROM roles WHERE id = $1', [id]) if (result.rows.length === 0) return res.status(404).json({ error: 'Role not found' }) await client.query('COMMIT') res.json(result.rows[0]) } catch (err) { await client.query('ROLLBACK') res.status(500).json({ error: err.message }) } }) export default router