2023-08-30 00:12:25 +03:00
|
|
|
import type { HttpClient } from '@shlinkio/shlink-js-sdk';
|
|
|
|
import { ShlinkApiClient } from '@shlinkio/shlink-js-sdk';
|
2023-02-18 13:11:01 +03:00
|
|
|
import type { GetState } from '../../container/types';
|
2023-02-18 12:40:37 +03:00
|
|
|
import type { ServerWithId } from '../../servers/data';
|
|
|
|
import { hasServerData } from '../../servers/data';
|
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) => {
|
2023-08-30 00:12:25 +03:00
|
|
|
const { url: baseUrl, apiKey } = isGetState(getStateOrSelectedServer)
|
2020-08-27 23:09:16 +03:00
|
|
|
? getSelectedServerFromState(getStateOrSelectedServer)
|
|
|
|
: getStateOrSelectedServer;
|
2023-08-30 00:12:25 +03:00
|
|
|
const serverKey = `${apiKey}_${baseUrl}`;
|
2020-08-27 23:09:16 +03:00
|
|
|
|
2023-08-30 00:12:25 +03:00
|
|
|
const apiClient = apiClients[serverKey] ?? new ShlinkApiClient(httpClient, { apiKey, baseUrl });
|
|
|
|
apiClients[serverKey] = apiClient;
|
2020-08-27 23:09:16 +03:00
|
|
|
|
2023-08-30 00:12:25 +03:00
|
|
|
return apiClient;
|
2020-08-27 23:09:16 +03:00
|
|
|
};
|
2022-11-04 22:52:06 +03:00
|
|
|
|
|
|
|
export type ShlinkApiClientBuilder = ReturnType<typeof buildShlinkApiClient>;
|