Files
tcg-collectors-server/src/routes/sets/index.js
T
joseph.nelson4456 4f73991360 added collection and set APIs (#5)
Reviewed-on: #5
Co-authored-by: Joseph Nelson <joseph.nelson4456@gmail.com>
Co-committed-by: Joseph Nelson <joseph.nelson4456@gmail.com>
2026-05-16 23:15:06 -07:00

113 lines
2.6 KiB
JavaScript

import express from 'express'
import { Pool } from 'pg'
import { database } from '../../config'
const { check, validationResult } = require('express-validator')
const router = express.Router()
// Create a connection pool to the database
const pool = new Pool(database)
// Get all sets
router.get('/', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM sets')
res.json(result.rows)
} catch (error) {
res.status(500).json({ message: error.message })
}
})
// Create a new set
router.post(
'/',
[
check('collection_id').not().isEmpty(),
check('name').not().isEmpty(),
check('location_id').not().isEmpty(),
check('image_id').not().isEmpty(),
],
async (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
try {
const result = await pool.query(
'INSERT INTO sets (collection_id, name, location_id, image_id, created_at, updated_at) VALUES ($1, $2, $3, $4, NOW(), NOW()) RETURNING *',
[
req.body.collection_id,
req.body.name,
req.body.location_id,
req.body.image_id,
]
)
res.status(201).json(result.rows[0])
} catch (error) {
res.status(500).json({ message: error.message })
}
}
)
// Get a single set by ID
router.get('/:id', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM sets WHERE id = $1', [
req.params.id,
])
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Set not found' })
}
res.json(result.rows[0])
} catch (error) {
res.status(500).json({ message: error.message })
}
})
// Update a set by ID
router.put('/:id', [check('name').not().isEmpty()], async (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
try {
const result = await pool.query(
'UPDATE sets SET name = $1, updated_at = NOW() WHERE id = $2 RETURNING *',
[req.body.name, req.params.id]
)
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Set not found' })
}
res.json(result.rows[0])
} catch (error) {
res.status(500).json({ message: error.message })
}
})
// Delete a set by ID
router.delete('/:id', async (req, res) => {
try {
const result = await pool.query(
'DELETE FROM sets WHERE id = $1 RETURNING *',
[req.params.id]
)
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Set not found' })
}
res.json(result.rows[0])
} catch (error) {
res.status(500).json({ message: error.message })
}
})
module.exports = router