dees-comms/ts/dees-comms.classes.deescomms.ts

67 lines
2.0 KiB
TypeScript
Raw Normal View History

2020-10-06 15:56:00 +00:00
import { TypedRequest } from '@apiglobal/typedrequest';
import * as plugins from './dees-comms.plugins';
2022-01-28 16:40:12 +00:00
let BroadcastChannel = globalThis.BroadcastChannel;
if (!BroadcastChannel) {
BroadcastChannel = plugins.BroadCastChannelPolyfill as any;
}
2020-10-06 15:56:00 +00:00
/**
* a comm class for client side communication between workers and tabs.
*/
export class DeesComms {
// sending messages
private postChannel = new BroadcastChannel('dees-comms');
2020-10-06 17:18:20 +00:00
public typedrouter = new plugins.typedrequest.TypedRouter();
2020-12-21 12:07:18 +00:00
public typedtarget = new plugins.typedrequest.TypedTarget({
postMethodWithTypedRouter: async (messageArg) => {
this.postMessage(messageArg);
},
2020-12-21 12:07:34 +00:00
typedRouterRef: this.typedrouter,
});
2020-10-06 17:18:20 +00:00
2020-10-06 15:56:00 +00:00
private subscriptionChannel = new BroadcastChannel('dees-comms');
constructor() {
2020-10-06 21:49:03 +00:00
this.subscriptionChannel.onmessage = async (eventArg) => {
2020-10-06 15:56:00 +00:00
const message = eventArg.data;
2020-10-06 17:18:20 +00:00
console.log(JSON.stringify(message));
2020-10-06 21:49:03 +00:00
const response = await this.typedrouter.routeAndAddResponse(message);
if (response) {
this.postMessage(response);
}
2020-10-06 15:56:00 +00:00
};
}
/**
* creates a typedrequest with this classes postMessage as postMethod
*/
public createTypedRequest<T extends plugins.typedrequestInterfaces.ITypedRequest>(
methodName: T['method']
): TypedRequest<T> {
2020-12-21 12:07:34 +00:00
const typedrequest = new plugins.typedrequest.TypedRequest(this.typedtarget, methodName);
2020-10-06 15:56:00 +00:00
return typedrequest;
}
/**
* posts a typedrequestmessage
*/
public async postMessage<T = plugins.typedrequestInterfaces.ITypedRequest>(
messageArg: T
): Promise<void> {
this.postChannel.postMessage(messageArg);
}
/**
* subscribe to messages
*/
2020-10-06 17:18:20 +00:00
public async createTypedHandler<T extends plugins.typedrequestInterfaces.ITypedRequest>(
methodArg: T['method'],
handlerFunction: plugins.typedrequest.THandlerFunction<T>
) {
2020-12-21 12:07:34 +00:00
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<T>(methodArg, handlerFunction)
);
2020-10-06 17:18:20 +00:00
}
2020-10-06 15:56:00 +00:00
}