From e67c00c4dea4a11330c052ae389a215404c20233 Mon Sep 17 00:00:00 2001 From: andreagerino Date: Fri, 27 Nov 2015 21:25:09 +0100 Subject: [PATCH] ... --- routes/storage.js | 86 +++++++++++++++++------------------------------ 1 file changed, 30 insertions(+), 56 deletions(-) diff --git a/routes/storage.js b/routes/storage.js index a5b5a18..088b582 100644 --- a/routes/storage.js +++ b/routes/storage.js @@ -11,19 +11,22 @@ var assert = assert = require('assert'); var mongoUrl = 'mongodb://icarus:icarus@localhost:27017/icarus'; //Use connect method to test the connection to the Server -var mongoDb; +var icarusDb; mongoClient.connect(mongoUrl, function(err, db) { assert.equal(null, err, err); debug("Connected to MongoDB database: "+db.databaseName); - mongoDb = db; + icarusDb = db; }); router.get('/:resource_id', function(req, res, next) { - mongoClient.connect(mongoUrl, function(err, db) { + var collection = icarusDb.collection('resources'); + + var _id = new ObjectID(req.params.resource_id); + collection.find({"_id":_id}).limit(1).next(function(err, doc){ if(err!=null){ @@ -32,31 +35,15 @@ router.get('/:resource_id', function(req, res, next) { }else{ - var collection = db.collection('resources'); - - var _id = new ObjectID(req.params.resource_id); - collection.find({"_id":_id}).limit(1).next(function(err, doc){ - - if(err!=null){ - - debug(err); - next(err); - - }else{ - - if(doc==undefined){ - - res.sendStatus(404); + if(doc==undefined){ - }else{ + res.sendStatus(404); - res.send(doc); - - } + }else{ - } + res.send(doc); - }); + } } @@ -66,50 +53,37 @@ router.get('/:resource_id', function(req, res, next) { router.post('/', function(req, res, next){ - mongoClient.connect(mongoUrl, function(err, db) { - - if(err!=null){ - - debug(err); - next(err); - - }else{ - - var collection = db.collection('resources'); - var resource = req.body; - - if(Object.keys(resource).length>0) { - - collection.insertOne(resource, function (err, r) { + var collection = icarusDb.collection('resources'); + var resource = req.body; - if (err != null) { + if(Object.keys(resource).length>0) { - debug(err); - next(err); + collection.insertOne(resource, function (err, r) { - } else { + if (err != null) { - res.statusCode = 201; - res.send({"_id":r.insertedId}); + debug(err); + next(err); - } + } else { - }); + res.statusCode = 201; + res.send({"_id":r.insertedId}); - }else{ + } - var error = new Error("You can't store an empty resource!"); - error.status = 400; + }); - debug(error); - next(error); + }else{ - } + var error = new Error("You can't store an empty resource!"); + error.status = 400; - } + debug(error); + next(error); - }); + } -}); +} module.exports = router; -- 2.18.1