Skip to content

Commit

Permalink
Replace v1 queries related to services for React-Query
Browse files Browse the repository at this point in the history
  • Loading branch information
matborowczyk committed Jan 23, 2025
1 parent b9d2139 commit d7af9ab
Show file tree
Hide file tree
Showing 25 changed files with 598 additions and 438 deletions.
1 change: 1 addition & 0 deletions src/Data/Managers/V2/DELETE/DeleteService/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useDeleteService";
56 changes: 56 additions & 0 deletions src/Data/Managers/V2/DELETE/DeleteService/useDeleteService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import {
UseMutationResult,
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";

/**
* React Query hook for Deleting an Service.
*
* @returns {Mutation} - The mutation object provided by `useMutation` hook.
*/
export const useDeleteService = (
environment: string,
service_entity: string,
): UseMutationResult<void, Error, void, unknown> => {
const client = useQueryClient();
const { createHeaders, handleErrors } = useFetchHelpers();
const headers = createHeaders(environment);

const baseUrlManager = new PrimaryBaseUrlManager(
globalThis.location.origin,
globalThis.location.pathname,
);

const baseUrl = baseUrlManager.getBaseUrl(process.env.API_BASEURL);

/**
* Delete an Service.
*
* @returns {Promise<void>} - A promise that resolves when the Service is successfully deleted
*/
const deleteService = async (): Promise<void> => {
const response = await fetch(
baseUrl + `/lsm/v1/service_catalog/${service_entity}`,
{
method: "DELETE",
headers: headers,
},
);

await handleErrors(response);
};

return useMutation({
mutationFn: deleteService,
mutationKey: ["delete_service"],
onSuccess: () => {
client.refetchQueries({ queryKey: ["get_service_models-continuous"] });
client.refetchQueries({ queryKey: ["get_service_models-one_time"] });
client.refetchQueries({ queryKey: ["get_service_model-one_time"] });
client.refetchQueries({ queryKey: ["get_service_model-continuous"] });
},
});
};
1 change: 0 additions & 1 deletion src/Data/Managers/V2/GETTERS/GetAllServiceModels/index.ts

This file was deleted.

1 change: 1 addition & 0 deletions src/Data/Managers/V2/GETTERS/GetServiceConfig/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useGetServiceConfig";
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { UseQueryResult, useQuery } from "@tanstack/react-query";
import { Config } from "@/Core";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";

/**
* Return Signature of the useGetServiceConfig React Query
*/
interface GetServiceConfig {
useOneTime: () => UseQueryResult<Config, Error>;
}

/**
* React Query hook to fetch the service config
*
* @param service {string} - the service entity
* @param environment {string} - the environment in which the instance belongs
*
* @returns {GetServiceConfig} An object containing the different available queries.
* @returns {UseQueryResult<Config, Error>} returns.useOneTime - Fetch the service model with a single query.
* @returns {UseQueryResult<Config, Error>} returns.useContinuous - Fetch the service model with a recursive query with an interval of 5s.
*/
export const useGetServiceConfig = (
service: string,
environment: string,
): GetServiceConfig => {
const { createHeaders, handleErrors } = useFetchHelpers();
const headers = createHeaders(environment);

const baseUrlManager = new PrimaryBaseUrlManager(
globalThis.location.origin,
globalThis.location.pathname,
);
const baseUrl = baseUrlManager.getBaseUrl(process.env.API_BASEURL);

const fetchInstance = async (): Promise<{ data: Config }> => {
const response = await fetch(
`${baseUrl}/lsm/v1/service_catalog/${service}/config`,
{
headers,
},
);

await handleErrors(
response,
`Failed to fetch Service Config for: ${service}`,
);

return response.json();
};

return {
useOneTime: (): UseQueryResult<Config, Error> =>
useQuery({
queryKey: ["get_service_config-one_time", service],
queryFn: fetchInstance,
retry: false,
select: (data) => data.data,
}),
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ interface GetServiceModel {
* React Query hook to fetch the service model
*
* @param service {string} - the service entity
* @param instanceId {string} - the instance ID for which the data needs to be fetched.
* @param environment {string} - the environment in which the instance belongs
*
* @returns {GetServiceModel} An object containing the different available queries.
Expand All @@ -37,7 +36,7 @@ export const useGetServiceModel = (

const fetchInstance = async (): Promise<{ data: ServiceModel }> => {
const response = await fetch(
`${baseUrl}/lsm/v1/service_catalog/${service}`,
`${baseUrl}/lsm/v1/service_catalog/${service}?instance_summary=True`,
{
headers,
},
Expand Down
2 changes: 1 addition & 1 deletion src/Data/Managers/V2/GETTERS/GetServiceModel/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from "./UseGetServiceModel";
export * from "./useGetServiceModel";
1 change: 1 addition & 0 deletions src/Data/Managers/V2/GETTERS/GetServiceModels/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useGetServiceModels";
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,23 @@ import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";

/**
* Return Signature of the useGetAllServiceModels React Query
* Return Signature of the useGetServiceModel React Query
*/
interface useGetAllServiceModels {
interface GetServiceModels {
useOneTime: () => UseQueryResult<ServiceModel[], Error>;
useContinuous: () => UseQueryResult<ServiceModel[], Error>;
}

/**
* React Query hook to fetch all the service models available in the given environment.
* React Query hook to fetch the service models
*
* @param environment {string} - the environment in which the instance belongs
* @param environment {string} - the environment in which the services belongs
*
* @returns {useGetAllServiceModels} An object containing the different available queries.
* @returns {GetServiceModels} An object containing the different available queries.
* @returns {UseQueryResult<ServiceModel[], Error>} returns.useOneTime - Fetch the service models with a single query.
* @returns {UseQueryResult<ServiceModel[], Error>} returns.useContinuous - Fetch the service models with a recursive query with an interval of 5s.
* @returns {UseQueryResult<ServiceModel[], Error>} returns.useContinuous - Fetch the service models with an interval of 5s.
*/
export const useGetAllServiceModels = (
environment: string,
): useGetAllServiceModels => {
export const useGetServiceModels = (environment: string): GetServiceModels => {
const { createHeaders, handleErrors } = useFetchHelpers();
const headers = createHeaders(environment);

Expand All @@ -32,16 +30,13 @@ export const useGetAllServiceModels = (
);
const baseUrl = baseUrlManager.getBaseUrl(process.env.API_BASEURL);

/**
* Fetches all service models from the service catalog.
*
* @returns {Promise<{ data: ServiceModel[] }>} A promise that resolves to an object containing an array of service models.
* @throws Will throw an error if the fetch operation fails.
*/
const fetchServices = async (): Promise<{ data: ServiceModel[] }> => {
const response = await fetch(`${baseUrl}/lsm/v1/service_catalog`, {
headers,
});
const response = await fetch(
`${baseUrl}/lsm/v1/service_catalog?instance_summary=True`,
{
headers,
},
);

await handleErrors(response, `Failed to fetch Service Models`);

Expand All @@ -51,14 +46,14 @@ export const useGetAllServiceModels = (
return {
useOneTime: (): UseQueryResult<ServiceModel[], Error> =>
useQuery({
queryKey: ["get_all_service_models-one_time"],
queryKey: ["get_service_models-one_time"],
queryFn: fetchServices,
retry: false,
select: (data) => data.data,
}),
useContinuous: (): UseQueryResult<ServiceModel[], Error> =>
useQuery({
queryKey: ["get_all_service_models-continuous"],
queryKey: ["get_service_models-continuous"],
queryFn: fetchServices,
refetchInterval: 5000,
select: (data) => data.data,
Expand Down
Empty file.
53 changes: 53 additions & 0 deletions src/Data/Managers/V2/POST/UpdateCatalog/useUpdateCatalog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
UseMutationResult,
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";

/**
* React Query hook for updating environment catalog.
*
* @param {string} environment - The environment to use for creating headers.
* @returns {UseMutationResult<void, Error, void, unknown>}- The mutation object from `useMutation` hook.
*/
export const useUpdateCatalog = (
environment: string,
): UseMutationResult<void, Error, void, unknown> => {
const client = useQueryClient();
const baseUrlManager = new PrimaryBaseUrlManager(
globalThis.location.origin,
globalThis.location.pathname,
);
const { createHeaders, handleErrors } = useFetchHelpers();
const headers = createHeaders(environment);
const baseUrl = baseUrlManager.getBaseUrl(process.env.API_BASEURL);

/**
* Update the environment catalog.
*
* @returns {Promise<void>} - The promise object of the fetch request.
* @throws {Error} If the response is not successful, an error with the error message is thrown.
*/
const updateCatalog = async (): Promise<void> => {
const response = await fetch(
baseUrl + `/lsm/v1/exporter/export_service_definition`,
{
method: "POST",
headers,
},
);

await handleErrors(response);
};

return useMutation({
mutationFn: updateCatalog,
mutationKey: ["update_catalog"],
onSuccess: () => {
client.invalidateQueries({ queryKey: ["get_service_models-one_time"] });
client.invalidateQueries({ queryKey: ["get_service_models-continuous"] });
},
});
};
45 changes: 29 additions & 16 deletions src/Slices/CreateInstance/UI/Page.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,44 @@
import React, { useContext } from "react";
import { PageContainer, RemoteDataView } from "@/UI/Components";
import { useGetServiceModel } from "@/Data/Managers/V2/GETTERS/GetServiceModel";
import { ErrorView, LoadingView, PageContainer } from "@/UI/Components";
import { DependencyContext } from "@/UI/Dependency";
import { useRouteParams } from "@/UI/Routing";
import { words } from "@/UI/words";
import { CreateInstance } from "./CreateInstance";

export const Page: React.FC = () => {
const { service: serviceName } = useRouteParams<"CreateInstance">();
const { queryResolver } = useContext(DependencyContext);
const { environmentHandler } = useContext(DependencyContext);
const env = environmentHandler.useId();

const [data, retry] = queryResolver.useContinuous<"GetService">({
kind: "GetService",
name: serviceName,
});
const { data, isError, error, isSuccess, refetch } = useGetServiceModel(
serviceName,
env,
).useContinuous();

return (
if (isError) {
<PageContainer pageTitle={words("inventory.createInstance.title")}>
<RemoteDataView
data={data}
retry={retry}
label="AddInstance"
SuccessView={(service) => (
<div aria-label="AddInstance-Success">
<CreateInstance serviceEntity={service} />
</div>
)}
<ErrorView
message={error.message}
retry={refetch}
ariaLabel="ServicesProvider-Failed"
/>
</PageContainer>;
}

if (isSuccess) {
return (
<PageContainer pageTitle={words("inventory.createInstance.title")}>
<div aria-label="AddInstance-Success">
<CreateInstance serviceEntity={data} />
</div>
</PageContainer>
);
}

return (
<PageContainer pageTitle={words("inventory.createInstance.title")}>
<LoadingView ariaLabel="ServicesProvider-Loading" />
</PageContainer>
);
};
Loading

0 comments on commit d7af9ab

Please sign in to comment.