Advertisement
Gaela

Untitled

Dec 6th, 2021
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const connection = require("./db-config");
  2. const express = require("express");
  3. const app = express();
  4. const port = process.env.PORT || 3000;
  5.  
  6.  
  7.  
  8. app.post("/api/movies", (req, res) => {
  9.   const { title, director, year, color, duration } = req.body;
  10.  
  11.   const { error } = Joi.object({
  12.     title: Joi.string().max(255).required(),
  13.     director: Joi.string().max(255).required(),
  14.     year: Joi.number().integer().min(1888).required(),
  15.     color: Joi.boolean().required(),
  16.     duration: Joi.number().integer().min(1).required(),
  17.   }).validate(
  18.     { title, director, year, color, duration },
  19.     { abortEarly: false }
  20.   );
  21.  
  22.   if (error) {
  23.     res.status(422).json({ validationErrors: error.details });
  24.   } else {
  25.     connection.query(
  26.       "INSERT INTO movies (title, director, year, color, duration) VALUES (?, ?, ?, ?, ?)",
  27.       [title, director, year, color, duration],
  28.       (err, result) => {
  29.         if (err) {
  30.           res.status(500).send("Error saving the movie");
  31.         } else {
  32.           const id = result.insertId;
  33.           const createdMovie = { id, title, director, year, color, duration };
  34.           res.status(201).json(createdMovie);
  35.         }
  36.       }
  37.     );
  38.   }
  39. });
  40.  
  41. app.post("/api/users", (req, res) => {
  42.   const { firstname, lastname, email } = req.body;
  43.   const db = connection.promise();
  44.   let validationErrors = null;
  45.   db.query("SELECT * FROM users WHERE email = ?", [email])
  46.     .then(([result]) => {
  47.       if (result[0]) return Promise.reject("DUPLICATE_EMAIL");
  48.       validationErrors = Joi.object({
  49.         email: Joi.string().email().max(255).required(),
  50.         firstname: Joi.string().max(255).required(),
  51.         lastname: Joi.string().max(255).required(),
  52.         city: Joi.string().allow(null, "").max(255),
  53.         language: Joi.string().allow(null, "").max(255),
  54.       }).validate({ firstname, lastname, email }, { abortEarly: false }).error;
  55.       if (validationErrors) return Promise.reject("INVALID_DATA");
  56.       return db.query(
  57.         "INSERT INTO users (firstname, lastname, email) VALUES (?, ?, ?)",
  58.         [firstname, lastname, email]
  59.       );
  60.     })
  61.     .then(([{ insertId }]) => {
  62.       res.status(201).json({ id: insertId, firstname, lastname, email });
  63.     })
  64.     .catch((err) => {
  65.       console.error(err);
  66.       if (err === "DUPLICATE_EMAIL")
  67.         res.status(409).json({ message: "This email is already used" });
  68.       else if (err === "INVALID_DATA")
  69.         res.status(422).json({ validationErrors });
  70.       else res.status(500).send("Error saving the user");
  71.     });
  72. });
  73. app.put("/api/users/:id", (req, res) => {
  74.   const userId = req.params.id;
  75.   const db = connection.promise();
  76.   let existingUser = null;
  77.   let validationErrors = null;
  78.   Promise.all([
  79.     db.query("SELECT * FROM users WHERE id = ?", [userId]),
  80.     db.query("SELECT * FROM users WHERE email = ? AND id <> ?", [
  81.       req.body.email,
  82.       userId,
  83.     ]),
  84.   ])
  85.     .then(([[[existingUser]], [[otherUserWithEmail]]]) => {
  86.       if (!existingUser) return Promise.reject("RECORD_NOT_FOUND");
  87.       if (otherUserWithEmail) return Promise.reject("DUPLICATE_EMAIL");
  88.       validationErrors = Joi.object({
  89.         email: Joi.string().email().max(255),
  90.         firstname: Joi.string().min(1).max(255),
  91.         lastname: Joi.string().min(1).max(255),
  92.         city: Joi.string().allow(null, "").max(255),
  93.         language: Joi.string().allow(null, "").max(255),
  94.       }).validate(req.body, { abortEarly: false }).error;
  95.       if (validationErrors) return Promise.reject("INVALID_DATA");
  96.       return db.query("UPDATE users SET ? WHERE id = ?", [req.body, userId]);
  97.     })
  98.     .then(() => {
  99.       res.status(200).json({ ...existingUser, ...req.body });
  100.     })
  101.     .catch((err) => {
  102.       console.error(err);
  103.       if (err === "RECORD_NOT_FOUND")
  104.         res.status(404).send(`User with id ${userId} not found.`);
  105.       if (err === "DUPLICATE_EMAIL")
  106.         res.status(409).json({ message: "This email is already used" });
  107.       else if (err === "INVALID_DATA")
  108.         res.status(422).json({ validationErrors });
  109.       else res.status(500).send("Error updating a user");
  110.     });
  111. });
  112.  
  113. app.put("/api/movies/:id", (req, res) => {
  114.   const movieId = req.params.id;
  115.   const db = connection.promise();
  116.   let existingMovie = null;
  117.   let validationErrors = null;
  118.   db.query("SELECT * FROM movies WHERE id = ?", [movieId])
  119.     .then(([results]) => {
  120.       existingMovie = results[0];
  121.       if (!existingMovie) return Promise.reject("RECORD_NOT_FOUND");
  122.       validationErrors = Joi.object({
  123.         title: Joi.string().max(255),
  124.         director: Joi.string().max(255),
  125.         year: Joi.number().integer().min(1888),
  126.         color: Joi.boolean(),
  127.         duration: Joi.number().integer().min(1),
  128.       }).validate(req.body, { abortEarly: false }).error;
  129.       if (validationErrors) return Promise.reject("INVALID_DATA");
  130.       return db.query("UPDATE movies SET ? WHERE id = ?", [req.body, movieId]);
  131.     })
  132.     .then(() => {
  133.       res.status(200).json({ ...existingMovie, ...req.body });
  134.     })
  135.     .catch((err) => {
  136.       console.error(err);
  137.       if (err === "RECORD_NOT_FOUND")
  138.         res.status(404).send(`Movie with id ${movieId} not found.`);
  139.       else if (err === "INVALID_DATA")
  140.         res.status(422).json({ validationErrors });
  141.       else res.status(500).send("Error updating a movie.");
  142.     });
  143. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement