Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simplified graphql explanation
// Say we need to display list of posts showing *only* their titles
// and name of the post author
// without graphql
const data = {
posts: null,
usersById: {},
};
get('/api/posts')
.then(posts => {
/* post object has fields that we need and don't need, for example
* { title, authorId, timestamp, content } */
data.posts = posts;
return Promise.all(posts.map(post => get(`/api/users/${post.authorId}`)));
})
.then(users => {
/* user object has fields that we need and don't need, for example
* { name, lastName, avatarUrl, age, dateCreated, etc... } */
users.reduce((acc, user) => {
acc[user.id] = user;
return acc;
}, data.usersById);
})
.then(() => {
/* we can finally display posts like we wanted */
const toRender = data.posts.map(post => (
<p>title: {post.title}, author: {data.usersById[post.authorId].name}</p>
));
});
// with graphql
get('/api/graphql', `{ posts: { title, author: { name } } }`)
.then(posts => {
const toRender = posts.map(post => (
<p>title: {post.title}, author: {post.author.name}</p>
));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment