Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require("express");
  2. var path = require("path");
  3. var bodyParser = require("body-parser");
  4. var mongodb = require("mongodb");
  5. var ObjectID = mongodb.ObjectID;
  6.  
  7. var CONTACTS_COLLECTION = "contacts";
  8.  
  9. var app = express();
  10. app.use(express.static(__dirname + "/public"));
  11. app.use(bodyParser.json());
  12.  
  13. // Create a database variable outside of the database connection callback to reuse the connection pool in your app.
  14. var db;
  15.  
  16. // Connect to the database before starting the application server.
  17. mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
  18.   if (err) {
  19.     console.log(err);
  20.     process.exit(1);
  21.   }
  22.  
  23.   // Save database object from the callback for reuse.
  24.   db = database;
  25.   console.log("Database connection ready");
  26.  
  27.   // Initialize the app.
  28.   var server = app.listen(process.env.PORT || 8080, function () {
  29.     var port = server.address().port;
  30.     console.log("App now running on port", port);
  31.   });
  32. });
  33.  
  34. // CONTACTS API ROUTES BELOW
  35.  
  36. // Generic error handler used by all endpoints.
  37. function handleError(res, reason, message, code) {
  38.   console.log("ERROR: " + reason);
  39.   res.status(code || 500).json({"error": message});
  40. }
  41.  
  42. /*  "/contacts"
  43.  *    GET: finds all contacts
  44.  *    POST: creates a new contact
  45.  */
  46.  
  47. app.get("/contacts", function(req, res) {
  48.   db.collection(CONTACTS_COLLECTION).find({}).toArray(function(err, docs) {
  49.     if (err) {
  50.       handleError(res, err.message, "Failed to get contacts.");
  51.     } else {
  52.       res.status(200).json(docs);
  53.     }
  54.   });
  55. });
  56.  
  57. app.post("/contacts", function(req, res) {
  58.   var newContact = req.body;
  59.   newContact.createDate = new Date();
  60.  
  61.   if (!(req.body.firstName || req.body.lastName)) {
  62.     handleError(res, "Invalid user input", "Must provide a first or last name.", 400);
  63.   }
  64.  
  65.   db.collection(CONTACTS_COLLECTION).insertOne(newContact, function(err, doc) {
  66.     if (err) {
  67.       handleError(res, err.message, "Failed to create new contact.");
  68.     } else {
  69.       res.status(201).json(doc.ops[0]);
  70.     }
  71.   });
  72. });
  73.  
  74. /*  "/contacts/:id"
  75.  *    GET: find contact by id
  76.  *    PUT: update contact by id
  77.  *    DELETE: deletes contact by id
  78.  */
  79.  
  80. app.get("/contacts/:id", function(req, res) {
  81.   db.collection(CONTACTS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
  82.     if (err) {
  83.       handleError(res, err.message, "Failed to get contact");
  84.     } else {
  85.       res.status(200).json(doc);
  86.     }
  87.   });
  88. });
  89.  
  90. app.put("/contacts/:id", function(req, res) {
  91.   var updateDoc = req.body;
  92.   delete updateDoc._id;
  93.  
  94.   db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
  95.     if (err) {
  96.       handleError(res, err.message, "Failed to update contact");
  97.     } else {
  98.       res.status(204).end();
  99.     }
  100.   });
  101. });
  102.  
  103. app.delete("/contacts/:id", function(req, res) {
  104.   db.collection(CONTACTS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
  105.     if (err) {
  106.       handleError(res, err.message, "Failed to delete contact");
  107.     } else {
  108.       res.status(204).end();
  109.     }
  110.   });
  111. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement