Select * for Github GraphQL Search

2019-02-28 16:17发布

问题:

One of the advantage of Github Search v4 (GraphQL) over v3 is that it can selectively pick the fields that we want, instead of always getting them all. However, the problem I'm facing now is how to get certain fields.

I tried the online help but it is more convolution to me than helpful. Till now, I'm still unable to find the fields for size, score and open issues for the returned repository(ies).

That's why I'm wondering if there is a way to get them all, like Select * in SQL. Thx.

回答1:

GraphQL requires that when requesting a field that you also request a selection set for that field (one or more fields belonging to that field's type), unless the field resolves to a scalar like a string or number. That means unfortunately there is no syntax for "get all available fields" -- you always have to specify the fields you want the server to return.

Outside of perusing the docs, there's two additional ways you can get a better picture of the fields that are available. One is the GraphQL API Explorer, which lets you try out queries in real time. It's just a GraphiQL interface, which means when you're composing the query, you can trigger the autocomplete feature by pressing Shift+Space or Alt+Space to see a list of available fields.

If you want to look up the fields for a specific type, you can also just ask GraphQL :)

query{
  __type(name:"Repository") {
    fields {
      name
      description
      type {
        kind
        name
        description
      }
      args {
        name
        description
        type {
          kind
          name
          description
        }
        defaultValue
      }
    }
  }
}


回答2:

Short Answer: No, by design.

GraphQL was designed to have the client explicitly define the data required, leading to one of the primary benefits of GraphQL, which is preventing over fetching.

Technically you can use GraphQL fragments somewhere in your application for every field type, but if you don't know which fields you are trying to get it wouldn't help you.