I've created a GraphQLSchema with two fields, both using a resolve()
to get the data from a mongoDB.
With that, the query...
{
article(id: "Dn59y87PGhkJXpaiZ") {
title
},
articleContent(id: "Dn59y87PGhkJXpaiZ") {
_id,
content(language: "en"),
type
}
}
...results in:
{
"data": {
"article": {
"title": "Sample Article"
},
"articleContent": [
{
"_id": "Kho2N8yip3uWj7Cib",
"content": "group",
"type": "group"
},
{
"_id": "mFopAj4jQQuGAJoAH",
"content": "paragraph",
"type": null
}
]
}
}
But I need a result structure like this (content should be inside of article object):
Expected result
{
"data": {
"article": {
"title": "Sample Article",
"content": [
{
"_id": "Kho2N8yip3uWj7Cib",
"content": "group",
"type": "group"
},
{
"_id": "mFopAj4jQQuGAJoAH",
"content": "paragraph",
"type": null
}
]
},
}
}
For me the problem are both async mongoDB resolves in my schema:
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLObjectType({
name: 'article',
fields: {
title: {
type: GraphQLString,
resolve (parent) {
return parent.title
}
}
}
}),
args: {
id: { type: new GraphQLNonNull(GraphQLID) }
},
async resolve ({ db }, { id }) {
return db.collection('content').findOne({ _id: id })
}
},
articleContent: {
type: new GraphQLList(new GraphQLObjectType({
name: 'articleContent',
fields: {
_id: { type: GraphQLID },
type: { type: GraphQLString },
content: {
type: GraphQLString,
args: {
language: { type: new GraphQLNonNull(GraphQLString) }
},
resolve (parent, { language }, context) {
return parent.content[language][0].content
}
}
}
})),
args: {
id: { type: new GraphQLNonNull(GraphQLID) }
},
async resolve ({ db }, { id }) {
return db.collection('content').find({ main: id }).toArray()
}
}
}
})
})
Update
If I nest the content inside the article, I do get the error Cannot read property 'collection' of undefined
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLObjectType({
name: 'article',
fields: {
title: {
type: GraphQLString,
resolve (parent) {
return parent.title
}
},
articleContent: {
type: new GraphQLList(new GraphQLObjectType({
name: 'articleContent',
fields: {
_id: { type: GraphQLID },
type: { type: GraphQLString },
content: {
type: GraphQLString,
args: {
language: { type: new GraphQLNonNull(GraphQLString) }
},
resolve (parent, { language }, context) {
return parent.content[language][0].content
}
}
}
})),
args: {
id: { type: new GraphQLNonNull(GraphQLID) }
},
async resolve ({ db }, { id }) { // db is undefined here!!
return db.collection('content').find({ main: id }).toArray()
}
}
}
}),
args: {
id: { type: new GraphQLNonNull(GraphQLID) }
},
async resolve ({ db }, { id }) {
return db.collection('content').findOne({ _id: id })
}
}
}
})
})