From ba06ea2c6c979b51c63a0c128c5d07b2ebeaeb25 Mon Sep 17 00:00:00 2001 From: andreagerino Date: Fri, 27 Nov 2015 18:35:09 +0100 Subject: [PATCH] ... --- routes/storage.js | 67 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/routes/storage.js b/routes/storage.js index 2fc3edf..b3f4c79 100644 --- a/routes/storage.js +++ b/routes/storage.js @@ -1,10 +1,75 @@ var express = require('express'); var router = express.Router(); +var debug = require('debug')('Icarus:server'); -router.get('/', function(req, res, next) { +var mongoClient = require('mongodb').MongoClient; +var assert = assert = require('assert'); + +// Connection URL +var mongoUrl = 'mongodb://icarus:icarus@webdev.ewlab.di.unimi.it:27017/icarus'; + +//Use connect method to test the connection to the Server +mongoClient.connect(mongoUrl, function(err, db) { + + assert.equal(null, err, err); + debug("Connected to MongoDB database: "+db.databaseName); + + db.close(); + +}); + +router.get('/:resource_id', function(req, res, next) { res.sendStatus(200); }); +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)>0) { + + collection.insertOne(resource, function (err, r) { + + if (err != null) { + + debug(err); + next(err); + + } else { + + db.close(); + res.sendStatus(201); + + } + + }); + + }else{ + + var error = new Error("You can't store an empty resource!"); + error.status = 400; + + debug(err); + next(error); + + } + + } + + }); + +}); + module.exports = router; -- 2.18.1