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';
2022-03-25 13:17:13 +00:00
import * as plugins from './dees-comms.plugins.js';
2020-10-06 15:56:00 +00:00
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 {
2022-03-29 11:14:10 +00:00
private broadcastChannel = new BroadcastChannel('dees-comms');
2020-10-06 15:56:00 +00:00
// sending messages
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
2022-03-29 08:01:50 +00:00
// receiving messages
2020-10-06 15:56:00 +00:00
constructor() {
2022-03-29 11:14:10 +00:00
this.broadcastChannel.onmessage = async (eventArg) => {
2022-03-29 08:01:50 +00:00
const message = (eventArg as any).method ? eventArg : 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> {
2022-03-29 11:14:10 +00:00
this.broadcastChannel.postMessage(messageArg);
2020-10-06 15:56:00 +00:00
}
/**
* 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
}