Created
June 8, 2020 10:55
-
-
Save lebowvsky/a840bcf98bf12c85b5b171c5685ca037 to your computer and use it in GitHub Desktop.
Express 6 - get detail
This file contains 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 connection = require("./conf"); | |
const express = require("express"); | |
const app = express(); | |
const port = 3000; | |
app.get("/api/movies", (req, res) => { | |
let sql = "SELECT * FROM movie"; | |
let sqlValues = []; | |
if (req.query.rating && req.query.genre) { | |
console.log("On y est"); | |
sqlValues = []; | |
sql += " WHERE rating = ? AND genre = ?"; | |
sqlValues.push(req.query.rating, req.query.genre); | |
} 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(`Erreur lors de la récupération des films : ${err}`); | |
} else { | |
res.json(results); | |
} | |
}); | |
}); | |
app.get("/api/movies/:id", (req, res) => { | |
const movieId = req.params.id; | |
connection.query( | |
"SELECT * FROM movie WHERE id = ?", | |
[movieId], | |
(err, results) => { | |
if (err) { | |
console.log(err); | |
res.status(500).send("Erreur lors de la récupération du film..."); | |
} else { | |
if (!results || results.length === 0) { | |
res.status(404).send("Pas de film correspondant..."); | |
} else { | |
res.json(results); | |
} | |
} | |
} | |
); | |
}); | |
app.listen(port, (err) => { | |
if (err) { | |
throw new Error("Something goes wrong"); | |
} else { | |
console.log(`Server is listen on the port : ${port}`); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment