diff --git a/routes/storage.js b/routes/storage.js index 2fc3edf850355511aceb9d7a55e6be391189fb87..b3f4c797815429ee06b754f96c17dd5787926cc8 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;