Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const connection = require('./config');
const express = require("express");
const port = 3000;
const app = express();
connection.connect(err => {
if(err){
console.log('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
})
app.use(express.json());
app.listen(port, () => {
console.log(`Server listen on ${port}`);
});
app.get("/", (req, res) => {
res.send("Welcome to my favourite movies list!");
});
app.get("/api/movies", (req, res) => {
connection.query("SELECT * FROM movies", (err, results) => {
if(err){
res.status(500).send("error retrieving datas");
}else{
res.status(200).json(results);
}
})
});
app.get("/api/movies/:id", (req, res) => {
connection.query(
"SELECT * FROM movies WHERE id=?",
[req.params.id],
(err, results) => {
if(err || results.length == 0){
res.status(500).send("error retrieving datas");
}else{
res.status(200).json(results);
}
})
});
app.get("/api/search", (req, res) => {
connection.query(
`SELECT * FROM movies WHERE duration <= ${req.query.maxDuration}`,
(err, results) => {
if(err){
res.status(500).send("error retrieving datas");
}else{
if(results.length > 0){
res.status(200).json(results);
}else{
res.status(404).send("No results for this duration");
}
}
})
});
app.post('/api/movies', (req, res) => {
const {title, director, year, color, duration} = req.body;
connection.query(
"INSERT INTO movies (title, director, year, color, duration) VALUES(?,?,?,?,?)",
[title, director, year, color, duration],
(err, results) => {
if(err){
console.log(err);
res.status(500).send("Error saving movie");
}else{
res.status(200).send("Successfully saved into database");
}
})
})
app.get("/users", (req, res) => {
connection.query(
"SELECT * FROM users",
(err, results) => {
if(err){
res.sendStatus(500);
}else{
res.status(200).send(results);
}
})
});
app.post("/users", (req, res) => {
const {firstname, lastname, email} = req.body;
connection.query(
"INSERT INTO users (firstname, lastname, email) VALUES(?,?,?)",
[firstname, lastname, email],
(err, results) => {
if(err){
console.log(err);
res.status(500).send("Failed to save data");
}else{
res.status(200).send("User saved succesfully");
}
}
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment