3 回答

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
我選擇了一個(gè)更緊湊的解決方案:
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!
}

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
我提出了一個(gè)中間立場(chǎng)的解決方案。我沒有嘗試將這種復(fù)雜性推到GraphQL上,而是選擇僅使用String
類型并JSON.stringify
在將其設(shè)置為字段之前對(duì)數(shù)據(jù)進(jìn)行查詢。所以一切都變得字符串化了,后來在我的應(yīng)用程序中,當(dāng)我需要使用此字段時(shí),我JSON.parse
得到的結(jié)果是返回所需的對(duì)象/數(shù)組/布爾值/等。
添加回答
舉報(bào)