Skip to content

Instantly share code, notes, and snippets.

@lifecoder
Created April 14, 2011 21:20
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save lifecoder/920582 to your computer and use it in GitHub Desktop.
Save lifecoder/920582 to your computer and use it in GitHub Desktop.
simple DAO example for nodejs
var mongo = require('mongodb'),
EventEmitter = require('events').EventEmitter;
function Connector(settings) {
settings.port = settings.port || mongo.Connection.DEFAULT_PORT;
this.settings = settings;
this.server = new mongo.Server(settings.host, settings.port);
this.db = new mongo.Db(settings.database, this.server, {native_parser: true});
}
Connector.prototype = new EventEmitter();
Connector.prototype.connect = function() {
var that = this;
this.db.open(function(err, db) {
if (err) return that.emit('error', err);
that.emit('ready', db);
});
}
function CategoryRepository(db) {
this.db = db;
}
CategoryRepository.prototype = new EventEmitter();
CategoryRepository.prototype.initialize = function() {
var that = this;
this.db.collection('categories', function(error, collection) {
that.collection = collection;
that.emit('ready', that);
});
}
CategoryRepository.prototype.findAll = function(callback) {
return this.db.collection('categories', onCollectionReady);
function onCollectionReady(error, collection) {
if (error) return callback(error);
collection.find(onCursorReady);
}
function onCursorReady(error, cursor) {
console.log('onCursorReady');
if (error) return callback(error, null);
cursor.toArray(callback);
}
}
function main() {
var connector = new Connector({server:'localhost', database:'learntrack'});
connector.on('ready', function() {
var repo = new CategoryRepository(connector.db);
repo.on('ready', onRepositoryReady);
return connector.connect(onConnectionOpen);
function onConnectionOpen(err, db) {
console.log('connected');
repo.initialize();
}
function onRepositoryReady(repo) {
repo.findAll(onQueryResult);
}
function onQueryResult(err, items) {
console.log('got results');
console.dir(items);
connector.db.close();
}
}
connector.connect();
}
main();
@eliseosoto
Copy link

What I get from this is that the preferred terminology in Node is "repository" and not "DAO"?

@lifecoder
Copy link
Author

No, I don't know about general preference of nodejs community. I just like it more. It is taken from DDD and has slightly different meaning than DAO.

@yeisoncruz16
Copy link

There is not a preference, it is agnostic to the language.
The above example is a DAO because is close to the storage layer, the repository usually use ORMs or DAO to prepare common queries.
Repository is a layer a little bit far of Storage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment