Skip to content

Commit

Permalink
Extract code duplicates from react queries
Browse files Browse the repository at this point in the history
  • Loading branch information
matborowczyk committed Jan 28, 2025
1 parent 8bf7600 commit 358603f
Show file tree
Hide file tree
Showing 79 changed files with 933 additions and 1,226 deletions.
1 change: 1 addition & 0 deletions src/Core/Domain/ProjectModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface EnvironmentModel {
repo_url: string;
description?: string;
icon?: string;
halted: boolean;
}

export interface FlatEnvironment extends EnvironmentModel {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ test("GIVEN QueryManager.ContinuousWithEnv WHEN environment changes THEN the api
repo_branch: "branch",
repo_url: "repo",
projectName: "project",
halted: false,
settings: {
enable_lsm_expert_mode: false,
},
},
{
id: "bbb",
Expand All @@ -39,6 +43,10 @@ test("GIVEN QueryManager.ContinuousWithEnv WHEN environment changes THEN the api
repo_branch: "branch",
repo_url: "repo",
projectName: "project",
halted: false,
settings: {
enable_lsm_expert_mode: false,
},
},
]),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,24 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";
import { useDelete } from "../../helpers/useQueries";

/**
* React Query hook for deleting version of Desired State
*
* @param {string} env - The environment in which we are trying to remove the version.
* @returns {Mutation} - The mutation object provided by `useMutation` hook.
*/
export const useDeleteDesiredStateVersion = (
env: string,
): UseMutationResult<void, Error, string, unknown> => {
export const useDeleteDesiredStateVersion = (): UseMutationResult<
void,
Error,
string,
unknown
> => {
const client = useQueryClient();
const { createHeaders, handleErrors } = useFetchHelpers();
const baseUrlManager = new PrimaryBaseUrlManager(
globalThis.location.origin,
globalThis.location.pathname,
);

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

/**
* Deletes a version of the desired state.
*
* @param {string} version - The version of the desired state to be removed.
* @returns {Promise<void>} - A promise that resolves when the version is successfully removed.
* @throws {Error} If the response is not successful, an error with the error message is thrown.
*/
const deleteOrder = async (version: string): Promise<void> => {
const response = await fetch(baseUrl + `/api/v1/version/${version}`, {
method: "DELETE",
headers: createHeaders(env),
});

await handleErrors(response);
};
const deleteFn = useDelete()<void>;

return useMutation({
mutationFn: deleteOrder,
mutationFn: (version) => deleteFn(`/api/v1/version/${version}`),
mutationKey: ["delete_desired_state_version"],
onSuccess: () => {
//invalidate the desired state queries to update the list
Expand Down
39 changes: 7 additions & 32 deletions src/Data/Managers/V2/DELETE/DeleteInstance/useDeleteInstance.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,24 @@
import { UseMutationResult, useMutation } from "@tanstack/react-query";
import { ParsedNumber } from "@/Core";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";
import { useDelete } from "../../helpers/useQueries";

/**
* React Query hook for Deleting an instance.
*
* @returns {Mutation} - The mutation object provided by `useMutation` hook.
*/
export const useDeleteInstance = (
environment: string,
instance_id: string,
service_entity: string,
version: ParsedNumber,
): UseMutationResult<void, Error, string, unknown> => {
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 instance.
*
* @returns {Promise<void>} - A promise that resolves when the instance is succesfully deleted
*/
const deleteInstance = async (): Promise<void> => {
const response = await fetch(
baseUrl +
`/lsm/v1/service_inventory/${service_entity}/${instance_id}?current_version=${version}`,
{
method: "DELETE",
headers: headers,
},
);

await handleErrors(response);
};
): UseMutationResult<void, Error, void, unknown> => {
const deleteFn = useDelete()<void>;

return useMutation({
mutationFn: deleteInstance,
mutationFn: () =>
deleteFn(
`/lsm/v1/service_inventory/${service_entity}/${instance_id}?current_version=${version}`,
),
mutationKey: ["delete_instance"],
});
};
33 changes: 3 additions & 30 deletions src/Data/Managers/V2/DELETE/DeleteService/useDeleteService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,48 +3,21 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";
import { useDelete } from "../../helpers/useQueries";

/**
* 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);
};
const deleteFn = useDelete()<void>;

return useMutation({
mutationFn: deleteService,
mutationFn: () => deleteFn(`/lsm/v1/service_catalog/${service_entity}`),
mutationKey: ["delete_service"],
onSuccess: () => {
client.refetchQueries({ queryKey: ["get_service_models-continuous"] });
Expand Down
41 changes: 7 additions & 34 deletions src/Data/Managers/V2/DELETE/DestroyInstance/useDestroyInstance.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { UseMutationResult, useMutation } from "@tanstack/react-query";
import { ParsedNumber } from "@/Core";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";
import { useDelete } from "../../helpers/useQueries";

/**
* React Query hook for destroying an instance.
Expand All @@ -10,44 +9,18 @@ import { useFetchHelpers } from "../../helpers";
* @returns {Mutation} - The mutation object provided by `useMutation` hook.
*/
export const useDestroyInstance = (
environment: string,
instance_id: string,
service_entity: string,
version: ParsedNumber,
message: string,
): UseMutationResult<void, Error, string, unknown> => {
const { createHeaders, handleErrors } = useFetchHelpers();
const headers = createHeaders(environment);

headers.append("message", message);

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

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

/**
* Destroy an instance.
*
* @returns {Promise<void>} - A promise that resolves when the instance is succesfully destroyed.
*/
const destroyInstance = async (): Promise<void> => {
const response = await fetch(
baseUrl +
`/lsm/v2/service_inventory/${service_entity}/${instance_id}/expert?current_version=${version}`,
{
method: "DELETE",
headers: headers,
},
);

await handleErrors(response);
};
): UseMutationResult<void, Error, void, unknown> => {
const deleteFn = useDelete({ message })<void>;

return useMutation({
mutationFn: destroyInstance,
mutationFn: () =>
deleteFn(
`/lsm/v2/service_inventory/${service_entity}/${instance_id}/expert?current_version=${version}`,
),
mutationKey: ["destroy_instance"],
});
};
28 changes: 3 additions & 25 deletions src/Data/Managers/V2/DELETE/RemoveUser/useRemoveUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";
import { useDelete } from "../../helpers/useQueries";

/**
* React Query hook for removing a user from the server.
Expand All @@ -18,31 +17,10 @@ export const useRemoveUser = (): UseMutationResult<
unknown
> => {
const client = useQueryClient();
const { createHeaders, handleErrors } = useFetchHelpers();
const baseUrlManager = new PrimaryBaseUrlManager(
globalThis.location.origin,
globalThis.location.pathname,
);

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

/**
* Deletes a user from the server.
*
* @param {string} username - The username of the user to be removed.
* @returns {Promise<void>} - A promise that resolves when the user is successfully removed.
*/
const deleteOrder = async (username: string): Promise<void> => {
const response = await fetch(baseUrl + `/api/v2/user/${username}`, {
method: "DELETE",
headers: createHeaders(),
});

await handleErrors(response);
};
const deleteFn = useDelete()<void>;

return useMutation({
mutationFn: deleteOrder,
mutationFn: (username) => deleteFn(`/api/v2/user/${username}`),
mutationKey: ["removeUser"],
onSuccess: () => {
// Refetch the users query to update the list
Expand Down
38 changes: 8 additions & 30 deletions src/Data/Managers/V2/GETTERS/FormSuggestions/useSuggestions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { useQuery } from "@tanstack/react-query";
import { FormSuggestion } from "@/Core";
import { PrimaryBaseUrlManager } from "@/UI";
import { useFetchHelpers } from "../../helpers";
import { useGet } from "../../helpers/useQueries";

interface ResponseData {
parameter: Record<string, Record<string, unknown>>;
}

/**
* React Query hook to handle suggested values for a parameter.
Expand All @@ -10,16 +13,13 @@ import { useFetchHelpers } from "../../helpers";
* if the suggestions are null or undefined, it will return null as data, and a success status.
*
* @param suggestions - The suggestions for the parameter.
* @param environment - The environment for the parameter.
*
* @returns The result of the query, {data, status, error, isLoading}.
*/
export const useSuggestedValues = (
suggestions: FormSuggestion | null | undefined,
environment: string,
) => {
//extracted headers to avoid breaking rules of Hooks
const { createHeaders, handleErrors } = useFetchHelpers();
const get = useGet()<ResponseData>;

if (!suggestions) {
return {
Expand All @@ -41,24 +41,6 @@ export const useSuggestedValues = (
},
};
}
const baseUrlManager = new PrimaryBaseUrlManager(
globalThis.location.origin,
globalThis.location.pathname,
);
const baseUrl = baseUrlManager.getBaseUrl(process.env.API_BASEURL);

const fetchParameter = async () => {
const response = await fetch(
`${baseUrl}/api/v1/parameter/${suggestions.parameter_name}`,
{
headers: createHeaders(environment),
},
);

await handleErrors(response);

return response.json();
};

return {
/**
Expand All @@ -67,12 +49,8 @@ export const useSuggestedValues = (
*/
useOneTime: () =>
useQuery({
queryKey: [
"get_parameter-one_time",
suggestions.parameter_name,
environment,
],
queryFn: fetchParameter,
queryKey: ["get_parameter-one_time", suggestions.parameter_name],
queryFn: () => get(`/api/v1/parameter/${suggestions.parameter_name}`),
retry: false,
select: (data) => data.parameter,
}),
Expand Down
Loading

0 comments on commit 358603f

Please sign in to comment.