From 310d822daee8b5c3e804099342d90e4a8aba281f Mon Sep 17 00:00:00 2001 From: Ruclo Date: Sat, 19 Oct 2024 16:15:38 +0200 Subject: [PATCH] feat: POST /events --- index.js | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 0a0b71d..5061747 100644 --- a/index.js +++ b/index.js @@ -18,6 +18,9 @@ app.use(cors({ origin: 'http://localhost:5173' })); +// Use middleware to parse JSON in request body +app.use(express.json()); + // Define a simple route app.get('/', (req, res) => { res.send('Hello from the Node.js backend!'); @@ -54,8 +57,24 @@ app.get('/events/offline', async (req, res) => { }); app.post('/events', async (req, res) => { + const { title, date, type, description, link } = req.body; + + let trimmedTitle; + if (!title || (trimmedTitle = title.trim()).length == 0) { + return res.status(400).json({error: 'Title required.'}) + } + + let dateObj; + if (isNaN((dateObj = new Date(date)).getTime())) { + return res.status(400).json({error: 'Invalid date.'}) + } + + if (type && !['offline', 'online'].includes(type)) { + return res.status(400).json({error: 'Invalid type. Allowed types: online/offline.'}) + } + try { - const result = await pool.query('INSERT INTO events (name, date) VALUES ($1, $2) RETURNING *', ['New event', new Date()]); + const result = await pool.query('INSERT INTO events (title, date, type, description, image, link) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *', [trimmedTitle, dateObj, type, description.trim(), null, link]); res.json(result.rows[0]); } catch (err) { console.error(err);