是否可以指定GraphQL中的字段应该是黑盒子,类似于Flow具有“任何”类型的方式?我的架构中有一个字段应该能够接受任意值,可以是String,Boolean,Object,Array等。
发布于 2019-06-06 09:32:59
我想出了一个中间解决方案。而不是试图将这种复杂性推到GraphQL上,我选择在将其设置到字段之前使用String
类型和JSON.stringify
数据。所以一切都得到了字符串化,后来在我的应用程序中,当我需要使用这个字段时,我JSON.parse
得到了返回所需对象/数组/布尔值等的结果。
发布于 2019-06-06 10:42:59
@ mpen的答案很棒,但我选择了更紧凑的解决方案:
const { GraphQLScalarType } = require('graphql')
const { Kind } = require('graphql/language')
const ObjectScalarType = new GraphQLScalarType({
name: 'Object',
description: 'Arbitrary object',
parseValue: (value) => {
return typeof value === 'object' ? value
: typeof value === 'string' ? JSON.parse(value)
: null
},
serialize: (value) => {
return typeof value === 'object' ? value
: typeof value === 'string' ? JSON.parse(value)
: null
},
parseLiteral: (ast) => {
switch (ast.kind) {
case Kind.STRING: return JSON.parse(ast.value)
case Kind.OBJECT: throw new Error(`Not sure what to do with OBJECT for ObjectScalarType`)
default: return null
}
}
})
然后我的解析器看起来像:
{
Object: ObjectScalarType,
RootQuery: ...
RootMutation: ...
}
我.gql
看起来像:
scalar Object
type Foo {
id: ID!
values: Object!
}
https://stackoverflow.com/questions/-100006939
复制相似问题