Created
September 14, 2020 09:23
-
-
Save alyson-b69/082ebc44f51e396c828ed79b7ca1b132 to your computer and use it in GitHub Desktop.
EXPRESS 6 - GET en détails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get All | |
app.get("/api/movies", (req, res) => { | |
let sql = "SELECT * FROM movie"; | |
const sqlValues = []; | |
if (req.query.rating) { | |
sql += " WHERE rating = ?"; | |
sqlValues.push(req.query.rating); | |
} | |
if (req.query.genre) { | |
sql += " WHERE genre = ?"; | |
sqlValues.push(req.query.genre); | |
} | |
connection.query(sql, sqlValues, (err, results) => { | |
if (err) { | |
res.status(500).send(`An error occurred: ${err.message}`); | |
} else { | |
res.json(results); | |
} | |
}); | |
}); | |
// Get one | |
app.get("/api/movies/:id", (req, res) => { | |
const movieId = req.params.id; | |
connection.query( | |
"SELECT * FROM movie WHERE id = ?", | |
[movieId], | |
(err, results) => { | |
if (err) { | |
res.status(500).send("An error occured :", err); | |
} | |
if (results.length === 0) { | |
return res.status(404).send("Movie not found"); | |
} else { | |
res.status(200).json(results[0]); | |
} | |
} | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment