Skip to content
Snippets Groups Projects
useCommitSize.ts 1.79 KiB
Newer Older
import { useQuery } from "@tanstack/react-query";
import axios from "axios";

export const useCommitSize = (projectId, commitIds, token, host) => {
    const platform = host.includes('gitlab') ? 'gitlab' : 'github';


    const { data, isLoading } = useQuery({
        queryKey: ['commitDataSize', platform, projectId, commitIds],
        queryFn: async () => {
            const promises = commitIds.map(commitId => {
                const url = platform === 'gitlab'
                    ? `${host}/api/v4/projects/${projectId}/repository/commits/${commitId.id}`
                    : `https://api.github.com/repos/${projectId}/commits/${commitId.sha}`;

                const headers = platform === 'gitlab'
                    ? { 'PRIVATE-TOKEN': token }
                    : { 'Authorization': `Bearer ${token}` };

                return axios.get(url, { headers }).then(response => {
                    const { stats, commit, author } = response.data;
                    let commitSize = 'small';
                    const totalChanges = stats.additions + stats.deletions;

                    if (totalChanges > 50) commitSize = 'medium';
                    if (totalChanges > 200) commitSize = 'big';

                    return {
                        project_id: projectId,
                        author_name: platform === 'gitlab'
                            ? response.data.author_name
                            : author?.login || commit.author.name,
                        created_at: platform === 'gitlab'
                            ? response.data.created_at
                            : commit.author.date,
                        size: commitSize
                    };
                });
            });

            return Promise.all(promises);
        }
    });

    return { data, isLoading };
};