graphql,联合标量类型? [英] graphql, union scalar type?
问题描述
payload
字段可以是Int
或String
标量类型.
当我将其写为联合体类型时:
The payload
field can be Int
or String
scalar type.
when I write it like union type:
const schema = `
input QuickReply {
content_type: String
title: String
payload: Int | String
image_url: String
}
`
我遇到一个错误:
GraphQLError: Syntax Error GraphQL request (45:18) Expected Name, found |
44: title: String
45: payload: Int | String
^
46: image_url: String
GraphQL
似乎不支持联合标量类型.
It seems GraphQL
does not support union scalar type.
那么,我该如何解决这种情况?
So, how can I solve this situation?
推荐答案
标量不能用作并集的一部分,因为根据规范,并集明确地表示一个对象,该对象可能是GraphQL对象类型的列表之一."相反,您可以使用自定义标量.例如:
Scalars can't be used as part of unions, since per the specification, unions specifically "represent an object that could be one of a list of GraphQL Object types." Instead, you can use a custom scalar. For example:
const MAX_INT = 2147483647
const MIN_INT = -2147483648
const coerceIntString = (value) => {
if (Array.isArray(value)) {
throw new TypeError(`IntString cannot represent an array value: [${String(value)}]`)
}
if (Number.isInteger(value)) {
if (value < MIN_INT || value > MAX_INT) {
throw new TypeError(`Value is integer but outside of valid range for 32-bit signed integer: ${String(value)}`)
}
return value
}
return String(value)
}
const IntString = new GraphQLScalarType({
name: 'IntString',
serialize: coerceIntString,
parseValue: coerceIntString,
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return coerceIntString(parseInt(ast.value, 10))
}
if (ast.kind === Kind.STRING) {
return ast.value
}
return undefined
}
})
此代码有效地组合了Int和String类型的行为,同时仍强制使用32位带符号整数的范围.但是,您可以具有所需的任何类型强制行为.查看源代码,以了解如何内置标量工作,或
This code effectively combines the behaviors for both the Int and String types, while still enforcing the range for 32-bit signed integers. However, you could have whatever type coercion behavior you want. Check out the source code to see how the built-in scalars work, or this article for more details around how custom scalars work.
请注意,如果您要为 output 字段返回多个标量之一,则可以对 parent 类型使用并集来获得相似的结果.例如,这是不可能的:
Note that if you're trying to return one of several scalars for an output field, it's possible to utilize a union for the parent type to achieve a similar result. For example, this isn't possible:
type Post {
content: String | Int
}
但是您可以执行以下操作:
but you can do the following:
type PostString {
content: String
}
type PostInt {
content: Int
}
union Post = PostString | PostInt
这篇关于graphql,联合标量类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!