From 97af24ab2b91ceb28391473da3dcbb8c1a563b4f Mon Sep 17 00:00:00 2001 From: xue jiahao Date: Thu, 12 Mar 2026 16:15:47 +0800 Subject: [PATCH] refactor(preload): use Proxy for auto IPC routing Replace manual IPC method mapping with Proxy-based approach. Method names now automatically route to IPC channels, eliminating the need to update this file when adding new APIs. - Uses Proxy to intercept property access - Static properties (platform) handled separately - Supports variable argument counts via rest parameters --- src/preload/index.ts | 46 +++++++++++++++----------------------------- 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/src/preload/index.ts b/src/preload/index.ts index 4b355db..95e505c 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -2,38 +2,24 @@ import { contextBridge, ipcRenderer } from "electron"; import { electronAPI } from "@electron-toolkit/preload"; import type { SelfAPI } from "./index.d"; -// Generic invoke helper - reduces boilerplate -const invoke = (channel: string, arg?: unknown): Promise => - ipcRenderer.invoke(channel, arg); - -// Custom APIs for renderer - bridges to IPC handlers -const api: SelfAPI = { +// Static properties that are not IPC methods +const staticProps = { platform: process.platform, +} as const; - // Domain management - getDomains: () => invoke("getDomains"), - createDomain: (params) => invoke("createDomain", params), - updateDomain: (params) => invoke("updateDomain", params), - deleteDomain: (id) => invoke("deleteDomain", id), - testConnection: (id) => invoke("testConnection", id), - testDomainConnection: (params) => invoke("testDomainConnection", params), - - // Browse - getApps: (params) => invoke("getApps", params), - getAppDetail: (params) => invoke("getAppDetail", params), - getFileContent: (params) => invoke("getFileContent", params), - - // Deploy - deploy: (params) => invoke("deploy", params), - - // Download - download: (params) => invoke("download", params), - - // Version management - getVersions: (params) => invoke("getVersions", params), - deleteVersion: (id) => invoke("deleteVersion", id), - rollback: (params) => invoke("rollback", params), -}; +// Proxy-based API that automatically routes method calls to IPC invoke +// Method name = IPC channel name, no manual mapping needed +const api: SelfAPI = new Proxy(staticProps as SelfAPI, { + get(_target, prop: string) { + // Return static property if exists + if (prop in staticProps) { + return (staticProps as Record)[prop]; + } + // Otherwise, auto-create IPC invoke function + // prop (method name) = IPC channel name + return (...args: unknown[]) => ipcRenderer.invoke(prop, ...args); + }, +}); // Use `contextBridge` APIs to expose Electron APIs to // renderer only if context isolation is enabled, otherwise