Skip to content

Instantly share code, notes, and snippets.

@timoyuen
Forked from everdimension/graphql-example.js
Created January 2, 2019 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timoyuen/8712a8a4165f7f3f3af25cab2c1b08c5 to your computer and use it in GitHub Desktop.
Save timoyuen/8712a8a4165f7f3f3af25cab2c1b08c5 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