javascriptgithubgithub-apioctokit-js

How can I use octokit to list open PRs from all repos in my org?


I would like to write a script in Javascript to query all open github PRs in all repos in my org. I can use this URL to do it in a browser: https://my.github.server/pulls?q=is%3Aopen+is%3Apr+org%3Amy-org-name.

But using octokit, I need to supply the name of the repo in which to search. It looks as if the github API also requires it, but like I said, the URL above doesn't supply a repo name and it works just fine.

The documented one also has /repos at the beginning, which mine above does not. I can't find the one I'm using anywhere in the github API docs. If I try octokit.request( 'GET /pulls?q=...' ) as above, I get a 404.

I'm sure there's a way to list the repos and run the above search on each one, but I have dozens of repos, so that's likely to be much slower. Is there a way to do it in one request?


Solution

  • There is no direct way to fetch all open PRs across all repositories within an organization in a single request using GitHub's API or Octokit. The Search API can search for PRs but it doesn't support filtering by organization.

    You can get a list of all repositories in the organization and use the list of repositories to get all pull requests for each repository.

    Example:

    const { Octokit } = require("@octokit/core");
    
    const octokit = new Octokit({ auth: `your_auth_token` });
    
    async function fetchAllRepos(org) {
        const repos = [];
        let page = 1;
        while (true) {
            const result = await octokit.request('GET /orgs/{org}/repos', {
                org: org,
                type: 'public',
                per_page: 100,
                page: page
            });
    
            if (result.data.length === 0) break;
            repos.push(...result.data);
            page++;
        }
        return repos;
    }
    
    async function fetchAllPRs(org) {
        const repos = await fetchAllRepos(org);
    
        const prPromises = repos.map(repo =>
            octokit.request('GET /repos/{owner}/{repo}/pulls', {
                owner: org,
                repo: repo.name,
                state: 'open'
            })
        );
    
        const prResults = await Promise.all(prPromises);
        const prs = prResults.flatMap(result => result.data);
        return prs;
    }
    
    fetchAllPRs('my-org-name')
        .then(prs => console.log(prs))
        .catch(err => console.error(err));
    

    Not sure how slow this will be in your case. I hope this helps anyway.