Skip to content
Browse files

emit state changes on connection

  • Loading branch information...
1 parent e38412b commit 1a7027cf09a59e653e366ab43338ef0aeec621ef @aheckmann aheckmann committed
Showing with 24 additions and 1 deletion.
  1. +24 −1 lib/connection.js
View
25 lib/connection.js
@@ -17,6 +17,16 @@ var url = require('url')
var rgxProtocol = /^(?:.)+:\/\//;
/**
+ * Connection states
+ */
+
+var STATES = Connection.STATES = Object.create(null);
+STATES['0'] = 'disconnected';
+STATES['1'] = 'connected';
+STATES['2'] = 'connecting';
+STATES['3'] = 'disconnecting';
+
+/**
* Connection constructor. For practical reasons, a Connection equals a Db
*
* @param {Mongoose} mongoose base
@@ -27,6 +37,7 @@ function Connection (base) {
this.base = base;
this.collections = {};
this.models = {};
+ this._readyState = 0;
};
/**
@@ -42,10 +53,22 @@ Connection.prototype.__proto__ = EventEmitter.prototype;
* 2 = Connecting
* 3 = Disconnecting
*
+ * Each state change emits its associated event name.
+ *
* @api public
*/
-Connection.prototype.readyState = 0;
+Object.defineProperty(Connection.prototype, 'readyState', {
+ get: function(){ return this._readyState; }
+ , set: function (val) {
+ if (!(val in STATES)) {
+ throw new Error('invalid connection state: ' + val);
+ }
+
+ this._readyState = val;
+ this.emit(STATES[val]);
+ }
+});
/**
* A hash of the collections associated with this connection

0 comments on commit 1a7027c

Please sign in to comment.
Something went wrong with that request. Please try again.