Skip to content
Snippets Groups Projects
useCommitSize.ts 2.2 KiB
Newer Older
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import PromisePool from 'es6-promise-pool';
export const useCommitSize = (projectId, commits, token, host) => {
    const platform = host.includes('gitlab') ? 'gitlab' : 'github';

    const { data, isLoading } = useQuery({
        queryKey: ['commitDataSize', platform, projectId, commits],
        queryFn: async () => {
            const BATCH_SIZE = 30;

            const fetchCommitData = async (commit) => {
                const url = platform === 'gitlab'
                    ? `${host}/api/v4/projects/${projectId}/repository/commits/${commit.id}`
                    : `https://api.github.com/repos/${projectId}/commits/${commit.sha}`;

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

                const response = await axios.get(url, { headers });
                const { stats, commit: commitData, 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 || commitData.author.name,
                    created_at: platform === 'gitlab'
                        ? response.data.created_at
                        : commitData.author.date,
                    size: commitSize
                };
            };

            const results = [];
            const pool = new PromisePool(() => {
                const commit = commits.shift();
                return commit ? fetchCommitData(commit).then(result => {
                    results.push(result);
                    return result;
                }) : null;
            }, BATCH_SIZE);

            await pool.start();
            console.log('results', results);
            return Promise.all(results);
        }
    });

    return { data, isLoading };
};