在模式中定义查询时,如何引用先前声明的 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
当然,这种修改fullfils promise ,只是只要枚举名称不GraphQLEnumType现有的方法和变量名(这是目前干扰:
name
,description
,_values
,_enumConfig
,_valueLookup
,_nameLookup
,getValues
,serialize
,parseValue
,_getValueLookup
, _getNameLookup
和 toString
— 参见 https://github.com/graphql/graphql-js/blob/master/src/type/definition.js#L687 中第 687 行周围 GraphQLEnumType
类的定义)
最佳答案
我刚遇到这个。我的枚举:
const contributorArgs = Object.assign(
{},
connectionArgs, {
sort: {
type: new GraphQLEnumType({
name: 'ContributorSort',
values: {
top: { value: 0 },
},
})
},
}
);
在我的查询中,我正在做:
... on Topic {
id
contributors(first: 10, sort: 'top') {
...
}
}
原来你只是不引用该值(在考虑之后这是有道理的;它是枚举类型中的一个值,而不是一个实际值:
... on Topic {
id
contributors(first: 10, sort: top) {
...
}
}
关于graphql - 如何使用 GraphQLEnumType 中的名称作为 GraphQL 查询参数的 defaultValue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666622/