Skip to content

Custom Driver

Sometimes, the built-in signaling drivers may not fit your specific use case or requirements. In such cases, you can implement your own custom signaling driver by adhering to the following interface:

import { Driver } from 'peerix';

class MyDriver extends Driver {
  async subscribe(namespace, handler) {
    // implement subscription logic for the given namespace and handler
  }
  async unsubscribe(namespace, handler) {
    // implement unsubscription logic for the given namespace and handler
  }
  async dispatch(namespace, message) {
    // implement dispatch logic for the given namespace and message
  }
}

This driver interface allows you to integrate Peerix with any signaling mechanism you prefer, such as WebSocket transport.

const driver = new CustomDriver();

To better illustrate how to implement a custom signaling driver, here is an example of a minimal in-memory driver that can be used for testing purposes:

// Minimal in-memory signaling driver
class MemoryDriver extends Driver {
  constructor() {
    super();
    this.handlers = new Map();
  }
  subscribe(namespace, handler) {
    const k = namespace.join(':');
    if (!this.handlers.has(k)) {
      this.handlers.set(k, new Set());
    }
    this.handlers.get(k).add(handler);
  }
  unsubscribe(namespace, handler) {
    const k = namespace.join(':');
    this.handlers.get(k)?.delete(handler);
  }
  dispatch(namespace, message) {
    const k = namespace.join(':');
    if (!this.handlers.has(k)) return;
    for (const handler of this.handlers.get(k)) {
      setTimeout(() => handler(message), 0);
    }
  }
}