在模式中定义查询时,如何引用先前声明的 GraphQLEnumType 的值,以将其用作参数的默认值?
假设我定义了以下ObservationPeriod
GraphQLEnumType:
observationPeriodEnum = new GraphQLEnumType {
name: "ObservationPeriod"
description: "One of the performance metrics observation periods"
values:
Daily:
value: '1D'
description: "Daily"
[…]
}
并将其用作查询参数的类型period
:
queryRootType = new GraphQLObjectType {
name: "QueryRoot"
description: "Query entry points to the DWH."
fields:
performance:
type: performanceType
description: "Given a portfolio EID, an observation period (defaults to YTD)
and as-of date, as well as the source performance engine,
return the matching performance metrics."
args:
period:
type: observationPeriodEnum
defaultValue: observationPeriodEnum.Daily ← how to achieve this?
[…]
}
目前我使用实际的'1D'
字符串值作为默认值;这有效:
period:
type: observationPeriodEnum
defaultValue: '1D'
但是有没有办法我可以使用Daily
符号名称呢?我找不到在架构本身中使用名称的方法。有什么我忽略的吗?
我在问,因为我希望枚举类型也可以作为一组常量,并且能够在架构定义中像这样使用它们:
period:
type: observationPeriodEnum
defaultValue: observationPeriodEnum.Daily
天真的解决方法:
##
# Given a GraphQLEnumType instance, this macro function injects the names
# of its enum values as keys the instance itself and returns the modified
# GraphQLEnumType instance.
#
modifiedWithNameKeys = (enumType) ->
for ev in enumType.getValues()
unless enumType[ ev.name]?
enumType[ ev.name] = ev.value
else
console.warn "SCHEMA> Enum name #{ev.name} conflicts with key of same
name on GraphQLEnumType object; it won't be injected for value lookup"
enumType
observationPeriodEnum = modifiedWithNameKeys new GraphQLEnumType {
name: "description: "Daily""
values:
[…]
允许在模式定义中根据需要使用它:
period:
type: observationPeriodEnum
defaultValue: observationPeriodEnum.Daily
当然,这个修饰符实现了它的承诺name
,只要枚举名称不干扰 GraphQLEnumType 现有的方法和变量名称(目前是:在https://github.com/graphql/graphql-js/blob/master/src/type/definition.js#L687)description
_values
_enumConfig
_valueLookup
_nameLookup
getValues
serialize
parseValue
_getValueLookup
_getNameLookup
toString
GraphQLEnumType