Hi noobie to graphql ive created a simple node.js project that communicates with apollo Server. The issues is that i want to nest comments that relate to each product. As you can see ive added productId in both types.
below in Apollo Explorer i want to run the below query to nest comment relating to each product my plan is store each products and comments in seperates db tables eventually.
query {
allProducts {
product_Description
comment {
commentBody
}
}
}
const { ApolloServer, gql } = require('apollo-server')
let products = [
{
productId : 101,
productTitle : "EasyJet Summer Flight Sale 2023 - 100,000 flights on offer - From £29.99",
product_Description : " cheaps flights available",
price : "£302",
},
{
productId : 102,
productTitle : "Apple Leather Case with MagSafe for iPhone 13 Pro Max Midnight",
product_Description : "Aple leather case get this deal!!!",
price : "£29"
},
{
productId : 103,
productTitle : "Xiaomi Redmi Note 10 Pro - Mobile Phone 6 128 GB",
product_Description : "Another chinese mobile phone yarn !!!",
price : "£120"
}
]
let comments = [
{
commentId : 1,
commentBody : "amazing product really cheap flights",
productId : 101,
},
{
commentId : 2,
commentBody : "amazing product really cheap flights",
productId : 102,
},
{
commentId : "3",
commentBody : "amazing product really cheap flights",
productId : 103,
},
]
const typeDefs = gql `
type Product {
productId: ID!,
productTitle: String!,
product_Description: String!,
price: String!
comment: [Comment]
}
type Comment {
commentId: Int!,
commentBody: String!,
}
type Query {
productCount: Int!
allProducts: [Product!]!
allComments: [Comment!]!
findProduct(productTitle: String!): Product
}
`
const resolvers = {
Query: {
productCount: () => products.length,
allProducts: () => products,
allComments: () => comments,
findProduct: (root, args) => products.find(p => p.productTitle === args.productTitle),
},
Product: {
comment: parent => {
console.log('parent data',parent)
return parent.comment.map(commentList => parent.productId === commentList.productId)
}
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
})
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`)
})
this is error im getting
{
"errors": [
{
"message": "Cannot return null for non-nullable field Comment.commentId.",
"locations": [
{
"line": 6,
"column": 9
any help greatfully appreciated :)
CodePudding user response:
You're mapping when you should be filtering. Also your comments aren't attached to the parent, they are just a variable in scope.
Change:
return parent.comment.map(
commentList => parent.productId === commentList.productId
)
to:
return comments.filter(
el => parent.productId === el.productId
)