是否可以指定GraphQL中的字段应该是黑盒子,类似于Flow具有“任何”类型的方式?我的架构中有一个字段应该能够接受任意值,可以是String,Boolean,Object,Array等。
发布于 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
复制相似问题