Skip to content

Commit

Permalink
Expose a new semi-public ddp.eventInterface API
Browse files Browse the repository at this point in the history
This new API allows apps that need to monitor DDP events to do so without having to worry about the underlying DDP instance or websocket changing
  • Loading branch information
TheRealNate committed Aug 9, 2021
1 parent 0a0c874 commit 98b3761
Showing 1 changed file with 43 additions and 4 deletions.
47 changes: 43 additions & 4 deletions lib/ddp.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
/**
* DDP.JS 2.1.0
*/

import EventEmitter from 'wolfy87-eventemitter';
import Queue from './queue';
import Socket from './socket';
import { uniqueId } from './utils';

const DDP_VERSION = '1';
const PUBLIC_EVENTS = [
'connected',
'disconnected',
// Subscription messages
'ready',
'nosub',
Expand All @@ -23,13 +21,54 @@ const PUBLIC_EVENTS = [
];
const DEFAULT_RECONNECT_INTERVAL = 10000;

class EventInterface {
constructor() {
this.listeners = {};
PUBLIC_EVENTS.forEach(eventName => {
this.listeners[eventName] = {};
});
}

activate(ddp) {
this.ddp = ddp;
PUBLIC_EVENTS.forEach(eventName => {
this.ddp.addListener(eventName, event => {
this._handleEvent(eventName, event);
});
});
}

_handleEvent(eventName, event) {
for(let func of Object.values(this.listeners[eventName])) {
try {
func(event);
}
catch(e) {
console.error("@meteorrn/core failed to call DDP event handler for " + eventName, e);
}
}
}

on(eventName, func) {
const id = Math.random()+"";
if(!this.listeners[eventName]) throw new Error(`Unsupported event name "${eventName}"`);
this.listeners[eventName][id] = func;
return {remove:() => delete this.listeners[eventName][id]};
}
}

const eventInterface = new EventInterface();

export default class DDP extends EventEmitter {
emit() {
setTimeout(super.emit.bind(this, ...arguments), 0);
}

constructor(options) {
super();

this.eventInterface = eventInterface;
eventInterface.activate(this);

this.status = 'disconnected';

Expand Down

0 comments on commit 98b3761

Please sign in to comment.