From ef0b9ca2f0893244f2e7ac2433d828b6889b28a6 Mon Sep 17 00:00:00 2001 From: purocean Date: Mon, 9 Dec 2024 15:11:06 +0800 Subject: [PATCH] feat: enhance JSON-RPC initialization --- src/renderer/startup.ts | 2 +- src/renderer/support/jsonrpc.ts | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/renderer/startup.ts b/src/renderer/startup.ts index b1281d233..f6b4621c5 100644 --- a/src/renderer/startup.ts +++ b/src/renderer/startup.ts @@ -260,7 +260,7 @@ whenEditorReady().then(() => { // json-rpc -jsonrpc.init({ ctx }) +jsonrpc.init({ ctx }, whenEditorReady()) setTimeout(() => { removeOldDatabases() diff --git a/src/renderer/support/jsonrpc.ts b/src/renderer/support/jsonrpc.ts index 4da7c939f..d5a92aad7 100644 --- a/src/renderer/support/jsonrpc.ts +++ b/src/renderer/support/jsonrpc.ts @@ -2,6 +2,8 @@ import { JSONRPCError, JSONRPCRequest, JSONRPCResult, JSONRPCServer, JSONRPCServ import { FLAG_DEBUG } from '@fe/support/args' import { isElectron, nodeRequire } from './env' +let rpcReady: Promise | null = null + class ElectronRendererServerChannel implements JSONRPCServerChannel { ipcRenderer: Electron.IpcRenderer @@ -15,7 +17,15 @@ class ElectronRendererServerChannel implements JSONRPCServerChannel { setMessageHandler (callback: (message: JSONRPCRequest) => void): void { this.ipcRenderer.on('jsonrpc', (_event, message) => { - callback(message) + // delay the message until the app is ready + if (rpcReady) { + rpcReady.then(() => { + rpcReady = null + callback(message) + }) + } else { + callback(message) + } }) } } @@ -27,8 +37,9 @@ function initElectronRPCServer (modules: Record) { } } -export function init (modules: Record) { +export function init (modules: Record, ready: Promise) { if (isElectron) { + rpcReady = ready initElectronRPCServer(modules) } }