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@localhost:27017/icarus'; //Use connect method to test the connection to the Server var mongoDb; mongoClient.connect(mongoUrl, function(err, db) { assert.equal(null, err, err); debug("Connected to MongoDB database: "+db.databaseName); mongoDb = db; }); router.get('/:resource_id', function(req, res, next) { mongoClient.connect(mongoUrl, function(err, db) { if(err!=null){ debug(err); next(err); }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); }else{ res.send(doc); } } }); } }); }); 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) { 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); } } }); }); module.exports = router;