2022-08-11 04:33:29 +00:00
|
|
|
import { useQuery } from 'react-query';
|
|
|
|
|
2022-10-23 06:53:25 +00:00
|
|
|
import { EnvironmentId } from '@/react/portainer/environments/types';
|
2023-05-18 05:53:34 +00:00
|
|
|
import axios, {
|
|
|
|
agentTargetHeader,
|
|
|
|
parseAxiosError,
|
|
|
|
} from '@/portainer/services/axios';
|
|
|
|
import { withGlobalError } from '@/react-tools/react-query';
|
2022-08-11 04:33:29 +00:00
|
|
|
|
|
|
|
import { urlBuilder } from '../containers.service';
|
|
|
|
import { DockerContainerResponse } from '../types/response';
|
|
|
|
import { parseViewModel } from '../utils';
|
|
|
|
|
|
|
|
import { Filters } from './types';
|
|
|
|
import { queryKeys } from './query-keys';
|
|
|
|
|
2023-05-18 05:53:34 +00:00
|
|
|
interface UseContainers {
|
|
|
|
all?: boolean;
|
|
|
|
filters?: Filters;
|
|
|
|
nodeName?: string;
|
|
|
|
}
|
|
|
|
|
2022-08-11 04:33:29 +00:00
|
|
|
export function useContainers(
|
|
|
|
environmentId: EnvironmentId,
|
2023-05-18 05:53:34 +00:00
|
|
|
{
|
|
|
|
autoRefreshRate,
|
|
|
|
|
|
|
|
...params
|
|
|
|
}: UseContainers & {
|
|
|
|
autoRefreshRate?: number;
|
|
|
|
} = {}
|
2022-08-11 04:33:29 +00:00
|
|
|
) {
|
|
|
|
return useQuery(
|
2023-05-18 05:53:34 +00:00
|
|
|
queryKeys.filters(environmentId, params),
|
|
|
|
() => getContainers(environmentId, params),
|
2022-08-11 04:33:29 +00:00
|
|
|
{
|
2023-05-18 05:53:34 +00:00
|
|
|
...withGlobalError('Unable to retrieve containers'),
|
2022-08-11 04:33:29 +00:00
|
|
|
refetchInterval() {
|
|
|
|
return autoRefreshRate ?? false;
|
|
|
|
},
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getContainers(
|
|
|
|
environmentId: EnvironmentId,
|
2023-05-18 05:53:34 +00:00
|
|
|
{ all = true, filters, nodeName }: UseContainers = {}
|
2022-08-11 04:33:29 +00:00
|
|
|
) {
|
|
|
|
try {
|
|
|
|
const { data } = await axios.get<DockerContainerResponse[]>(
|
|
|
|
urlBuilder(environmentId, undefined, 'json'),
|
|
|
|
{
|
|
|
|
params: { all, filters: filters && JSON.stringify(filters) },
|
2023-05-18 05:53:34 +00:00
|
|
|
headers: nodeName
|
|
|
|
? {
|
|
|
|
[agentTargetHeader]: nodeName,
|
|
|
|
}
|
|
|
|
: undefined,
|
2022-08-11 04:33:29 +00:00
|
|
|
}
|
|
|
|
);
|
|
|
|
return data.map((c) => parseViewModel(c));
|
|
|
|
} catch (error) {
|
|
|
|
throw parseAxiosError(error as Error, 'Unable to retrieve containers');
|
|
|
|
}
|
|
|
|
}
|