数据库查询的输出:
"_id": "5cd532a8452d22435be6a9ac",
"properties": {
"somerandomname": "asd,
"someotherrandomname": "adsad"
}
如何构建这种类型的graphql?
类似的东西:
export const aaa = new GraphQLObjectType({
name: 'aaa',
fields: () => ({
_id: {
type: GraphQLString
},
properties: {
type: GraphQLObjectType
},
})
});
但是GraphQLObjectType需要配置。
有什么想法吗?
答案 0 :(得分:2)
为了实现这一点,您必须定义一个返回GraphQLScalarType
的自定义json
。您可以在custom-scalars中详细了解它。
或者您可以只使用软件包graphql-type-json,该软件包基本上是返回json的GraphQLScalarType
的实现,例如:
const {GraphQLJSON} = require('graphql-type-json');
const aaa = new GraphQLObjectType({
name: 'aaa',
fields: () => ({
_id: {
type: GraphQLString
},
properties: {
type: GraphQLJSON
},
})
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
myField: {
type: aaa,
resolve(parent, args) {
// Here: return your object as it is
// for example:
return {
_id: "this",
properties: {
somerandomname: "asd",
someotherrandomname: "asdad",
"what?!": "it also has strings",
noway: [
"what about them arrays"
]
}
};
}
},
}
})
然后,如果您查询:
{
myField {
_id
properties
}
}
您将获得输出:
{
"data": {
"myField": {
"_id": "this",
"properties": {
"somerandomname": "asd",
"someotherrandomname": "asdad",
"what?!": "it also has strings",
"noway": [
"what about them arrays"
]
}
}
}
}