简体   繁体   中英

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

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 (eg 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 (eg 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.

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"
        }
      ]
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM