message-bridge

Bridges class function calls between two contexes(workers) with messages.

Usage no npm install needed!

<script type="module">
  import messageBridge from 'https://cdn.skypack.dev/message-bridge';
</script>

README

message-bridge

Bridges class function calls between two contexes(workers) with messages.

Install

npm install --save message-bridge
Also contains an amd bundle you can use with systemjs and requirejs.

Usage

I built this library for communication with a web worker.
Let say we want to implement this communication to the web worker.

// The service that runs on the worker.
class Service {
    public getTrue(): boolean {
        return true; 
    }

    public addAsync(a: number, b: number): Promise<number> {
        return new Promise(resolve => { setTimeout(() => resolve(a + b), 1); });
    }
}

// Create the bridge interface (return promise for sync functions).
interface ServiceBridge {
    getTrue(): Promise<boolean>;
    addAsync(a: number, b: number): Promise<number>;
}

let channel = /* Find a way to create your channel (MessageChannel or just use the worker itself) */;

// At your main program:
let servicePromise: Promise<ServiceBridge> = ServiceToMessageBridge.create(channel.port1);

// At the worker:
let service = new Service();
let bridge2 = MessageToServiceBridge.create(service, channel.port2);

// Then, at your main program:
let serviceBridge = await servicePromise;
let result = await serviceBridge.getTrue();
let sum = await serviceBridge.addAsync(4,9);