Skip to content

Instantly share code, notes, and snippets.

@alyson-b69
Created September 14, 2020 09:23
Show Gist options
  • Save alyson-b69/082ebc44f51e396c828ed79b7ca1b132 to your computer and use it in GitHub Desktop.
Save alyson-b69/082ebc44f51e396c828ed79b7ca1b132 to your computer and use it in GitHub Desktop.
EXPRESS 6 - GET en détails
// 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