Skip to content
Prev Previous commit
Next Next commit
Make Kuzzle and Websocket prototypes inherit from EventEmitter
  • Loading branch information
ballinette committed Apr 20, 2017
commit bc8bb638c1eb55788fbd9a5b37274f98acf5830c
68 changes: 20 additions & 48 deletions src/Kuzzle.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ function Kuzzle (host, options, cb) {
if (!(this instanceof Kuzzle)) {
return new Kuzzle(host, options, cb);
}
EventEmitter.call(this);

if (!cb && typeof options === 'function') {
cb = options;
Expand Down Expand Up @@ -264,11 +265,6 @@ function Kuzzle (host, options, cb) {
enumerable: true
});

Object.defineProperty(this, 'eventEmitter', {
value: new EventEmitter(this.eventListeners, this.eventTimeout),
enumerable: true
});

if (!options || !options.connect || options.connect === 'auto') {
this.connect();
} else {
Expand All @@ -293,6 +289,8 @@ function Kuzzle (host, options, cb) {
}
}

Kuzzle.prototype = new EventEmitter();

/**
* Connects to a Kuzzle instance using the provided host name.
* @returns {Object} this
Expand Down Expand Up @@ -320,23 +318,23 @@ Kuzzle.prototype.connect = function () {
self.state = 'connected';
renewAllSubscriptions.call(self);
dequeue.call(self);
self.eventEmitter.emitEvent('connected');
self.emitEvent('connected');

if (self.connectCB) {
self.connectCB(null, self);
}
});

self.network.on('discarded', function (data) {
self.eventEmitter.emitEvent('discarded', data);
self.emitEvent('discarded', data);
});

self.network.onConnectError(function (error) {
var connectionError = new Error('Unable to connect to kuzzle proxy server at "' + self.host + '"');

connectionError.internal = error;
self.state = 'error';
self.eventEmitter.emitEvent('error', connectionError);
self.emitEvent('error', connectionError);

if (self.connectCB) {
self.connectCB(connectionError);
Expand All @@ -354,7 +352,7 @@ Kuzzle.prototype.connect = function () {
self.queuing = true;
}

self.eventEmitter.emitEvent('disconnected');
self.emitEvent('disconnected');
});

self.network.onReconnect(function () {
Expand All @@ -371,7 +369,7 @@ Kuzzle.prototype.connect = function () {
}

// alert listeners
self.eventEmitter.emitEvent('reconnected');
self.emitEvent('reconnected');
};

self.state = 'connected';
Expand All @@ -381,7 +379,7 @@ Kuzzle.prototype.connect = function () {
// shouldn't obtain an error but let's invalidate the token anyway
if (err || !res.valid) {
self.jwtToken = undefined;
self.eventEmitter.emitEvent('jwtTokenExpired');
self.emitEvent('jwtTokenExpired');
}

reconnect();
Expand All @@ -406,20 +404,20 @@ Kuzzle.prototype.setJwtToken = function(token) {
if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {
this.jwtToken = token.result.jwt;
} else {
this.eventEmitter.emitEvent('loginAttempt', {
this.emitEvent('loginAttempt', {
success: false,
error: 'Cannot find a valid JWT token in the following object: ' + JSON.stringify(token)
});

return this;
}
} else {
this.eventEmitter.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});
this.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});
return this;
}

renewAllSubscriptions.call(this);
this.eventEmitter.emitEvent('loginAttempt', {success: true});
this.emitEvent('loginAttempt', {success: true});
return this;
};

Expand Down Expand Up @@ -498,7 +496,7 @@ Kuzzle.prototype.login = function (strategy) {
}
else {
cb && cb(error);
self.eventEmitter.emitEvent('loginAttempt', {success: false, error: error.message});
self.emitEvent('loginAttempt', {success: false, error: error.message});
}
});
};
Expand Down Expand Up @@ -673,7 +671,7 @@ function cleanQueue () {
self.offlineQueue
.splice(0, lastDocumentIndex + 1)
.forEach(function (droppedRequest) {
self.eventEmitter.emitEvent('offlineQueuePop', droppedRequest.query);
self.emitEvent('offlineQueuePop', droppedRequest.query);
});
}
}
Expand All @@ -682,7 +680,7 @@ function cleanQueue () {
self.offlineQueue
.splice(0, self.offlineQueue.length - self.queueMaxSize)
.forEach(function (droppedRequest) {
self.eventEmitter.emitEvent('offlineQueuePop', droppedRequest.query);
self.emitEvent('offlineQueuePop', droppedRequest.query);
});
}
}
Expand Down Expand Up @@ -722,14 +720,14 @@ function emitRequest (request, cb) {

if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {
self.jwtToken = undefined;
self.eventEmitter.emitEvent('jwtTokenExpired', request, cb);
self.emitEvent('jwtTokenExpired', request, cb);
}

if (response.error) {
error = new Error(response.error.message);
Object.assign(error, response.error);
error.status = response.status;
self.eventEmitter.emitEvent('queryError', error, request, cb);
self.emitEvent('queryError', error, request, cb);
}

if (cb) {
Expand All @@ -755,7 +753,7 @@ function dequeue () {
dequeuingProcess = function () {
if (self.offlineQueue.length > 0) {
emitRequest.call(self, self.offlineQueue[0].query, self.offlineQueue[0].cb);
self.eventEmitter.emitEvent('offlineQueuePop', self.offlineQueue.shift());
self.emitEvent('offlineQueuePop', self.offlineQueue.shift());

setTimeout(function () {
dequeuingProcess();
Expand Down Expand Up @@ -836,10 +834,9 @@ Kuzzle.prototype.addListener = function(event, listener) {
throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());
}

return this.eventEmitter.addListener(event, listener);
return EventEmitter.prototype.addListener.call(this, event, listener);
};


/**
* Kuzzle monitors active connections, and ongoing/completed/failed requests.
* This method returns all available statistics from Kuzzle.
Expand Down Expand Up @@ -1329,7 +1326,7 @@ Kuzzle.prototype.query = function (queryArgs, query, options, cb) {
cleanQueue.call(this, object, cb);
if (!self.queueFilter || self.queueFilter(object)) {
self.offlineQueue.push({ts: Date.now(), query: object, cb: cb});
self.eventEmitter.emitEvent('offlineQueuePush', {query: object, cb: cb});
self.emitEvent('offlineQueuePush', {query: object, cb: cb});
}
}
else {
Expand All @@ -1339,31 +1336,6 @@ Kuzzle.prototype.query = function (queryArgs, query, options, cb) {
return self;
};

/**
* Removes all listeners, either from a specific event or from all events
*
* @param {string} event - One of the event described in the Event Handling section of this documentation
* @returns {Kuzzle} this object
*/
Kuzzle.prototype.removeAllListeners = function (event) {
this.eventEmitter.removeAllListeners(event);

return this;
};

/**
* Removes a listener from an event.
*
* @param {string} event - One of the event described in the Event Handling section of this documentation
* @param {string} listenerId - The ID returned by addListener
* @returns {Kuzzle} this object
*/
Kuzzle.prototype.removeListener = function (event, listenerId) {
this.eventEmitter.removeListener(event, listenerId);

return this;
};

/**
* Replays the requests queued during offline mode.
* Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false.
Expand Down
2 changes: 1 addition & 1 deletion src/Room.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ function notificationCallback (data) {

if (data.action === 'jwtTokenExpired') {
this.kuzzle.jwtToken = undefined;
return this.kuzzle.eventEmitter.emitEvent('jwtTokenExpired');
return this.kuzzle.emitEvent('jwtTokenExpired');
}

if (data.controller === 'document' || (data.controller === 'realtime' && data.action === 'publish')) {
Expand Down
19 changes: 17 additions & 2 deletions src/eventEmitter/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
var
uuid = require('uuid');

function EventEmitter(listeners, eventTimeout) {
function EventEmitter(eventTimeout) {
Object.defineProperties(this, {
eventListeners: {
value: listeners || {}
value: {}
},
eventTimeout: {
value: eventTimeout || 200,
Expand Down Expand Up @@ -136,6 +136,21 @@ EventEmitter.prototype.removeListener = function (event, listenerId) {
return self;
};

/**
* Unregisters a callback from a room.
*
* @param {string} roomId
* @param {function} callback
*/
EventEmitter.prototype.off = function (event, callback) {
var listenerId = this.getListener(event, callback);

if (listenerId) {
this.removeListener(event, listenerId);
}
};


/**
* Removes all listeners, either from a specific event or from all events
*
Expand Down
Loading