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>
This commit was merged in pull request #5.
This commit is contained in:
2026-05-16 23:15:06 -07:00
committed by joseph.nelson4456
parent 0db3d677b2
commit 4f73991360
4 changed files with 230 additions and 0 deletions
+111
View File
@@ -0,0 +1,111 @@
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 collections
router.get('/', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM collections')
res.json(result.rows)
} catch (error) {
console.error(error)
res.status(500).send('Server error')
}
})
// Get a single collection by id
router.get('/:id', async (req, res) => {
const { id } = req.params
try {
const result = await pool.query('SELECT * FROM collections WHERE id = $1', [
id,
])
if (result.rows.length === 0) {
return res.status(404).send('Collection not found')
}
res.json(result.rows[0])
} catch (error) {
console.error(error)
res.status(500).send('Server error')
}
})
// Create a new collection
router.post(
'/',
[
check('name', 'Name is required').not().isEmpty(),
check('image_id', 'Image id is required').not().isEmpty(),
],
async (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
const { name, image_id } = req.body
try {
const result = await pool.query(
'INSERT INTO collections (name, image_id, created_at, updated_at) VALUES ($1, $2, NOW(), NOW()) RETURNING *',
[name, image_id]
)
res.status(201).json(result.rows[0])
} catch (error) {
console.error(error)
res.status(500).send('Server error')
}
}
)
// Update an existing collection
router.put(
'/:id',
[
check('name', 'Name is required').not().isEmpty(),
check('image_id', 'Image id is required').not().isEmpty(),
],
async (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
const { name, image_id } = req.body
const { id } = req.params
try {
await pool.query(
'UPDATE collections SET name = $1, image_id = $2, updated_at = NOW() WHERE id = $3',
[name, image_id, id]
)
res.send('Collection updated')
} catch (error) {
console.error(error)
res.status(500).send('Server error')
}
}
)
// Delete an existing collection
router.delete('/:id', async (req, res) => {
const { id } = req.params
try {
await pool.query('DELETE FROM collections WHERE id = $1', [id])
res.send('Collection deleted')
} catch (error) {
console.error(error)
res.status(500).send('Server error')
}
})
export default router