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

33 lines
1.3 KiB
TypeScript
Raw Normal View History

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
export const buildShlinkApiClient = (httpClient: HttpClient) => (getStateOrSelectedServer: GetState | ServerWithId) => {
const { url: baseUrl, apiKey } = isGetState(getStateOrSelectedServer)
2020-08-27 23:09:16 +03:00
? getSelectedServerFromState(getStateOrSelectedServer)
: getStateOrSelectedServer;
const serverKey = `${apiKey}_${baseUrl}`;
2020-08-27 23:09:16 +03:00
const apiClient = apiClients[serverKey] ?? new ShlinkApiClient(httpClient, { apiKey, baseUrl });
apiClients[serverKey] = apiClient;
2020-08-27 23:09:16 +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>;