SHARE
TWEET

backend

a guest Jul 17th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require("dotenv").config();
  2. const express = require("express");
  3. const morgan = require("morgan");
  4. const app = express();
  5.  
  6. const bodyParser = require("body-parser");
  7. app.use(bodyParser.json());
  8.  
  9. const cors = require("cors");
  10. app.use(cors());
  11.  
  12. const Person = require("./models/person");
  13.  
  14. app.use(express.static("build"));
  15.  
  16. morgan.token("postData", function(req, res) {
  17.   return JSON.stringify(req.body);
  18. });
  19.  
  20. app.use(
  21.   morgan(
  22.     ":method :url :status :res[content-length] - :response-time ms  :postData"
  23.   )
  24. );
  25.  
  26. let persons = [];
  27.  
  28. app.get("/", (req, res) => {
  29.   res.send("<h1>Tere!</h1>");
  30. });
  31.  
  32. // app.get("/persons/:id", (req, res) => {
  33. //   Person.findById(req.params.id).then(person => {
  34. //     res.json(person.toJSON());
  35. //   });
  36. // });
  37.  
  38. app.get("/info", (req, res) => {
  39.   res.write(`<p>Phonebook has info for ${persons.length} people</p>`);
  40.   res.end();
  41. });
  42.  
  43. app.get("/persons", (req, res) => {
  44.   Person.find({}).then(persons => {
  45.     res.json(persons.map(person => person.toJSON()));
  46.   });
  47. });
  48.  
  49. app.get("/persons/:id", (req, res, next) => {
  50.   Person.findById(req.params.id)
  51.     .then(person => {
  52.       if (person) {
  53.         res.json(person.toJSON());
  54.       } else {
  55.         res.status(404).end();
  56.       }
  57.     })
  58.     .catch(error => next(error));
  59. });
  60.  
  61. const generateId = () => {
  62.   const random = Math.floor(Math.random() * 99999);
  63.   return random;
  64. };
  65.  
  66. app.post("/persons", (req, res, next) => {
  67.   const body = req.body;
  68.  
  69.   // if (!body.name) {
  70.   //   return res.status(400).json({
  71.   //     error: "name missing"
  72.   //   });
  73.   // }
  74.   // if (!body.number) {
  75.   //   return res.status(400).json({
  76.   //     error: "number missing"
  77.   //   });
  78.   // }
  79.  
  80.   const person = new Person({
  81.     name: body.name,
  82.     number: body.number,
  83.     id: generateId()
  84.   });
  85.   const checkNames = persons.map(person => person.name).includes(person.name);
  86.  
  87.   if (checkNames === true) {
  88.     return res.status(406).json({
  89.       error: "name must be unique"
  90.     });
  91.   } else {
  92.     person
  93.       .save()
  94.       .then(savedPerson => {
  95.         res.json(savedPerson.toJSON());
  96.       })
  97.       .catch(error => console.log(error.message));
  98.   }
  99. });
  100.  
  101. app.put("/persons/:id", (request, response, next) => {
  102.   const body = request.body;
  103.  
  104.   const person = {
  105.     name: body.name,
  106.     number: body.number
  107.   };
  108.  
  109.   Person.findByIdAndUpdate(request.params.id, person, { new: true })
  110.     .then(updatedPerson => {
  111.       response.json(updatedPerson.toJSON());
  112.     })
  113.     .catch(error => next(error));
  114. });
  115.  
  116. app.delete("/persons/:id", (req, res, next) => {
  117.   Person.findByIdAndRemove(req.params.id)
  118.     .then(result => {
  119.       res.status(204).end();
  120.     })
  121.     .catch(error => next(error));
  122. });
  123.  
  124. const unknownEndpoint = (request, response) => {
  125.   response.status(404).send({ error: "unknown endpoint" });
  126. };
  127.  
  128. app.use(unknownEndpoint);
  129.  
  130. const errorHandler = (error, request, response, next) => {
  131.   console.error(error.message);
  132.  
  133.   if (error.name === "CastError" && error.kind == "ObjectId") {
  134.     return response.status(400).send({ error: "malformatted id" });
  135.   } else if (error.name === "ValidationError") {
  136.     return response.status(400).json({ error: error.message });
  137.   }
  138.  
  139.   next(error);
  140. };
  141.  
  142. app.use(errorHandler);
  143.  
  144. const PORT = process.env.PORT;
  145. app.listen(PORT, () => {
  146.   console.log(`Server running on port ${PORT}`);
  147. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top