상세 컨텐츠

본문 제목

IPCServiceBase

code/electron.js

by goldtagworks 2024. 7. 10. 21:44

본문

반응형

이 클래스를 베이스로 하면 상속 받은 클래스들에선 따로 Handle 를 등록하지 않아 ipc 가 호출되면서 클래스에 함수를 타게 된다.

메인쪽 코드는 가벼워졌는데, 렌더러쪽은 여전히 귀찮다.

 

// electron/nodejs
import Electron, { ipcMain } from 'electron';

// platform
import { ServiceBase } from '@main/platform/serviceBase';

// logger
import { getLogger } from '@main/frameworks/logger';
const logger = getLogger('event-bus');

export interface IPCParams {
    sender: Electron.WebContents;
    ipcParams?: any;
}

/**
 * ServiceBase class
 */
export abstract class IPCServiceBase extends ServiceBase {
    /** 수행할 이벤트 이름 */
    protected _channel?: string;

    /**
     * 생성자
     * @param channel - .
     */
    constructor(channel: string) {
        super();

        this._channel = channel;
    }

    /** dispose */
    public async dispose(): Promise<void> {
        if (this._channel) {
            ipcMain.removeListener(this._channel, this._ipcHandle);
        }
    }

    /**
     * IPC로 전달받은 액션을 찾아 해당 함수를 실행한다.
     * - this를 넘기기 위해서는 super 후에 해야한다.
     * @param _this - .
     */
    protected _ipcListener(_this: any): void {
        if (this._channel) {
            // IPC 이벤트 설정
            ipcMain.handle(this._channel, this._ipcHandle);
        }
    }

    /**
     *
     * @param event .
     * @param callFuncName .
     * @param ipcParams .
     * @returns .
     */
    protected _ipcHandle = async (event: any, callFuncName: string, ipcParams?: any): Promise<any> => {
        try {
            // api 호출
            return await this.constructor.prototype[callFuncName]({
                sender: event.sender,
                ipcParams: { ...ipcParams }
            });
        } catch (error) {
            // 해당 엑션이 없는 경우
            logger.error(`${this._channel}: [${callFuncName}] eventName not found.`);
        }

        return undefined;
    };
}
반응형

관련글 더보기