我试图创建一个我认为是阿波罗GraphQL的联合或Enum,然而,我的理解是在菜鸟的水平。下面写代码的正确方法是什么?
路径:sampleType.graphql
union GridSize = 'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
type Element {
xs: GridSize
}发布于 2021-10-16 01:07:51
GraphQL不像您所做的那样支持字符串文本或数字文本。例如,在TypeScript中,您可以使用这样的文字:
type GridSize = 'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12GraphQL没有这样的东西。您可以使用枚举:
enum GRID_SIZE {
SOME_VALUE_HERE
SECOND_OPTION
}但是不幸的是,您的示例无法工作,因为枚举中的值必须遵循这个正则表达式/[_A-Za-z][_0-9A-Za-z]*/,这意味着它不能以(或仅是)一个数字开始。
那你能做什么?
您可以使用Dani R's commented answer,只需创建一个接受Int | String的联合。这是最简单的事。或者,如果您想将它作为自己的类型“真正”--它的行为方式(主要是)--您可以创建一个自定义标量:
"""
The following values are accepted
'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
"""
scalar GridSize
type Element {
xs: GridSize
}然后,您需要创建标量解析器:
const { GraphQLScalarType, Kind } = require('graphql')
const allowedValues = ['auto', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
const gridSizeScalar = new GraphQLScalarType({
name: 'GridSize',
description: `
The following values are accepted
'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
`,
serialize(value) {
// outgoing from your code
if (!allowedValues.includes(value)) {
// or you could throw, but your own code had better not return bad values :)
console.error('something')
return null
}
return value
},
parseValue(value) {
// incoming from input
if (!allowedValues.includes(value)) {
// you probably have a better error message than I do
throw new RangeError('Not a valid Grid Size')
}
return value
},
parseLiteral(ast) {
if ((ast.kind !== Kind.INT) && (ast.kind !== Kind.STRING)) {
// if this value isn't a string or number, it's definitely not OK
return null
}
return ast.value
}
})把这个塞进你的解决方案
const resolvers = {
Query: {},
Mutation: {},
Whatever: {},
GridSize: gridSizeScalar
}https://stackoverflow.com/questions/69578405
复制相似问题