From 3b690470057286b3ff5cfbe797a045b95e0e605d Mon Sep 17 00:00:00 2001 From: Hazim Arafa Date: Thu, 12 Dec 2024 13:06:22 -0500 Subject: [PATCH] refactor: only initialize the api-client once --- ui/src/lib/client.ts | 49 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/ui/src/lib/client.ts b/ui/src/lib/client.ts index 2f2a98d..b6c3f08 100644 --- a/ui/src/lib/client.ts +++ b/ui/src/lib/client.ts @@ -5,18 +5,51 @@ import { import { redirect } from "next/navigation"; import { auth } from "../app/api/auth/[...nextauth]/authOptions"; -export async function getClient(tenantId: string) { - const session = await auth(); +export class LHUserTasksClientSingleton { + private static instance: LittleHorseUserTasksApiClient | null = null; + private static currentConfig: { + baseUrl: string; + tenantId: string; + accessToken: string; + } | null = null; + + private constructor() {} + + public static async getInstance( + tenantId: string, + ): Promise { + const session = await auth(); + + if (!session) redirect(`/api/auth/signin?callbackUrl=/`); + + const config = { + baseUrl: process.env.LHUT_API_URL!, + tenantId, + accessToken: session.access_token, + }; - if (!session) redirect(`/api/auth/signin?callbackUrl=/`); + // Create new instance if config changes or doesn't exist + if ( + !this.instance || + !this.currentConfig || + this.currentConfig.baseUrl !== config.baseUrl || + this.currentConfig.tenantId !== config.tenantId || + this.currentConfig.accessToken !== config.accessToken + ) { + this.instance = new LittleHorseUserTasksApiClient(config); + this.currentConfig = config; + } - return new LittleHorseUserTasksApiClient({ - baseUrl: process.env.LHUT_API_URL!, - tenantId, - accessToken: session.access_token, - }); + return this.instance; + } +} + +// Updated getClient function using the singleton +export async function getClient(tenantId: string) { + return LHUserTasksClientSingleton.getInstance(tenantId); } +// Updated error handling wrapper export async function clientWithErrorHandling( tenantId: string, action: (client: LittleHorseUserTasksApiClient) => Promise,