2022-11-04 22:52:06 +03:00
|
|
|
import { hasServerData, ServerWithId } from '../../servers/data';
|
2020-08-27 23:09:16 +03:00
|
|
|
import { GetState } from '../../container/types';
|
2022-05-28 11:47:39 +03:00
|
|
|
import { ShlinkApiClient } from './ShlinkApiClient';
|
2022-11-15 01:06:06 +03:00
|
|
|
import { Fetch } from '../../utils/types';
|
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 01:06:06 +03:00
|
|
|
export const buildShlinkApiClient = (fetch: Fetch) => (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-13 18:57:16 +03:00
|
|
|
apiClients[clientKey] = new ShlinkApiClient(fetch, 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>;
|