2024-08-28 04:41:08 -07:00
|
|
|
import { getAuthUserUrl, getMeUrl } from 'pl-fe/utils/auth';
|
2022-03-18 14:04:08 -07:00
|
|
|
|
2024-08-04 07:09:52 -07:00
|
|
|
import { getClient } from '../api';
|
|
|
|
|
2024-08-11 01:48:58 -07:00
|
|
|
import type { Instance } from 'pl-api';
|
2024-08-28 04:41:08 -07:00
|
|
|
import type { AppDispatch, RootState } from 'pl-fe/store';
|
2024-08-04 07:09:52 -07:00
|
|
|
|
|
|
|
const INSTANCE_FETCH_SUCCESS = 'INSTANCE_FETCH_SUCCESS' as const;
|
2024-08-11 01:48:58 -07:00
|
|
|
const INSTANCE_FETCH_FAIL = 'INSTANCE_FETCH_FAIL' as const;
|
2021-10-20 11:18:55 -07:00
|
|
|
|
2022-04-25 11:57:24 -07:00
|
|
|
/** Figure out the appropriate instance to fetch depending on the state */
|
2024-05-12 16:18:04 -07:00
|
|
|
const getHost = (state: RootState) => {
|
2022-12-25 15:31:07 -08:00
|
|
|
const accountUrl = getMeUrl(state) || getAuthUserUrl(state) as string;
|
2021-10-20 11:18:55 -07:00
|
|
|
|
|
|
|
try {
|
|
|
|
return new URL(accountUrl).host;
|
|
|
|
} catch {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-08-11 01:48:58 -07:00
|
|
|
interface InstanceFetchSuccessAction {
|
|
|
|
type: typeof INSTANCE_FETCH_SUCCESS;
|
|
|
|
instance: Instance;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface InstanceFetchFailAction {
|
|
|
|
type: typeof INSTANCE_FETCH_FAIL;
|
|
|
|
error: any;
|
|
|
|
}
|
|
|
|
|
2024-08-04 07:09:52 -07:00
|
|
|
const fetchInstance = () => async (dispatch: AppDispatch, getState: () => RootState) => {
|
|
|
|
try {
|
|
|
|
const instance = await getClient(getState).instance.getInstance();
|
2024-05-11 14:37:37 -07:00
|
|
|
|
2024-08-11 01:48:58 -07:00
|
|
|
const action: InstanceFetchSuccessAction = { type: INSTANCE_FETCH_SUCCESS, instance };
|
|
|
|
dispatch(action);
|
2024-08-04 07:09:52 -07:00
|
|
|
} catch (error) {
|
|
|
|
dispatch({ type: INSTANCE_FETCH_FAIL, error });
|
|
|
|
}
|
|
|
|
};
|
2024-05-12 16:18:04 -07:00
|
|
|
|
2024-08-11 01:48:58 -07:00
|
|
|
type InstanceAction =
|
|
|
|
InstanceFetchSuccessAction
|
|
|
|
| InstanceFetchFailAction
|
|
|
|
|
2024-05-12 16:18:04 -07:00
|
|
|
export {
|
2024-08-04 07:09:52 -07:00
|
|
|
INSTANCE_FETCH_SUCCESS,
|
2024-08-11 01:48:58 -07:00
|
|
|
INSTANCE_FETCH_FAIL,
|
2024-05-12 16:18:04 -07:00
|
|
|
getHost,
|
|
|
|
fetchInstance,
|
2024-08-11 01:48:58 -07:00
|
|
|
type InstanceAction,
|
2024-05-12 16:18:04 -07:00
|
|
|
};
|