Last active
December 17, 2019 15:13
-
-
Save jervalles/d21a1ca228e3f49c6247ef8cf9c631dc to your computer and use it in GitHub Desktop.
express 6
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 express = require("express"); | |
const connection = require("./conf"); | |
const app = express(); | |
const port = 3000; | |
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); | |
sqlValues.push(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(`An error occurred: ${err.message}`); | |
} else { | |
d; | |
res.json(results); | |
} | |
}); | |
}); | |
app.get("/api/movies/:id", (req, res) => { | |
const idMovie = req.params.id; | |
connection.query( | |
"SELECT * FROM movie WHERE id = ?", | |
[idMovie], | |
(err, results) => { | |
if (err) { | |
res.status(500).send(`An error occurred: ${err.message}`); | |
} | |
if (results.length === 0) { | |
return res.status(404).send("Movie not found"); | |
} else { | |
res.json(results); | |
} | |
} | |
); | |
}); | |
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