进行内省时选择非必填字段

时间:2019-12-12 17:07:35

标签: graphql introspection

我将GraphQL与JS中的Apollo Server和Client一起使用,并尝试自省我的模式。

简化,我有一个类似的架构:

input LocationInput {
  lat: Float
  lon: Float
}

input CreateCityInput {
  name: String!
  location: LocationInput
}

我用这样的内省来查询它:

fragment InputTypeRef on __Type {
  kind
  name
  ofType {
    kind
    name
    inputFields {
      name
      type {
        name
        kind
        ofType {
          kind
          name
          inputFields {
            name
            type {
              name
              kind
            }
          }
        }
      }
    }
  }
}

query CreateCityInputFields {
  input: __type(name: "CreateCityInput") {
    inputFields {
      name
      description
      type {
        ...InputTypeRef
      }
    }
  }
}

结果我收到:

{
  "data": {
    "input": {
      "inputFields": [
        {
          "name": "name",
          "description": "",
          "type": {
            "kind": "NON_NULL",
            "name": null,
            "ofType": {
              "kind": "SCALAR",
              "name": "String",
              "inputFields": null
            }
          }
        },
        {
          "name": "location",
          "description": "",
          "type": {
            "kind": "INPUT_OBJECT",
            "name": "LocationInput",
            "ofType": null
          }
        }
      ]
    }
  }
}

可以看到:latlon丢失了。如果我在LocationInput中根据需要(location: LocationInput!设置了CreateCityInput,则会收到丢失的latlon

如何在不需要避风港lat的情况下查询lonLocationInput

1 个答案:

答案 0 :(得分:0)

似乎我对内省的查询有误。将inputField部分从ofType移到较高的位置可解决此问题:

  kind
  name
  inputFields {
    name
    description
    type {
      kind
      name
      ofType {
        kind
        name
      }
    }
  }
  ofType {
    kind
    name
    inputFields {
      name
      description
      type {
        kind
        name
        ofType {
          kind
          name
        }
      }
    }
  }
}

query CreateCityInputFields {
  input: __type(name: "CreateCityInput") {
    inputFields {
      name
      description
      type {
        ...InputTypeRef
      }
    }
  }
}

解决了这个问题。