2020-11-12 12:55:52 +00:00
|
|
|
import { createContext, useContext } from "react";
|
|
|
|
import KeycloakAdminClient from "keycloak-admin";
|
|
|
|
import { RealmContext } from "../realm-context/RealmContext";
|
|
|
|
|
|
|
|
export const AdminClient = createContext<KeycloakAdminClient | undefined>(
|
|
|
|
undefined
|
|
|
|
);
|
|
|
|
|
|
|
|
export const useAdminClient = () => {
|
|
|
|
const adminClient = useContext(AdminClient)!;
|
|
|
|
const { realm } = useContext(RealmContext);
|
|
|
|
|
|
|
|
adminClient.setConfig({
|
|
|
|
realmName: realm,
|
|
|
|
});
|
|
|
|
|
|
|
|
return adminClient;
|
|
|
|
};
|
2021-01-05 13:39:27 +00:00
|
|
|
|
2021-01-11 18:56:19 +00:00
|
|
|
/**
|
|
|
|
* Util function to only set the state when the component is still mounted.
|
|
|
|
*
|
|
|
|
* It takes 2 functions one you do your adminClient call in and the other to set your state
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* useEffect(() => {
|
|
|
|
* return asyncStateFetch(
|
|
|
|
* () => adminClient.components.findOne({ id }),
|
|
|
|
* (component) => setupForm(component)
|
|
|
|
* );
|
|
|
|
* }, []);
|
|
|
|
*
|
|
|
|
* @param adminClientCall use this to do your adminClient call
|
|
|
|
* @param callback when the data is fetched this is where you set your state
|
2021-02-17 21:12:25 +00:00
|
|
|
* @param onError custom error handler
|
2021-01-11 18:56:19 +00:00
|
|
|
*/
|
|
|
|
export function asyncStateFetch<T>(
|
2021-01-05 13:39:27 +00:00
|
|
|
adminClientCall: () => Promise<T>,
|
2021-02-17 21:12:25 +00:00
|
|
|
callback: (param: T) => void,
|
|
|
|
onError?: (error: Error) => void
|
2021-01-05 13:39:27 +00:00
|
|
|
) {
|
|
|
|
let canceled = false;
|
|
|
|
|
2021-02-17 21:12:25 +00:00
|
|
|
adminClientCall()
|
|
|
|
.then((result) => {
|
|
|
|
try {
|
|
|
|
if (!canceled) {
|
|
|
|
callback(result);
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
if (onError) onError(error);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch(onError);
|
2021-01-05 13:39:27 +00:00
|
|
|
|
|
|
|
return () => {
|
|
|
|
canceled = true;
|
|
|
|
};
|
|
|
|
}
|