Last active
September 13, 2020 17:32
-
-
Save justinehell/5b3691801d32598064253e38409d5853 to your computer and use it in GitHub Desktop.
Express 6 - GET en détail
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
const express = require("express"); | |
const app = express(); | |
const port = 3000; | |
const connection = require("./conf"); | |
app.use(express.json()); | |
app.use( | |
express.urlencoded({ | |
extended: true, | |
}) | |
); | |
// GET ALL MOVIEs or FILTERED MOVIES with rating and/or genre | |
app.get("/api/movies", (req, res) => { | |
let sql = "SELECT * FROM movie"; | |
const sqlValues = []; | |
if (req.query.genre && req.query.rating) { | |
sql += " WHERE genre = ? AND rating = ?"; | |
sqlValues.push(req.query.genre); | |
sqlValues.push(req.query.rating); | |
} else if (req.query.rating) { | |
sql += " WHERE rating = ?"; | |
sqlValues.push(req.query.rating); | |
} else if (req.query.genre) { | |
sql += " WHERE genre = ?"; | |
sqlValues.push(req.query.genre); | |
} | |
connection.query(sql, sqlValues, (err, results) => { | |
if (err) { | |
res.status(500).send("Error while recovering movies"); | |
} else { | |
res.json(results); | |
} | |
}); | |
}); | |
// GET ONE MOVIE | |
app.get("/api/movies/:id", (req, res) => { | |
const idMovie = req.params.id; | |
connection.query( | |
"SELECT * from movie WHERE id= ?", | |
[idMovie], | |
(err, results) => { | |
if (err) { | |
return res.status(500).send(`An error occurred: ${err.message}`); | |
} | |
if (results[0] === undefined) { | |
return res.status(404).send("Movie not found"); | |
} | |
return res.json(results[0]); | |
} | |
); | |
}); | |
app.listen(port, (err) => { | |
if (err) { | |
throw new Error("Something bad happened..."); | |
} | |
console.log(`Server is listening on ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment