var express = require('express'); var router = express.Router(); var debug = require('debug')('Icarus:server'); var mongoClient = require('mongodb').MongoClient; var ObjectID = require('mongodb').ObjectID; var assert = assert = require('assert'); // Connection URL var mongoUrl = 'mongodb://icarus:icarus@webdev.ewlab.di.unimi.it:27017/icarus'; //Connect to the server and intialise the pool var icarusDb; mongoClient.connect(mongoUrl, function(err, db) { assert.equal(null, err, err); debug("Connected to MongoDB database: "+db.databaseName); icarusDb = db; }); router.get('/:resource_id', function(req, res, next) { 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){ debug(err); next(err); }else{ if(doc==undefined){ res.sendStatus(404); }else{ res.send(doc); } } }); }); router.post('/', function(req, res, next){ var collection = icarusDb.collection('resources'); var resource = req.body; if(Object.keys(resource).length>0) { var timestampContainer = getTimestampContainer(resource); if(timestampContainer!=undefined){ preprocessTimestampContainer(timestampContainer); } collection.insertOne(resource, function (err, r) { if (err != null) { 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); } }); function getTimestampContainer(arg){ if(arg['timestamp']!=undefined&&(arg['timestamp']['utc']!=undefined)||arg['timestamp']['user']!=undefined) return arg['timestamp']; return undefined; } function preprocessTimestampContainer(container){ var utcSeconds = container['utc']; var userSeconds = container['user']; if(utcSeconds!=undefined){ var utcMsec = utcSeconds * 1000; container['utc'] = new Date(utcMsec); } if(userSeconds!=undefined){ var userMsec = userSeconds * 1000; container['user'] = new Date(userMsec); } } module.exports = router;