import { TypedRequest } from '@apiglobal/typedrequest'; import * as plugins from './dees-comms.plugins'; /** * a comm class for client side communication between workers and tabs. */ export class DeesComms { // sending messages private postChannel = new BroadcastChannel('dees-comms'); public typedrouter = new plugins.typedrequest.TypedRouter(); private subscriptionChannel = new BroadcastChannel('dees-comms'); constructor() { this.subscriptionChannel.onmessage = async (eventArg) => { const message = eventArg.data; console.log(JSON.stringify(message)); const response = await this.typedrouter.routeAndAddResponse(message); if (response) { this.postMessage(response); } }; } /** * creates a typedrequest with this classes postMessage as postMethod */ public createTypedRequest( methodName: T['method'] ): TypedRequest { const typedrequest = new plugins.typedrequest.TypedRequest( async (messageArg) => { this.postMessage(messageArg); }, methodName, this.typedrouter ); return typedrequest; } /** * posts a typedrequestmessage */ public async postMessage( messageArg: T ): Promise { this.postChannel.postMessage(messageArg); } /** * subscribe to messages */ public async createTypedHandler( methodArg: T['method'], handlerFunction: plugins.typedrequest.THandlerFunction ) { this.typedrouter.addTypedHandler(new plugins.typedrequest.TypedHandler(methodArg, handlerFunction)); } }