From 75b2c34a135b5cf7430b09f7a63c8d92cdc1b7df Mon Sep 17 00:00:00 2001 From: Mauricio Siu <47042324+Siumauricio@users.noreply.github.com> Date: Sat, 5 Jul 2025 17:06:39 -0600 Subject: [PATCH] feat(api): implement lazy WebSocket client for improved connection management - Introduced a `createLazyWSClient` function to manage WebSocket connections more efficiently by delaying the creation of the client until it's needed. - Updated the `wsClient` initialization to use the new lazy client, enhancing performance and resource management in the application. --- apps/dokploy/utils/api.ts | 41 +++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/apps/dokploy/utils/api.ts b/apps/dokploy/utils/api.ts index 56197528b..4de5fe036 100644 --- a/apps/dokploy/utils/api.ts +++ b/apps/dokploy/utils/api.ts @@ -30,12 +30,41 @@ const getWsUrl = () => { return `${protocol}${host}/drawer-logs`; }; -const wsClient = - typeof window !== "undefined" - ? createWSClient({ - url: getWsUrl() || "", - }) - : null; +// Create WebSocket client with delayed connection +const createLazyWSClient = () => { + if (typeof window === "undefined") return null; + + let actualClient: ReturnType | null = null; + + return { + request: (op: any, callbacks: any) => { + if (!actualClient) { + const wsUrl = getWsUrl(); + if (wsUrl) { + actualClient = createWSClient({ url: wsUrl }); + } + } + return actualClient?.request(op, callbacks) || (() => {}); + }, + close: () => { + if (actualClient) { + actualClient.close(); + actualClient = null; + } + }, + getConnection: () => { + if (!actualClient) { + const wsUrl = getWsUrl(); + if (wsUrl) { + actualClient = createWSClient({ url: wsUrl }); + } + } + return actualClient!.getConnection(); + }, + }; +}; + +const wsClient = createLazyWSClient(); /** A set of type-safe react-query hooks for your tRPC API. */ export const api = createTRPCNext({