GitHub GraphQL 过滤器多变量语言过滤器

GitHub GraphQL filter multi variable language filter

我正在尝试使用 GitHub 的 GraphQL API 来查找与查询匹配但限于特定语言的存储库列表。但是,我在文档中找不到任何与典型的在线搜索支持的多变量语言过滤器相关的内容,也找不到任何类似的东西通常是如何用 GraphQL 完成的。

{
  search(query: "language:java", type: REPOSITORY, first: 10) {
    repositoryCount
    edges {
      node {
        ... on Repository {
          nameWithOwner
          forkCount
          hasIssuesEnabled
          hasProjectsEnabled
          homepageUrl
          id
        }
      }
    }
  } 
}

我想传递两个关于语言的参数并显示结果,但是这个query只是使用字符串来搜索。我需要像这样以多项形式发送请求 language:['go','java','javaScript']

作为解决方法,您可以使用 aliases to build dynamic query with many search query targetting a specific language and fragments 来避免在查询中重复 SearchResultItemConnection

{
  go: search(query: "language:go", type: REPOSITORY, first: 10) {
    ...SearchResult
  }
  java: search(query: "language:java", type: REPOSITORY, first: 10) {
    ...SearchResult
  }
  javascript: search(query: "language:javascript", type: REPOSITORY, first: 10) {
    ...SearchResult
  }
}

fragment SearchResult on SearchResultItemConnection {
  repositoryCount
  edges {
    node {
      ... on Repository {
        nameWithOwner
        forkCount
        hasIssuesEnabled
        hasProjectsEnabled
        homepageUrl
        id
      }
    }
  }
}

Try it in the explorer

请注意,它仅适用于 OR 查询(java 或 java 脚本或语言列表)但不适用于 AND

可以通过编程方式构建请求,例如在这个 脚本中:

import requests

token = "YOUR_TOKEN"
languages = ["go","java","javaScript"]

query = """
{
  %s
}

fragment SearchResult on SearchResultItemConnection {
  repositoryCount
  edges {
    node {
      ... on Repository {
        nameWithOwner
        forkCount
        hasIssuesEnabled
        hasProjectsEnabled
        homepageUrl
        id
      }
    }
  }
}
"""

searchFragments = "".join([
    """
    %s: search(query: "language:%s", type: REPOSITORY, first: 10) {
      ...SearchResult
    }
    """ % (t,t) for t in languages
])
r = requests.post("https://api.github.com/graphql",
    headers = {
        "Authorization": f"Bearer {token}"
    },
    json = {
        "query": query % searchFragments
    }
)
print(r.json()["data"])