Created
February 18, 2020 07:46
-
-
Save bastienapp/f0b9a02be61652d55508bcd8b1118f8b to your computer and use it in GitHub Desktop.
Express quest 6
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.listen(port, (err) => { | |
if (err) { | |
throw new Error('Something bad happened...'); | |
} | |
console.log(`Server is listening on ${port}`); | |
}); | |
const bodyParser = require('body-parser'); | |
// Support JSON-encoded bodies | |
app.use(bodyParser.json()); | |
// Support URL-encoded bodies | |
app.use(bodyParser.urlencoded({ | |
extended: true | |
})); | |
app.get('/api/movies/:id', (req, res) => { | |
const id = req.params.id; | |
connection.query('SELECT * from movie WHERE id = ?', [id], (err, results) => { | |
if (err) { | |
console.error(err); | |
res.status(500).send(`An error occurred: ${err.message}`); | |
} else if (results === undefined || results.length < 1) { | |
res.status(404).send('Movie not found'); | |
} else { | |
res.json(results[0]); | |
} | |
}); | |
}); | |
app.get('/api/movies', (req, res) => { | |
let sql = 'SELECT * FROM movie'; | |
const sqlValues = []; | |
if (req.query.genre) { | |
sql += ' WHERE genre = ?'; | |
sqlValues.push(req.query.genre); | |
} | |
else if (req.query.rating) { | |
sql += ' WHERE rating = ?'; | |
sqlValues.push(req.query.rating); | |
} | |
// send an SQL query to get all employees | |
connection.query(sql, sqlValues, (err, results) => { | |
if (err) { | |
res.status(500).json({ | |
error: err, | |
message: 'Erreur lors de la récupération des films' | |
}); | |
} else { | |
res.json(results); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment