GraphQL Crash Core with Rails (part 2)

Tram Ho

Hello guys!

In the last post, we also went to learn and know what GraphQL is? How it works and why is it so popular, and with some other GraphQL , in today’s post, you and I will continue to learn it through a demo project. Use Ruby On Rails as the main framework with GraphQL . But first to do this we need to install GraphQL on the environment of rails.

Install GraphQL

  • First we need to create a demo project

rails new graphql-ruby --skip-yarn --skip-action-mailer --skip-action-cable --skip-sprockets --skip-coffee --skip-javascript --skip-turbolinks --api

  • then move into project directory:

cd graphql-ruby

Generating models:

Here we create 2 model order and payment

And we set a relationship between 2 tables as 1-n:

Create Database

  • we run the command:

$ rails db:create to create a SQLite3 development database (default)

and

  • run $ rails db:migrate to models and database, then we need some sample data to execute,

ADD seed data

Open the seed.rb file, this is where we will create the sample data to serve the process

Add a few example objects to start the database:

After creating a few sample objects, we need to run the following command to write data to the database:

$ rails db:seed

We have basically completed the setup at this point, but we haven’t seen any graphQL related yet. Right now we will come to the important part of adding GraphQL to the project.

Adding GraphQL

  • First we need to add the graphql gem to the graphql file

Then run the command bundle install to install the gem in your application.

Install GraphQL with ‘rails generate’

After the above step we need to proceed to the command:

$ rails generate graphql:install after running this command it will automatically add a directory /graphql/ to our main directory diagram, and also a GraphQL dedicated controller you can see. at /controllers/graphql_controller.rb.

Add GraphQL objects for models:

Now we need to create GraphQL objects to match our models:

We simply run the following 2 commands:

Done, we now have all the files and folders needed to create our first Query! However, some of them still need some extra code. Next ! We need to define the GraphQL types and their fields:

This allows us to access PaymentType objects containing the id field (with the special primary key ID), and the amount field will be of the Float format. Since both are set to null: false, getting a Query response with nil in either field will cause an error.

GraphQL objects will inherit Types::BaseObject . So, once we defined our class PaymentType < Types::BaseObject class, we now have Types::PaymentType . We can use these Custom Types to determine what we get back from each field.

Let’s see how we can use Types::PaymentType in OrderType:

  • Some things to note here:
    • Since the model order has id , description and total columns, we can simply create a field for them and retrieve their data.
    • Because of our has_many-attached_to relationship, we could also do a payments field then look up all the Types::PaymentType objects belonging to each order .
  • However, order does not have a payments_count column, so we define the Payment_count () to return an integer equal to the length of the payments array.

Define fields on QueryType

We are almost ready to write the first Query first, but first we need to let the primary QueryType expect it, When GraphQL receives a Query request (as opposed to a Mutation request), it will be Go to the QueryType class, Like Types above, we will define the Query methods that are available through the fields.

Our first query will simply retrieve all Orders in the database. Inside the declaration of the QueryType class, we will add a field that returns an array of Types::OrderType :

As above, we define our all_orders () method below the field with the same name and ask it to simply return all Orders.

Everything is now set! We can open Insomnia and write our first Query to retrieve all Orders from the database.

Writing our first Query

The GraphQL Query format Here’s what our first query should look like nafy:

At the top, we define the request as query {} , inside the query, we call all_orders of QueryType through allOrders {} . Don’t forget to switch from snake-case to camel-case!

Inside allOrders {} , we select the fields from the Order model we want to return, These are the same fields as we specified in app/graphql/types/order_type.rb You can select and select the what you want to receive!

Note that: for the Payment {} , we also have to specify the fields from Types :: PaymentType that we want to receive. The available fields are the ones we specified in app / graphql / styles / Payment_type.rb.

The PaymentCount field will run the Payment_count method on Types::OrderType and return the appropriate value. and now Let’s put this Query into Insomnia and test our API!

Execute Query in Insomnia

First we need to turn on the server with the command: rails s and click on the following link: http: // localhost: 3000 / graphql .

Open Insomnia and create a POST reques. In the top left corner of the request text editor, make sure the format of the POST request is set to “GraphQL Query”. (“Query GraphQL”.)

NEXT :

We add the code from the query above. Then send it out and see what it returns:

Great! All of our data is beautiful and organized – and that’s exactly what we ask for.

ok next Let’s run a similar query, but with less fields:

Perfect! If we don’t need id or PaymentCount , then there’s absolutely no need to include them in Query!

Conclusion:

We now have a very simple API to retrieve data from database using GraphQL! However, since GraphQL Queries can only retrieve data, we cannot use our existing code to make any changes to the database. So today we have an overview of how to install and pair together, and how to use graphql after pairing, hopefully this first article will help you get it installed. graphql and beyond knows its basic usage when combined with Rails. See you in the next posts!

Source: https://dev.to/isalevine/ruby-on-rails-graphql-api-tutorial-from-rails-new-to-first-query-76h

Share the news now

Source : Viblo