rihurla
rihurla

Reputation: 403

Github API GET Approved Pull Request Reviews List

I'm working on a Github Action with the Github API endpoint for the list of reviews but it returns the whole history, including dismissals and comments, but the only ones I need are the ones where the state is "APPROVED".

The issue is that if the PR has more than 100 review objects (100 being the max per page), I'm unable to find the approved objects which will be on the following page since it returns in chronological order.

Is there any other way to get the pull request review approved state?

My code is the following:

async function evaluateReviews() {
  const result = await octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews', {
    owner: owner,
    repo: repo,
    pull_number: pullNumber
  });

  const numberOfApprovalsRequired = core.getInput('number-of-approvals');
  const reviews = result.data
  var approvals = 0

  reviews.forEach((item, i) => {
    if (item.state == "APPROVED") {
      approvals += 1;
    }
  });

  if (approvals >= numberOfApprovalsRequired) {
    addApprovedLabel();
  }
}

Upvotes: 2

Views: 1948

Answers (1)

rihurla
rihurla

Reputation: 403

I'm posting the answer here so it might help someone with the same issue.

I opened a ticket on Github support, and they answered by saying that the endpoint to retrieve only approved pull request review is not available via REST API, however, I can get the count by using their GraphQL API.

I was able to get exactly what I needed by changing my previous request with a new one using GraphQL.

Here is the code.

async function evaluateReviews() {
  try {
    const approvedResponse = await octokit.graphql(`
      query($name: String!, $owner: String!, $pull_number: Int!) {
        repository(name: $name, owner: $owner) {
          pullRequest(number: $pull_number) {
            reviews(states: APPROVED) {
              totalCount
            }
          }
        }
      }
      `, {
        "name": name,
        "owner": owner,
        "pull_number": pullNumber
      });
      const approvalsRequired = core.getInput('number-of-approvals');
      const approvals = approvedResponse.repository.pullRequest.reviews.totalCount
      if (approvals >= approvalsRequired) {
        addApprovedLabel();
      }
    } catch (error) {
      console.log(`ERROR: ${error}`);
    }
}

Reference:

Pull Request Review Object

Pull Request Review State Object

GitHub GraphQL Explorer

Example on GitHub GraphQL Explorer:

{
  repository(name: "fetch", owner: "github") {
    pullRequest(number: 913) {
      reviews(states: APPROVED) {
        totalCount
      }
    }
  }
}

Response:

{
  "data": {
    "repository": {
      "pullRequest": {
        "reviews": {
          "totalCount": 3
        }
      }
    }
  }
}

Upvotes: 4

Related Questions