storage.js 1.5 KB
Newer Older
1 2
var express = require('express');
var router = express.Router();
andreagerino's avatar
andreagerino committed
3
var debug = require('debug')('Icarus:server');
4

andreagerino's avatar
andreagerino committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
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) {
22 23 24 25 26

    res.sendStatus(200);

});

andreagerino's avatar
andreagerino committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
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;

andreagerino's avatar
andreagerino committed
64
                debug(error);
andreagerino's avatar
andreagerino committed
65 66 67 68 69 70 71 72 73 74
                next(error);

            }

        }

    });

});

75
module.exports = router;