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
This commit is contained in:
@@ -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 = <T>(channel: string, arg?: unknown): Promise<T> =>
|
||||
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<string, unknown>)[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
|
||||
|
||||
Reference in New Issue
Block a user