2023-03-02 19:45:19 +00:00
|
|
|
import { useMutation, useQuery, useQueryClient } from 'react-query';
|
|
|
|
import { compact } from 'lodash';
|
|
|
|
|
|
|
|
import { withError } from '@/react-tools/react-query';
|
|
|
|
import axios, { parseAxiosError } from '@/portainer/services/axios';
|
|
|
|
import { EnvironmentId } from '@/react/portainer/environments/types';
|
2023-05-03 03:55:25 +00:00
|
|
|
import { isFulfilled } from '@/react/utils';
|
2023-03-02 19:45:19 +00:00
|
|
|
|
|
|
|
import { getNamespaces } from '../namespaces/service';
|
|
|
|
|
2023-05-02 06:42:16 +00:00
|
|
|
import { Service } from './types';
|
|
|
|
|
2023-03-02 19:45:19 +00:00
|
|
|
export const queryKeys = {
|
|
|
|
list: (environmentId: EnvironmentId) =>
|
|
|
|
['environments', environmentId, 'kubernetes', 'services'] as const,
|
|
|
|
};
|
|
|
|
|
|
|
|
async function getServices(
|
|
|
|
environmentId: EnvironmentId,
|
|
|
|
namespace: string,
|
|
|
|
lookupApps: boolean
|
|
|
|
) {
|
|
|
|
try {
|
2023-05-02 06:42:16 +00:00
|
|
|
const { data: services } = await axios.get<Array<Service>>(
|
2023-03-02 19:45:19 +00:00
|
|
|
`kubernetes/${environmentId}/namespaces/${namespace}/services`,
|
|
|
|
{
|
|
|
|
params: {
|
|
|
|
lookupapplications: lookupApps,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
);
|
|
|
|
return services;
|
|
|
|
} catch (e) {
|
|
|
|
throw parseAxiosError(e as Error, 'Unable to retrieve services');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useServices(environmentId: EnvironmentId) {
|
|
|
|
return useQuery(
|
|
|
|
queryKeys.list(environmentId),
|
|
|
|
async () => {
|
|
|
|
const namespaces = await getNamespaces(environmentId);
|
|
|
|
const settledServicesPromise = await Promise.allSettled(
|
|
|
|
Object.keys(namespaces).map((namespace) =>
|
|
|
|
getServices(environmentId, namespace, true)
|
|
|
|
)
|
|
|
|
);
|
|
|
|
return compact(
|
|
|
|
settledServicesPromise.filter(isFulfilled).flatMap((i) => i.value)
|
|
|
|
);
|
|
|
|
},
|
|
|
|
withError('Unable to get services.')
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useMutationDeleteServices(environmentId: EnvironmentId) {
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation(deleteServices, {
|
|
|
|
onSuccess: () =>
|
|
|
|
// use the exact same query keys as the useServices hook to invalidate the services list
|
|
|
|
queryClient.invalidateQueries(queryKeys.list(environmentId)),
|
|
|
|
...withError('Unable to delete service(s)'),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function deleteServices({
|
|
|
|
environmentId,
|
|
|
|
data,
|
|
|
|
}: {
|
|
|
|
environmentId: EnvironmentId;
|
|
|
|
data: Record<string, string[]>;
|
|
|
|
}) {
|
|
|
|
try {
|
|
|
|
return await axios.post(
|
|
|
|
`kubernetes/${environmentId}/services/delete`,
|
|
|
|
data
|
|
|
|
);
|
|
|
|
} catch (e) {
|
|
|
|
throw parseAxiosError(e as Error, 'Unable to delete service(s)');
|
|
|
|
}
|
|
|
|
}
|