mime-chat/src/composables/useIpcMain.ts
2021-06-19 11:25:32 -05:00

88 lines
2 KiB
TypeScript

import { ipcMain, IpcMainInvokeEvent, IpcMainEvent } from "electron";
export class IpcHandler<InputType, ReturnType> implements IIpcHandler<InputType, ReturnType> {
readonly channel: string;
readonly _handlerCallback: IpcHandlerCallback<InputType, ReturnType>;
constructor(options: {
channel: string;
handlerCallback: IpcHandlerCallback<InputType, ReturnType>;
}) {
this.channel = options.channel;
this._handlerCallback = options.handlerCallback;
}
handle() {
console.log(`[IPC] INIT: ${this.channel}`);
this.remove();
ipcMain.handle(this.channel, this._onInvoke);
}
remove() {
ipcMain.removeHandler(this.channel);
}
private _onInvoke = (_e: IpcMainInvokeEvent, payload?: string | null): Promise<Error | ReturnType> => {
return new Promise(async (resolve, reject) => {
console.log(`[IPC] Handle:${this.channel}`);
try {
const params = payload ? JSON.parse(payload) : null;
const res = await this._handlerCallback(params);
resolve(res as unknown as ReturnType);
} catch(e) {
console.log(`[IPC] Error:${this.channel}`);
reject(e);
}
});
}
}
export class IpcListener<InputType> implements IIpcListener<InputType> {
readonly channel: string;
readonly _listenerCallback: IpcListenerCallback<InputType>;
constructor(options: {
channel: string;
listenerCallback: IpcListenerCallback<InputType>;
}) {
this.channel = options.channel;
this._listenerCallback = options.listenerCallback;
}
listen() {
console.log(`[IPC] Init: ${this.channel}`);
this.remove();
ipcMain.on(this.channel, this._onPost);
}
remove() {
ipcMain.removeAllListeners(this.channel);
}
private _onPost = (_e: IpcMainEvent, payload?: string | null): void => {
console.log(`[IPC] Post: ${this.channel}`);
const params = payload ? JSON.parse(payload) : null;
this._listenerCallback(params);
}
}