Skip to content

Instantly share code, notes, and snippets.

@vmalep
Created November 16, 2021 21:51
Show Gist options
  • Save vmalep/f74b83c95e9f671ccf5332cc23ac6e11 to your computer and use it in GitHub Desktop.
Save vmalep/f74b83c95e9f671ccf5332cc23ac6e11 to your computer and use it in GitHub Desktop.
app.post('/api/movies', (req, res) => {
const { title, director, year, color, duration } = req.body
connection.promise().query(
'INSERT INTO movies(title, director, year, color, duration) VALUES (?, ?, ?, ?, ?)',
[title, director, year, color, duration])
.then(result => {
const id = result.insertId
const createdMovie = { id, title, director, year, color, duration }
res.status(201).json(createdMovie)
res.redirect('Movie successfully saved')
})
.catch(err => res.status(500).send('Error saving the movie'))
})
app.put('/api/movies/:id', (req, res) => {
const movieId = req.params.id;
const db = connection.promise();
let existingMovie = null;
db.query('SELECT * FROM movies WHERE id = ?', [movieId])
.then(([results]) => {
existingMovie = results[0];
if (!existingMovie) return Promise.reject('RECORD_NOT_FOUND');
return db.query('UPDATE movies SET ? WHERE id = ?', [req.body, movieId]);
})
.then(() => {
res.status(200).json({ ...existingMovie, ...req.body });
})
.catch((err) => {
console.error(err);
if (err === 'RECORD_NOT_FOUND')
res.status(404).send(`movie not found.`);
else res.status(500).send('Error updating a movie');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment