We currently have a schema like below
# 'Feed' matches our Feed type used with redis
type Feed {
id: String
author: String
url: String
posts: [Post]
} # 'Post' matches our Post type used with redis
type Post {
id: String
author: String
title: String
html: String
text: String
published: String
updated: String
url: String
site: String
guid: String
}
Notice feed can also return an array of Post, to allow nested queries, we have to define them in resolvers after the Query:
module.exports.resolvers = {
Query: {
//Queries are here
},
Feed: {
posts: async parent => {
const maxPosts = await getPostsCount();
const ids = await getPosts(0, maxPosts);
const posts = await Promise.all(ids.map(postId => getPost(postId)));
const filteredPosts = posts.filter(post => post.author === parent.author);
return filteredPosts;
},
},
};
What the above code does is get all Posts in the database, then filter the Posts only returning Posts that have the same author as the returned value of the feed author. For example if I'm running the following query in GraphQL
{
getFeedById(id: "123") {
author
id
posts {
title
}
}
}
and the author name is Marie, the parent parameter that is provided to the nested query (posts) will be the results of the getFeedById which in this case the author name is Marie.
Real life data using a classmate of mine:
No comments:
Post a Comment