import express from 'express' import { pool } from '../../config/index.js' import { check, validationResult } from 'express-validator' const router = express.Router() // 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