Given a set of GraphQL variable types, is it possible to use the client schema to create a map of all valid values for each type in the set

扶醉桌前 提交于 2019-12-12 12:14:24

问题


Title mostly says it all: I'm building a react / relay application which will allow the user to dynamically create charts at runtime displaying their various income streams over a specified time range. One feature of this chart is the ability of the user to specify the sampling interval of each income stream (e.g. YEAR, QUARTER, MONTH, WEEK, etc.) as a parameter of each stream.

These values are defined in the schema as a GraphQLInputObjectType instance as follows:

enum timeSeriesIntervalEnum {
  YEAR
  QUARTER
  MONTH
  WEEK
}

On the client-side, I have react-relay fragments defined of the following form:

fragment on BalanceSheet {
  income {
    # some income stream
    afterTax {  
      values(interval: $samplingInterval)
      dates(interval: $samplingInterval)
    }
  }
}

This variable value will be populated as part of dropdown menu in a separate component where each value in the dropdown should correspond to a valid timeSeriesIntervalEnum value.

Although it would certainly be possible to simply hardcode these values in, the underlying API is still being changed quite often and I would like to reduce coupling and instead populate these fields dynamically by specifying the variable type for a given dropdown (e.g. timeSeriesIntervalEnum) and then use the graphql client schema to parse the values and populate either a config json file (pre-runtime) or assign the values dynamically at runtime.

NOTE: I already do a bit of query string and fragment transpilation pre-start, so I'm not averse to creating json config files as part of this process if that is required.


回答1:


This can be done using an introspection query.

In your case this is one possible solution:

{
    __type(name: "timeSeriesIntervalEnum") {
    name
    enumValues {
      name
    }
  }
}

The response contains a list of all possible types:

{
  "data": {
    "__type": {
      "name": "timeSeriesIntervalEnum",
      "enumValues": [
        {
          "name": "YEAR"
        },
        {
          "name": "QUARTER"
        },
        {
          "name": "MONTH"
        },
        {
          "name": "WEEK"
        }
      ]
    }
  }
}


来源:https://stackoverflow.com/questions/41840798/given-a-set-of-graphql-variable-types-is-it-possible-to-use-the-client-schema-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!