Last active
December 9, 2019 11:44
-
-
Save BastienSaulnier/f17aae1b4bee44dd13063fb565ba89ea to your computer and use it in GitHub Desktop.
Express 6 - GET en détail - Wild Code School
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 connection = require("./conf"); | |
const express = require("express"); | |
const app = express(); | |
const port = process.env.PORT || 3000; | |
/* --- GET All --- */ | |
app.get("/api/movies", (req, res) => { | |
let sql = "SELECT * FROM movie"; | |
const sqlValues = []; | |
if (req.query.rating && req.query.genre) { | |
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) { | |
return res.status(500).send("Erreur lors de la récupération des films"); | |
} else { | |
return res.json(results); | |
} | |
}); | |
}); | |
/* --- GET One --- */ | |
app.get("/api/movies/:id", (req, res) => { | |
const id = req.params.id; | |
connection.query(`SELECT * FROM movie WHERE ID =${id}`, (err, results) => { | |
if (err) { | |
return res.status(500).send("Erreur lors de la récupération du film"); | |
} | |
if (results.length === 0) { | |
return res.status(404).send(`Movie id=${id} not found`); | |
} else { | |
return res.json(results[0]); | |
} | |
}); | |
}); | |
//PORT | |
app.listen(port, err => { | |
if (err) { | |
throw new Error("Quelque chose ne s'est pas passé come prévu !"); | |
} | |
console.log(`Server listening to port ${port}...`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment