MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come utilizzare gli eventi mantiene la logica mongodb fuori dai gestori delle richieste node.js

Ecco la soluzione che ho trovato.

Ho usato mongojs che semplifica notevolmente l'interfaccia mongodb, a scapito della flessibilità nella configurazione, ma nasconde i callback annidati richiesti dal driver mongodb. Inoltre, rende la sintassi molto più simile al client mongo.

Quindi avvolgo l'oggetto Risposta HTTP in una chiusura e passo questa chiusura al metodo di query mongodb in un callback.

var MongoProvider = require('./MongoProvider');
MongoProvider.setCollection('things');

exports.index = function(request, response){
    function sendResponse(err, data) {
        if (err) { 
            response.send(500, err);
        }    
        response.send(data);
    };

    MongoProvider.fetchAll(things, sendResponse);
};

È ancora essenzialmente semplicemente passare l'oggetto risposta al provider di database, ma avvolgendolo in una chiusura che sa come gestire la risposta, mantiene quella logica fuori dal mio modulo di database.

Un leggero miglioramento consiste nell'utilizzare una funzione per creare una chiusura del gestore di risposta al di fuori del gestore della mia richiesta:

function makeSendResponse(response){
    return function sendResponse(err, data) {
        if (err) {
            console.warn(err);
            response.send(500, {error: err});
            return;
        }

        response.send(data);
    };
}

Quindi ora il mio gestore delle richieste ha questo aspetto:

exports.index = function(request, response) {
    response.send(makeSendResponse(response));
}

E il mio MongoProvider si presenta così:

var mongojs = require('mongojs');

MongoProvider = function(config) {
this.configure(config);
    this.db = mongojs.connect(this.url, this.collections);
}

MongoProvider.prototype.configure = function(config) {
    this.url = config.host + "/" + config.name;
    this.collections = config.collections;
}

MongoProvider.prototype.connect = function(url, collections) {
    return mongojs.connect(this.url, this.collections);
}

MongoProvider.prototype.fetchAll = function fetchAll(collection, callback) {
    this.db(collection).find(callback);
}

MongoProvider.prototype.fetchById = function fetchById(id, collection, callback) {
    var objectId = collection.db.bson_serializer.ObjectID.createFromHexString(id.toString());

    this.db(collection).findOne({ "_id": objectId }, callback);
}

MongoProvider.prototype.fetchMatches = function fetchMatches(json, collection, callback) {
    this.db(collection).find(Json.parse(json), callback);
}

module.exports = MongoProvider;

Posso anche estendere MongoProvider per raccolte specifiche per semplificare l'API ed eseguire ulteriori convalide:

ThingsProvider = function(config) {
    this.collection = 'things';
    this.mongoProvider = new MongoProvider(config);
    things = mongoProvider.db.collection('things');
}

ThingsProvider.prototype.fetchAll = function(callback) {
    things.fetchAll(callback);
}

//etc...

module.exports = ThingsProvider;