How would I delete all merged or closed PR branches with the GraphQL API?

I’m trying to achieve a GraphQL query + mutation to delete all merged or closed PR’s branches in a repo.

I’ve gotten stumped by how do I query for just PR’s which branches are still existing as I couldn’t find a way to use globs or filtering for the headRefName.

query FindBranchesPRState {
  repository(owner: "foo", name: "bar" ) {
    pullRequests(states: [CLOSED, MERGED], first: 100, headRefName: "") {
      nodes {
        title
        baseRef {
          name
        }
        headRef {
          name
        }
      }
    }
  }
}

The mutation should be fairly easy to achieve with deleteRef

There isn’t a way to query for PRs that only have a non-null headRef. So you would need to query for all closed and merged PRs, then filter the results for the list of headRef names, and then you could delete the branches that still exist.

I hope that helps!