我've come up with a middle-ground solution. Rather than trying to push this complexity onto GraphQL, I'选择在场上设置之前使用 String 类型和 JSON.stringify 我的数据 . 所以一切都得到了字符串化,后来在我的应用程序中,当我需要使用这个字段时,我得到了返回所需对象/数组/布尔值等的结果 .
7
@ 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
}
}
})
3 回答
我've come up with a middle-ground solution. Rather than trying to push this complexity onto GraphQL, I'选择在场上设置之前使用
String
类型和JSON.stringify
我的数据 . 所以一切都得到了字符串化,后来在我的应用程序中,当我需要使用这个字段时,我得到了返回所需对象/数组/布尔值等的结果 .@ mpen的答案很棒,但我选择了更紧凑的解决方案:
然后我的解析器看起来像:
我的
.gql
看起来像:是 . 只需创建一个允许任何内容的新
GraphQLScalarType
.这是我写的一个允许对象 . 您可以稍微扩展一下以允许更多的根类型 .