Skip to content

Commit

Permalink
refactor(ui): only initialize the api-client once
Browse files Browse the repository at this point in the history
  • Loading branch information
HazimAr committed Dec 12, 2024
1 parent 807245e commit 549a38d
Showing 1 changed file with 39 additions and 8 deletions.
47 changes: 39 additions & 8 deletions ui/src/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,47 @@ 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<LittleHorseUserTasksApiClient> {
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;
}
}

export async function getClient(tenantId: string) {
return LHUserTasksClientSingleton.getInstance(tenantId);
}

export async function clientWithErrorHandling<T>(
Expand Down

0 comments on commit 549a38d

Please sign in to comment.