dees-comms/ts/dees-comms.classes.deescomms.ts
2020-12-21 12:07:34 +00:00

67 lines
2.0 KiB
TypeScript

import { TypedRequest } from '@apiglobal/typedrequest';
import * as plugins from './dees-comms.plugins';
let BroadcastChannel = globalThis.BroadcastChannel;
if (!BroadcastChannel) {
BroadcastChannel = plugins.BroadCastChannelPolyfill as any;
}
/**
* 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();
public typedtarget = new plugins.typedrequest.TypedTarget({
postMethodWithTypedRouter: async (messageArg) => {
this.postMessage(messageArg);
},
typedRouterRef: this.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<T extends plugins.typedrequestInterfaces.ITypedRequest>(
methodName: T['method']
): TypedRequest<T> {
const typedrequest = new plugins.typedrequest.TypedRequest(this.typedtarget, methodName);
return typedrequest;
}
/**
* posts a typedrequestmessage
*/
public async postMessage<T = plugins.typedrequestInterfaces.ITypedRequest>(
messageArg: T
): Promise<void> {
this.postChannel.postMessage(messageArg);
}
/**
* subscribe to messages
*/
public async createTypedHandler<T extends plugins.typedrequestInterfaces.ITypedRequest>(
methodArg: T['method'],
handlerFunction: plugins.typedrequest.THandlerFunction<T>
) {
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<T>(methodArg, handlerFunction)
);
}
}