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
|
|
|
|
2022-11-15 22:31:35 +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]) {
|
2022-11-15 22:31:35 +03:00
|
|
|
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>;
|