Skip to content

Instantly share code, notes, and snippets.

@everdimension
Created October 10, 2017 15:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save everdimension/8f22f3ad64fbe9ba215674748c862f84 to your computer and use it in GitHub Desktop.
Save everdimension/8f22f3ad64fbe9ba215674748c862f84 to your computer and use it in GitHub Desktop.
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