Build server APIs with GraphQL and Express #3: Specific argument and The parameter in Query GraphQL

in #utopian-io5 years ago (edited)

Repository

https://github.com/graphql

What Will I Learn?

  • Specific argument
  • The parameter in Query GraphQL

Requirements

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

Resources

Difficulty

Basic

Tutorial Content

Hi, all this time we will go back to discussing the tutorial series on GraphQL. We have made some previous tutorials about GraphQL, now this time we will discuss it more deeply. So for those of you who are just following this tutorial, I suggest you follow the previous tutorial. You can follow the previous tutorial in the curriculum section. In this section, we will discuss the arguments in GraphQL. let's just follow this tutorial.

Specific argument

In this section, we will discuss new things that we will learn in GraphQL, namely arguments. arguments are important things that exist in the query. so later we can choose the data we want specifically. In the previous tutorial, we have succeeded in getting the JSON data list in the forum.

  • Display specific data

In the previous tutorial, we have successfully displayed data from all the data in the forum. well in this section we will learn how to display data that is specific to a JSON data. Because we will retrieve specific data we need something unique from each data, now in this case we need the ID from the forum. For more details, we can see in the example below:

app.js

let schema = buildSchema(`
    type Forum {
        id : ID,
        title : String,
        desc : String
    }
    type Query {
        forum : Forum
        forums : [Forum]
    }
`)

In the forum schema, we have defined the id, title, and desc. Well for the Query section we need to add queries from specific data as follows forum: Forum. The key is the forum and the contents of the Forum schema. Different from the query under the forums: [Forum] we use array because the results of the data will be more than one.

  • Resolvers specific data

We have entered a new query in GraphQL, now to display the query results we will make the resolvers. In this resolvers, we will pass the argument in the form of an ID sent by the user. For more details, we can see in the example below:

app.js

let resolvers = {
    forum : (args)=> {
        return ForumsData.find(el => el.id == args.id)
    },
    forums: ()=> ForumsData
}

The code above is the resolvers that we have in this application. In the resolvers forums we send all the data that is at ForumsData.

I will create a new resolvers with the name of the forum. Because we use javascript we can use the find () function to find the same id from an element at ForumsData. In this resolvers function we will accept the parameter arguments (args)=> { } sent by the user and then we can match the argument with the elements in the ForumsData in this way ForumsData.find(el => el.id == args.id).

  • Pass parameters in graphiql

We already know that we will accept parameters in the forum resolvers. now how do we send parameters in graphiql ?. We can do it like the code below:

graphiql

{
  forums(id : "1") { // Id is the key that we passed and "1" is the value
    
  }
}

id is the key that we passed and "1" is the value. Well, now we can test whether our code works. we can see in the picture below:

ezgif.com-video-to-gif.gif

We can see in the picture above we cannot successfully query, we got an error. e get this error because the queries in our schema do not define parameters in the Query forum.

  • Pass parameters to the query schema

At the top, we have an error. This error occurs because we have not defined the parameters that we will shift to the forum query. for that we usually do it like the code below:

app.js

let schema = buildSchema(`
    type Forum {
        id : ID,
        title : String,
        desc : String
    }
    type Query {
        forum(id : ID!) : Forum,
        forums : [Forum]
    }
`)

To define it we can do it like thisforum (id: ID!): Forum, key id and data type ID. We can add ! which means that this parameter is required. Well, to see the full code on app.js we can see on below?:

app.js

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express()

let ForumsData = [
    {id: 1, title: "This the first Title of Forum", desc: "This the first Description from the first forum"},
    {id: 2, title: "This the second Title of Forum", desc: "This the first Description from the second forum"},
    {id : 3, title: "This the Third Title of Forum", desc: "This the first Description from the Third forum"}
];

let schema = buildSchema(`
    type Forum {
        id : ID,
        title : String,
        desc : String
    }
    type Query {
        forum(id : ID!) : Forum,
        forums : [Forum]
    }
`)

let resolvers = {
    forum: (args)=> {
        return ForumsData.find(el => el.id == args.id)
    },
    forums: ()=> ForumsData
}
app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: resolvers,
    graphiql : true // To set GUI For testing
}))

app.listen(4000, ()=> console.log("Running on port 4000..."));

To see the results we can run the server in nodemon app. our server runs on localhost/4000 app.listen(4000, ()=> console.log("Running on port 4000...")); and then you can access the URL / graphiql. The following are the results:

Screenshot_1.png

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

We can see above we have succeeded in fixing the error and successfully passed the parameters in the Query forum. we have learned how to use parameters in GraphQL and also learned how to access them in graphiql in the next tutorial we will learn about relation systems on GraphQL. thank you for following this tutorial, hopefully, it will be useful for you

Curriculum

GraphQL and Express #1

GraphQL and Express #2

Proof of work done

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

Sort:  

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

  • Again a very interesting and well explained tutorial. Good Job!

  • In the next tutorial put more comments in the code sections. The comments help a lot to better understand the code.

  • 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]

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

Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 10000 upvotes. Your next target is to reach 15000 upvotes.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

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!


@duski.harahap, sorry to see you have less Steem Power.
Your level lowered and you are now a Red Fish!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!