shlink-web-client/src/api/services/ShlinkApiClientBuilder.ts

34 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-02-18 12:40:37 +03:00
import type { ServerWithId } from '../../servers/data';
import { hasServerData } from '../../servers/data';
import type { GetState } from '../../container/types';
2022-05-28 11:47:39 +03:00
import { ShlinkApiClient } from './ShlinkApiClient';
2023-02-18 12:40:37 +03:00
import type { HttpClient } from '../../common/services/HttpClient';
2020-08-27 23:09:16 +03:00
const apiClients: Record<string, ShlinkApiClient> = {};
const isGetState = (getStateOrSelectedServer: GetState | ServerWithId): getStateOrSelectedServer is GetState =>
typeof getStateOrSelectedServer === 'function';
2022-11-04 22:52:06 +03:00
const getSelectedServerFromState = (getState: GetState): ServerWithId => {
const { selectedServer } = getState();
if (!hasServerData(selectedServer)) {
throw new Error('There\'s no selected server or it is not found');
}
2020-08-27 23:09:16 +03:00
2022-11-04 22:52:06 +03:00
return selectedServer;
};
2020-08-27 23:09:16 +03:00
export const buildShlinkApiClient = (httpClient: HttpClient) => (getStateOrSelectedServer: GetState | ServerWithId) => {
2022-11-04 22:52:06 +03:00
const { url, apiKey } = isGetState(getStateOrSelectedServer)
2020-08-27 23:09:16 +03:00
? getSelectedServerFromState(getStateOrSelectedServer)
: getStateOrSelectedServer;
const clientKey = `${url}_${apiKey}`;
if (!apiClients[clientKey]) {
apiClients[clientKey] = new ShlinkApiClient(httpClient, url, apiKey);
2020-08-27 23:09:16 +03:00
}
return apiClients[clientKey];
};
2022-11-04 22:52:06 +03:00
export type ShlinkApiClientBuilder = ReturnType<typeof buildShlinkApiClient>;