added user and role APIs and fixed some items that were missing (#3)

Reviewed-on: #3
Co-authored-by: Joseph Nelson <joseph.nelson4456@gmail.com>
Co-committed-by: Joseph Nelson <joseph.nelson4456@gmail.com>
This commit was merged in pull request #3.
This commit is contained in:
2026-05-15 23:34:27 -07:00
committed by joseph.nelson4456
parent 2636816241
commit 3b55f82130
7 changed files with 280 additions and 4 deletions
+93
View File
@@ -0,0 +1,93 @@
import express from 'express'
import { database } from '../../config'
const { Pool } = require('pg')
const router = express.Router()
// Create a connection pool to the database
const pool = new Pool(database)
// 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