Build server APIs with GraphQL and Express #5: Display relation data and Access data relation in resolvers

in utopian-io •  5 years ago 

Repository

https://github.com/graphql

What Will I Learn?

  • Display relation data
  • Access data relation in resolvers

Requirements

  • Basic Javascript
  • Install Node
  • Install Express
  • Install GraphQL

Resources

Difficulty

Basic

Tutorial Content

In this tutorial, we will continue the previous tutorial series about GraphQL on the API that we created. This tutorial will still continue the relation system that we created in the previous tutorial, in the previous tutorial we created a relation system but there are still errors when we use it in graphiql. For those of you who have just followed this tutorial, I suggest you follow the previous tutorial which is in the curriculum section below. for more details, we can continue with the following tutorial.

Display the relation

In the previous tutorial, we have created a system of relations between forum data and user data. but we have not shown the results of the relation to graphiql, now here we will learn how to display the relation in graphiql and can be consumed as the correct data. In the following, we will see a sample data relation that has not yet appeared:

app.js

let schema = buildSchema(` // schema
    type Forum {
        id : ID,
        title : String,
        desc : String,
        user:User
    }

    type User {
        id : ID,
        name : String
    }

    type Query {
        forum(id : ID!) : Forum,
        forums : [Forum],
        user(id :ID!) : User,
        users: [User]
    }
`)

let resolvers = { // Resolvers
    forum: (args)=> {
        return ForumsData.find(el => el.id == args.id)
    },
    forums: ()=> ForumsData,
    user: (args) => {
        return userData.find(el => el.id == args.id)
    },
    users:()=> userData
}

ezgif.com-video-to-gif (5).gif

We can see in the picture above, we have successfully used relations in resolvers users. but we cannot display the results from the forum data. This is because we do not pass the ID to the query we are using. to display relationship data we can use methods like the following.

  • Pass the relation data on the resolvers

The thing that causes us to not be able to display relations data on our graphiql is the resolvers users. we can see in the user's resolvers we only return the value of the user data userData, not returning the value from the data forum ForumData. We can see the sample code in the picture below:

app.js

let resolvers = {
    forum: (args)=> {
        return ForumsData.find(el => el.id == args.id)
    },
    forums: ()=> ForumsData,
    user: (args) => {
        return userData.find(el => el.id == args.id)
    },
    users:()=> userData // Just return user data
}

We can see in the code above we will change the resolvers forums first so that user data can appear on the resolvers forums.

Access user data in the forum

The first thing we will do is access the user data in the resolvers forums. I can do it in the following way:

app.js

let resolvers = {
    forum: (args)=> {
        let _forum = ForumsData.find(el => el.id == args.id)
        let _user = userData.find(el => el.id == _forum.id)

        _forum['user'] = _user
        return _forum
    },
}

Screenshot_4.png

The code above is the code from the resolvers forums, to display user data we need a little trick. So we will save the forum data that has been selected based on its id into a forum variable let _forum = ForumsData.find(el => el.id == args.id) with find()function.

Well then we will also choose user data by using the find () function, but the difference is that we will look for user data by matching user id with forum id. try to look at the code line below:

userData.find(el => el.id == _forum.id)

Here we can see we are using _forum.id instead of args.id, this is done to match the user with the forum data.

After that, we can save the results in an array of variables _forum like the following _forum['user'] = _user. We save the user data in the key array user. So later we will access the key user to get the data. We can see the results as shown below:

ezgif.com-video-to-gif (6).gif

We can see in the picture above we have successfully displayed user data on the resolvers forums. The data comes from the userId key at ForumsData as we see in the picture below:

Screenshot_3.png

Well, what we do from the resolvers forums side, we will also use the same concept on resolver users.


Access forum data in the data

In the previous section, we have displayed the user data in the forum resolvers. In this section we will display the forum data on the resolvers of users, the concept we use will be the same as what we did on the resolvers forums. for more details, we can see in the example below:

app.js

    user: (args) => {
        let _user = userData.find(el => el.id == args.id)
        let _forums = forumData.filter(el => el.userId == _user.id)

        _user['forums'] = _forums
        return _user
    },

There are some things we need to pay attention to in the user resolver. here we need to understand that under 1 user can have multiple forums, so we cannot use find () because find only searches for one data. We will use the filter () method. We can use the method like this forumData.filter(el => el.userId == _user.id).

By using this method we will filter data that has a user id _user.id that matches forum.userId. After that, we will save the results in _user variables with key forums _user ['forums']. We can see the results like the example below:

ezgif.com-video-to-gif (7).gif

We can see in the picture above we have successfully displayed the data that is in the forums at the resolvers users, this means that our relations system is running well. The relation system that we build is a one to one relations system, the relations are interrelated between one with one other data, enough until here my tutorial this time may be useful for you. thank you

Curriculum

GraphQL and Express #1

GraphQL and Express #2

GraphQL and Express #3

Proof of work done

https://github.com/milleaduski/api-graphql

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:

  • Nice work on the explanations of your code, although adding a bit more comments to the code can be helpful as well.

  • Thanks for following some of our suggestions in your previous tutorials.

Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

this is my last contribution in utopian. thank you very much @portugalcoin has reviewed many of my tutorials. You always give good advice and you are also a good person. enjoy your day and still be a good person. see you bro.

Thank you for your review, @portugalcoin! Keep up the good work!

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

#utopian-io has been a gift. We would like to keep its curation-efforts alive here on 'marlians.com'. We want to curate and reward 'contributions to open-source projects' with MARLIANS on the the marlians.com tribe, a SCOT-enabled steem condenser. Contributions can include suggestions, graphics, bug-finds, code etc. You can simply add in #marlians to your #utopian-io posts and it will appear on https://www.marlians.com/created/utopian enabling you to earn some MARLIANS along with steem/sbd. You can also post directly to steem via 'marlians.com'. We have some overseers who curate and who can render you help too. You can find them enlisted on https://www.marlians.com/created/utopian