Skip to content

Commit

Permalink
add onConnectionSetup event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
au-re committed Oct 26, 2024
1 parent e8ce245 commit 516b703
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/guest.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { extractMethods, isWorker } from "./helpers";
import { registerLocalMethods, registerRemoteMethods } from "./rpc";
import { actions, events, IConnection, ISchema } from "./types";
import { actions, EventHandlers, events, IConnection, ISchema } from "./types";

const REQUEST_INTERVAL = 10;
const TIMEOUT_INTERVAL = 3000;

let interval: any = null;
let connected = false;

function connect(schema: ISchema = {}): Promise<IConnection> {
function connect(schema: ISchema = {}, eventHandlers?: EventHandlers): Promise<IConnection> {
return new Promise((resolve, reject) => {
const localMethods = extractMethods(schema);

// on handshake response
function handleHandshakeResponse(event: any) {
async function handleHandshakeResponse(event: any) {
if (event.data.action !== actions.HANDSHAKE_REPLY) return;

// register local methods
Expand All @@ -27,6 +27,8 @@ function connect(schema: ISchema = {}): Promise<IConnection> {
event
);

await eventHandlers?.onConnectionSetup?.(remote);

// close the connection and all listeners when called
const close = () => {
self.removeEventListener(events.MESSAGE, handleHandshakeResponse);
Expand Down
1 change: 1 addition & 0 deletions src/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ function connect(guest: HTMLIFrameElement | Worker, schema: ISchema = {}): Promi
listeners.removeEventListener(events.MESSAGE, handleHandshake);
unregisterRemote();
unregisterLocal();
if (guestIsWorker) (guest as Worker).terminate();
};

// resolve connection object
Expand Down
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,7 @@ export interface IRPCResolvePayload {
callName: string;
connectionID: string;
}

export interface EventHandlers {
onConnectionSetup: (remote: ISchema) => Promise<void>;
}

0 comments on commit 516b703

Please sign in to comment.