diff --git a/server/api.js b/server/api.js index 7f4db1db3f..ec7bccbc66 100644 --- a/server/api.js +++ b/server/api.js @@ -1,5 +1,6 @@ import { Router } from "express"; import db from "./db.js"; + const router = Router(); router.get("/videos", async (_, res) => { @@ -14,17 +15,28 @@ router.get("/videos", async (_, res) => { }); router.post("/videos", async (req, res) => { - if (!req.body.title) { + const { title, src } = req.body; + + if (!title) { return res.status(422).json({ message: "Title field is required" }); } - if (!req.body.src) { + if (!src) { return res.status(422).json({ message: "src field is required" }); } - const result = await db.query( - `INSERT INTO videos (title,src) VALUES ('${req.body.title}','${req.body.src}') RETURNING id` - ); - const newVideoId = result.rows[0].id; - res.status(200).json({ success: true, data: { id: newVideoId } }); + + try { + const result = await db.query( + "INSERT INTO videos (title, src) VALUES ($1, $2) RETURNING id", + [title, src] + ); + + const newVideoId = result.rows[0].id; + res.status(200).json({ success: true, data: { id: newVideoId } }); + } catch (error) { + res + .status(500) + .json({ success: false, error: "Failed to insert video into database" }); + } }); router.delete("/videos/:id", async (req, res) => { @@ -32,23 +44,19 @@ router.delete("/videos/:id", async (req, res) => { try { const checkQuery = await db.query("SELECT * FROM videos WHERE id = $1", [ - `${videoId}`, + videoId, ]); if (checkQuery.rows.length === 0) { - return res.status(404).json({ - message: "Video not found", - }); + return res.status(404).json({ message: "Video not found" }); } - const deleteQuery = await db.query("DELETE FROM videos WHERE id = $1", [ - videoId, - ]); - + await db.query("DELETE FROM videos WHERE id = $1", [videoId]); return res.status(204).end(); } catch (error) { + console.error(error); res .status(500) - .json({ message: "Internal server error", error: this.error }); + .json({ message: "An error occurred while deleting the video" }); } });