Files
kintone-customize-manager/src/preload/index.ts
xue jiahao 97af24ab2b 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
2026-03-12 16:15:47 +08:00

40 lines
1.2 KiB
TypeScript

import { contextBridge, ipcRenderer } from "electron";
import { electronAPI } from "@electron-toolkit/preload";
import type { SelfAPI } from "./index.d";
// Static properties that are not IPC methods
const staticProps = {
platform: process.platform,
} as const;
// 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
// just add to the DOM global.
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld("electron", electronAPI);
contextBridge.exposeInMainWorld("api", api);
} catch (error) {
console.error(error);
}
} else {
// @ts-ignore (define in dts)
window.electron = electronAPI;
// @ts-ignore (define in dts)
window.api = api;
}