I have an issue with GraphQL (Specifically, implementing GraphQLList)
I have a query getItemByName
that correctly returns an Item
, with Type itemType
. But I haven't been able to implement a getItemList
(Or a proper example btw). I know that it's supposed to have a type that implements GraphQLList.
But am i doing it right? What's the data format that resolve
should recieve? (Or that getItems()
should return). An array of objects? Should those objects be implementing "itemType" definition? Should an interface be implemented?
export const itemType = new GraphQLObjectType({
name: 'Item',
fields: {
name: {
type: GraphQLString,
description: 'Item Name',
},
},
});
const itemListType = new GraphQLObjectType({
name: 'ItemsList',
fields: {
items: {
type: new GraphQLList(itemType),
description: 'List of items',
},
},
});
{...}
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
itemList: {
type: itemListType,
resolve: () => getItems(),
}
}
})
})
As it is now, the query:
itemList {
items {
name
}
}
its returning:
{
"data": {
"itemList": {
"items": null
}
}
}
Any help is really really welcome! :D
Regards!
Fixed the issue. It was not a problem with the structure of data that I was returning, it was the way i was defining a the query.
The
coworkList
query definition is that is now being passed into the schema. Works great! const schema = new GraphQLI'll first explain the root cause of your problem. Then I'll discuss how GraphQLList is generally used.
In your schema query,
itemList
field is of typeitemListType
. Now thisitemListType
has a fielditems
. Therefore, the query'sitemList
field must be resolved to an object which has anitems
field. But thegetItems()
function returns an array or a promised array and does not have fielditems
. That's why you're getting"items": null
in the query response.Now about the confusion around GraphQLList: if it's just a list, there's actually no need to define a separate GraphQL type for that. In your query, you include a field with type GraphQLList of item type:
If your list is not that simple, for instance,
itemList
actually has two fields(oldItems, newItems - both are lists), you should define a separate type. Remember to modify the resolve function accordingly:(By the way, your code has some syntax errors like itemsList, itemList, itemsListType, itemListType. I have edited your question. The changes will appear after my edit is approved.)
getItems()
should return an array of itemType objects (or a promise for one). What those itemTypes look like is up to you. They'll simply be passed to theresolve
function of the fields that you asked for initemType
.