storage.js 1.55 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
var mongoClient = require('mongodb').MongoClient;
var assert = assert = require('assert');

// Connection URL
andreagerino's avatar
andreagerino committed
9
var mongoUrl = 'mongodb://icarus:icarus@localhost:27017/icarus';
andreagerino's avatar
andreagerino committed
10 11 12 13 14 15 16 17 18 19 20 21

//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
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;

andreagerino's avatar
andreagerino committed
41
            if(Object.keys(resource).length>0) {
andreagerino's avatar
andreagerino committed
42 43 44 45 46 47 48 49 50 51 52

                collection.insertOne(resource, function (err, r) {

                    if (err != null) {

                        debug(err);
                        next(err);

                    } else {

                        db.close();
andreagerino's avatar
andreagerino committed
53
                        res.statusCode = 201;
andreagerino's avatar
andreagerino committed
54
                        res.send({"_id":r.insertedId});
andreagerino's avatar
andreagerino committed
55 56 57 58 59 60 61 62 63 64

                    }

                });

            }else{

                var error = new Error("You can't store an empty resource!");
                error.status = 400;

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

            }

        }

    });

});

76
module.exports = router;