Reputation: 1720
I'm less than a couple of weeks into using Apollo and GraphQL, and I'd like to retrieve multiple objects via GraphQL, but it won't allow me to.
With the query as:
const GET_ALL_PURCHASES_QUERY = (statusOfPurchase) => {
return gql`
query {
getAllPurchases(statusOfPurchase: "${statusOfPurchase}") {
id
customerInformation {
customerName
customerEmailAddress
}
createdAt
updatedAt
}
}
`
}
... and in the schema:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
getAllPurchases: {
type: PurchaseType,
args: {
statusOfPurchase: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve(parent, args) {
return PurchasesModel.schemaForPurchases.find({
statusOfPurchase: args.statusOfPurchase
}).limit(10)
.then(purchases => {
console.log('Schema:getAllPurchases()', purchases)
return purchases
})
}
}
}
})
Result in Node via the Terminal is:
Schema:getAllPurchases() [
{
_id: 60351a691d3e5a70d63eb13e,
customerInformation: [ [Object] ],
statusOfPurchase: 'new',
createdAt: 2021-02-23T15:08:25.230Z,
updatedAt: 2021-02-23T15:08:25.230Z,
__v: 0
},
{
_id: 60351b966de111716f2d8a6d,
customerInformation: [ [Object] ],
statusOfPurchase: 'new',
createdAt: 2021-02-23T15:13:26.552Z,
updatedAt: 2021-02-23T15:13:26.552Z,
__v: 0
}
]
Correct.
But in the application within Chrome, it's a single object with null as the value of each field.
With the query as:
const GET_ALL_PURCHASES_QUERY = () => {
return gql`
query {
getAllPurchases {
id
customerInformation {
customerName
customerEmailAddress
}
createdAt
updatedAt
}
}
`
}
... and with the appropriate changes to the schema, the result is the same as before, where I see two objects in Node but a failed single object in Chrome.
If I change: return purchases
to: return purchases[0]
I see the first object in Chrome with the correct values.
How am I supposed to return more than one object?
Upvotes: 4
Views: 1287
Reputation: 7326
Your type for the getAllPurchases
field is set to PurchaseType
in the schema. You want to use new GraphQLList(PurchaseType)
to have the return type be a list of purchases. That's why when you try to use the schema, it returns null if the types are bad, but correctly returns a purchase if you do return a single element.
See the graphql docs for an example of this.
Upvotes: 2