Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. var express = require("express");
  2. var bodyParser = require("body-parser");
  3.  
  4. var app = express();
  5.  
  6. app.use(bodyParser.json());
  7.  
  8. var port = process.env.PORT || 8080;
  9.  
  10. var contacts = [{
  11. name: "peter",
  12. phone: "123456",
  13. email: "peter@peter.com"
  14. }, {
  15. name: "paul",
  16. phone: "3333",
  17. email: "paul@paul.com"
  18. }];
  19.  
  20. // GET /contacts/
  21.  
  22. app.get("/contacts", (req,res)=>{
  23. res.send(contacts);
  24. });
  25.  
  26.  
  27. // POST /contacts/
  28.  
  29. app.post("/contacts", (req,res)=>{
  30.  
  31. var newContact = req.body;
  32.  
  33. contacts.push(newContact)
  34.  
  35. res.sendStatus(201);
  36. });
  37.  
  38.  
  39. // DELETE /contacts/
  40.  
  41. app.delete("/contacts", (req,res)=>{
  42.  
  43. contacts = [];
  44.  
  45. res.sendStatus(200);
  46. });
  47.  
  48.  
  49. // GET /contacts/peter
  50.  
  51. app.get("/contacts/:name", (req,res)=>{
  52.  
  53. var name = req.params.name;
  54.  
  55. var filteredContacts = contacts.filter((c) =>{
  56. return c.name == name;
  57. })
  58.  
  59. if (filteredContacts.length >= 1){
  60. res.send(filteredContacts[0]);
  61. }else{
  62. res.sendStatus(404);
  63. }
  64.  
  65. });
  66.  
  67.  
  68. // PUT /contacts/peter
  69.  
  70. app.put("/contacts/:name", (req,res)=>{
  71.  
  72. var name = req.params.name;
  73. var updatedContact = req.body;
  74. var found = false;
  75.  
  76. var updatedContacts = contacts.map((c) =>{
  77.  
  78. if(c.name == name){
  79. found = true;
  80. return updatedContact;
  81. }else{
  82. return c;
  83. }
  84.  
  85. });
  86.  
  87. if (found == false){
  88. res.sendStatus(404);
  89. }else{
  90. contacts = updatedContacts;
  91. res.sendStatus(200);
  92. }
  93.  
  94. });
  95.  
  96.  
  97. // DELETE /contacts/peter
  98.  
  99. app.delete("/contacts/:name", (req,res)=>{
  100.  
  101. var name = req.params.name;
  102. var found = false;
  103.  
  104. var updatedContacts = contacts.filter((c) =>{
  105.  
  106. if(c.name == name)
  107. found = true;
  108.  
  109. return c.name != name;
  110. });
  111.  
  112. if (found == false){
  113. res.sendStatus(404);
  114. }else{
  115. contacts = updatedContacts;
  116. res.sendStatus(200);
  117. }
  118.  
  119. });
  120.  
  121.  
  122.  
  123. app.listen(port, () => {
  124. console.log("Super server ready on port " + port);
  125. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement