Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

8.6 KB
Raw Blame
import {
  keepPreviousData,
  useInfiniteQuery,
  useMutation,
  useQuery,
  useQueryClient
} from "@tanstack/react-query";
import { format } from "date-fns";

import { apiRequest } from "@app/config/request";

import {
  Commit,
  CommitAuthor,
  CommitAuthorFilter,
  CommitWithChanges,
  RollbackPreview
} from "./types";

export const commitKeys = {
  count: ({
    projectId,
    environment,
    directory
  }: {
    projectId: string;
    environment: string;
    directory?: string;
  }) => [{ projectId, environment, directory }, "folder-commits-count"] as const,

  history: ({
    projectId,
    environment,
    directory
  }: {
    projectId: string;
    environment: string;
    directory?: string;
  }) => [{ projectId, environment, directory }, "folder-commits"] as const,

  authors: ({
    projectId,
    environment,
    directory
  }: {
    projectId: string;
    environment: string;
    directory?: string;
  }) => [{ projectId, environment, directory }, "folder-commit-authors"] as const,

  details: ({ projectId, commitId }: { projectId: string; commitId: string }) =>
    [{ projectId, commitId }, "commit-details"] as const,

  rollbackPreview: ({
    folderId,
    commitId,
    projectId,
    deepRollback
  }: {
    folderId: string;
    commitId: string;
    projectId: string;
    deepRollback: boolean;
  }) => [{ folderId, commitId, projectId, deepRollback }, "rollback-preview"] as const
};

const fetchFolderCommitsCount = async ({
  projectId,
  environment,
  directory
}: {
  projectId: string;
  environment: string;
  directory?: string;
}) => {
  const res = await apiRequest.get<{ count: number; folderId: string }>(
    "/api/v1/pit/commits/count",
    {
      params: {
        environment,
        path: directory,
        projectId
      }
    }
  );
  return res.data;
};

const fetchFolderCommitHistory = async (
  projectId: string,
  environment: string,
  directory: string,
  offset: number = 0,
  limit: number = 20,
  search?: string,
  sort: "asc" | "desc" = "desc",
  author?: CommitAuthorFilter
): Promise<{
  commits: Commit[];
  total: number;
  hasMore: boolean;
}> => {
  const res = await apiRequest.get<{
    commits: Commit[];
    total: number;
    hasMore: boolean;
  }>("/api/v1/pit/commits", {
    params: {
      environment,
      path: directory,
      projectId,
      offset,
      limit,
      search,
      sort,
      actorId: author?.actorId,
      actorType: author?.actorType
    }
  });
  return res.data;
};

const fetchFolderCommitAuthors = async ({
  projectId,
  environment,
  directory
}: {
  projectId: string;
  environment: string;
  directory?: string;
}) => {
  const res = await apiRequest.get<{ authors: CommitAuthor[] }>("/api/v1/pit/commits/authors", {
    params: {
      environment,
      path: directory,
      projectId
    }
  });
  return res.data.authors;
};

export const fetchCommitDetails = async (projectId: string, commitId: string) => {
  const { data } = await apiRequest.get<CommitWithChanges>(
    `/api/v1/pit/commits/${commitId}/changes`,
    {
      params: {
        projectId
      }
    }
  );
  return data;
};

export const fetchRollbackPreview = async (
  folderId: string,
  commitId: string,
  projectId: string,
  deepRollback: boolean
): Promise<RollbackPreview[]> => {
  const { data } = await apiRequest.get<RollbackPreview[]>(
    `/api/v1/pit/commits/${commitId}/compare`,
    {
      params: {
        folderId,
        deepRollback,
        projectId
      }
    }
  );
  return data;
};

const fetchRollback = async (
  folderId: string,
  commitId: string,
  projectId: string,
  deepRollback: boolean,
  message?: string,
  envSlug?: string
) => {
  const { data } = await apiRequest.post<{ success: boolean }>(
    `/api/v1/pit/commits/${commitId}/rollback`,
    {
      folderId,
      deepRollback,
      message,
      environment: envSlug,
      projectId
    }
  );
  return data;
};

const fetchRevert = async (commitId: string, projectId: string) => {
  const { data } = await apiRequest.post<{ success: boolean; message: string }>(
    `/api/v1/pit/commits/${commitId}/revert`,
    {
      projectId
    }
  );
  return data;
};

export const useCommitRevert = ({
  commitId,
  projectId,
  environment,
  directory
}: {
  commitId: string;
  projectId: string;
  environment: string;
  directory: string;
}) => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => fetchRevert(commitId, projectId),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [
          commitKeys.details({ projectId, commitId }),
          commitKeys.history({ projectId, environment, directory }),
          commitKeys.count({ projectId, environment, directory })
        ]
      });
    }
  });
};

export const useCommitRollback = ({
  projectId,
  commitId,
  folderId,
  deepRollback,
  environment,
  directory,
  envSlug
}: {
  projectId: string;
  commitId: string;
  folderId: string;
  deepRollback: boolean;
  environment: string;
  directory: string;
  envSlug: string;
}) => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (message: string) =>
      fetchRollback(folderId, commitId, projectId, deepRollback, message, envSlug),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [
          commitKeys.details({ projectId, commitId }),
          commitKeys.history({ projectId, environment, directory }),
          commitKeys.count({ projectId, environment, directory })
        ]
      });
    }
  });
};

export const useGetFolderCommitsCount = ({
  projectId,
  environment,
  directory,
  isPaused
}: {
  projectId: string;
  environment: string;
  directory: string;
  isPaused?: boolean;
}) =>
  useQuery({
    enabled: Boolean(projectId && environment) && !isPaused,
    queryKey: commitKeys.count({ projectId, environment, directory }),
    queryFn: () => fetchFolderCommitsCount({ projectId, environment, directory })
  });

export const useGetFolderCommitHistory = ({
  projectId,
  environment,
  directory,
  limit = 20,
  search,
  sort = "desc",
  author,
  isPaused
}: {
  projectId: string;
  environment: string;
  directory: string;
  limit?: number;
  search?: string;
  sort?: "asc" | "desc";
  author?: CommitAuthorFilter;
  isPaused?: boolean;
}) => {
  return useInfiniteQuery({
    initialPageParam: 0,
    queryKey: [
      commitKeys.history({ projectId, environment, directory }),
      limit,
      search,
      sort,
      author?.actorId,
      author?.actorType
    ],
    queryFn: ({ pageParam }) =>
      fetchFolderCommitHistory(
        projectId,
        environment,
        directory,
        pageParam,
        limit,
        search,
        sort,
        author
      ),
    enabled: Boolean(projectId && environment) && !isPaused,
    select: (data) => {
      const commits = (data?.pages ?? []).flatMap((page) => page.commits);
      const groups: { date: string; commits: Commit[] }[] = [];

      commits.forEach((commit) => {
        const date = format(new Date(commit.createdAt), "MMM d, yyyy");
        const group = groups.at(-1);
        if (group?.date === date) {
          group.commits.push(commit);
        } else {
          groups.push({ date, commits: [commit] });
        }
      });

      return {
        groups,
        loadedCount: commits.length,
        total: data?.pages?.[0]?.total ?? 0
      };
    },
    getNextPageParam: (lastPage, pages) => (lastPage.hasMore ? pages.length * limit : undefined)
  });
};

export const useGetCommitAuthors = ({
  projectId,
  environment,
  directory,
  isPaused
}: {
  projectId: string;
  environment: string;
  directory: string;
  isPaused?: boolean;
}) =>
  useQuery({
    enabled: Boolean(projectId && environment) && !isPaused,
    queryKey: commitKeys.authors({ projectId, environment, directory }),
    queryFn: () => fetchFolderCommitAuthors({ projectId, environment, directory })
  });

export const useGetCommitDetails = (projectId: string, commitId: string) => {
  return useQuery({
    queryKey: commitKeys.details({ projectId, commitId }),
    queryFn: () => fetchCommitDetails(projectId, commitId),
    enabled: Boolean(projectId) && Boolean(commitId)
  });
};

export const useGetRollbackPreview = (
  folderId: string,
  commitId: string,
  projectId: string,
  deepRollback: boolean
) => {
  return useQuery({
    queryKey: commitKeys.rollbackPreview({ folderId, commitId, projectId, deepRollback }),
    queryFn: () => fetchRollbackPreview(folderId, commitId, projectId, deepRollback),
    enabled: Boolean(folderId) && Boolean(commitId),
    // Toggling deep rollback swaps query keys, so hold the previous preview instead of
    // tearing the whole panel down to skeletons on every toggle
    placeholderData: keepPreviousData
  });
};