Creating relation between two Object Types in GraphQL using Node JS

Hello everyone, in this article we are going to look at how we can create relations between two object types in GraphQL.



This is the second part of GraphQL with Node, MongoDB and React series

If you have missed the first part here is the link : 

Set up graphQL backend using Node.js, express and mongoDB - Step by Step

Reading the above article is important as we are going to use the same example and and continue code from where we left there.

Ok until last time we have created two object types Game and Publisher. 
Game has field like id,name, genre and publisher has fields id, name and established. Now lets refer the diagram once again



As you can see each game has a publisher. So we need to link Game type with PublisherType for that to happen we need to add a key to each game data which will hold reference for it's Publisher

Ok so let's modify the dummy data array for Games


const games = [
    {name: "FIFA",id:"1",genre:"Sports, simulation",pubId:"1"},
    {name: "PUBG",id:"2",genre:"Battle royale",pubId:"2"},
    {name: "Call of Duty: Mobile",id:"3",genre:"First-person shooter, battle royale",pubId:"3"}
]

Now we have a reference with each game entry for it's Publisher. Mapping that field with Publishers id we can get book data with its publisher details

const GameType = new GraphQLObjectType({
    name: 'Game',
    fields : () => ({
        name: {type : GraphQLString},
        id: {type : GraphQLString},
        genre: {type : GraphQLString},
        publisher:{
            type: PublisherType,
            resolve(parent,args){
                return _.find(publishers,{id: parent.pubId})
            }
        }
    })
})

That's it we mapped game's pubId with Publisher's id field.

Now lets test with below query

{
    game(id:"2"){
        name,
        id,
        publisher{
            name
        }
    }
}

Use postman to test the same


Nice... now we are getting publisher details with game.

Thanks for your time. Kindly subscribe my blog.

Comments

Popular posts from this blog

Best coding practice and structure for redux saga with react hooks | Separate watcher and worker saga | React clean code

How to use redux with React Hooks - Creating TodoList

Setting up Redux Devtools for React applications