How to create a query using variables in GraphQL [Using Ruby on Rails]

Introduction

In the GraphQL query writing method introduced in the previous article You may be wondering, "How can I use a variable in a query?"

In the case of I I wanted to pass the data obtained by REST API to GraphQL API How can I embed a variable in a query? I had a question.

So, when you google "pass variables to GraphQL query" __ After all, easy-to-understand articles do not hit! __

So this time too, it's easy to understand for beginners (although I'm also a beginner ... I will explain how to use variables in GraphQL queries.

Static query

This time, I will explain using the following query as an example.

query {
    repositoryOwner(login:"github username") {
        repositories(last:5){
            nodes {
                name
            }
        }
    }
}

If you specify a github user name, It is a query to get 5 new ones from the specified user's repository.

However, in this state, it is not a dynamic query. If you write the user name directly in the query, you can only get the repository for that user.

For example, if you enter your github username, When creating an app that displays the latest 5 of the user's repositories This query cannot be used. How can I make this query a dynamic query?

To make this query a dynamic query You need to understand how to write the query variables.

What are variables

Variables are variables when translated into Japanese. ~~ (I can't say that I noticed it when I searched to write this article

Here, I will explain the "writing method" of these variables. If you add variables to the previous query and rewrite it, it will be as follows.

query ($user: String!) {
    repositoryOwner(login:$user) {
        repositories(last:5){
            nodes {
                name
            }
        }
    }
}

--variables--
{
  "user": "username"
}

If you compare before and after rewriting, the first and second lines and the three places below variables are different.

First, let ’s start with the first line.

query ($user: String!) {

The description $ user: String! Is added after the query. It writes Arguments, GraphQL arguments and argument types. Also, by writing "$" before the argument user, Variables written outside the query can be used inside the query as arguments.

Then the second line

repositoryOwner(login:$user) {

Before rewriting, I used to write the github user name directly in the login value. I think it has changed to $ user. This will take the data passed as an argument It is a dynamic query by giving it as the login value.

Finally, the description below variables

{
  "user": "username"
}

With GraphiQL, there is a space to write Variables under the query editor, so If you write it there, it will be combined with the description on the first and second lines that I explained earlier. It will be available in the query as the variable user.

… This is fine for how to use it in GraphiQL, It's a little different when used in Rails apps.

How to write Variables in Rails

That's why it's written in Rails.

This time, I will explain by adding to the newly created application with scaffold. The completed form is "Enter the name of a github user and it will display the 5 latest repositories for that user." Create something like that.

After installation, add the following to the controller.

controllers/users_controller.rb


class UsersController < ApplicationController
...abridgement...
  Query = GqlTest(Your own app name)::Client.parse <<-GRAPHQL
  query ($user: String!) {
    repositoryOwner(login: $user) {
        repositories(last:5){
            nodes {
                name
            }
        }
    }
}
    GRAPHQL

  def show
    username = @user.name
    @works = result(user: username).data.repository_owner.repositories.nodes
  end

···abridgement···
  private
  def result(variables = {})
    response = GqlTest(* Your own app name)::Client.query(Query, variables: variables)
  end
end

If you explain the added code The query is Query = GqlTest (your app name) :: Client.parse <<-GRAPHQL It's OK if you write the query you created earlier after the code in.

controllers/users_controller.rb


Query = GqlTest(Your own app name)::Client.parse <<-GRAPHQL
  query ($user: String!) {
    repositoryOwner(login: $user) {
        repositories(last:5){
            nodes {
                name
            }
        }
    }
}

What I added in the show action With the code that brings the user name registered in the new action as @ user.name and stores it in username This is the code that retrieves the result data with that username as an argument. user: username is It is described in the Variables space under the query editor of GraphiQL.

controllers/users_controller.rb


def show
    username = @user.name
    @works = result(user: username).data.repository_owner.repositories.nodes
end

In the result method under private, I added as follows. The difference from the previous article is after the query variables: variables Variables can be used by describing. A detailed explanation of this part can be found in the official reference of graphql-client. please confirm. (Official reference: https://github.com/github/graphql-client)

controllers/users_controller.rb


private
  def result(variables = {})
    response = GqlTest(* Your own app name)::Client.query(Query, variables: variables)
  end
end

And finally, it is completed by changing show.html.erb of view.

Ruby:views/show.html.erb


<% @works.each do |work|%>
   <p><%= work.name %></p>
<% end %>

Please add the above code to any place you like in show.html.erb created by scaffold. I think it will be displayed.

スクリーンショット 2020-08-28 23.24.05.png

If it can be displayed as above, it is complete!

That's all, thank you for your hard work!

(Since I scribbled it in the middle of the night, there may be various typographical errors ...)

Recommended Posts

How to create a query using variables in GraphQL [Using Ruby on Rails]
How to display a graph in Ruby on Rails (LazyHighChart)
[Rails] How to create a graph using lazy_high_charts
How to easily create a pull-down in Rails
[Ruby on Rails] How to install Bootstrap in Rails
How to build a Ruby on Rails environment using Docker (for Docker beginners)
[Ruby on Rails] How to write enum in Japanese
[Ruby On Rails] How to reset DB in Heroku
(Ruby on Rails6) How to create models and tables
How to implement image posting function using Active Storage in Ruby on Rails
How to use Ruby on Rails
[Ruby] How to split each GraphQL query into a file
Apply CSS to a specific View in Ruby on Rails
[Ruby on Rails] How to use CarrierWave
How to insert a video in Rails
[Ruby on Rails] How to use redirect_to
[rails] How to create a partial template
[Ruby on Rails] How to use kaminari
Beginners create portfolio in Ruby on Rails
[Rails 6] How to create a dynamic form input screen using cocoon
(Ruby on Rails6) Create a function to edit the posted content
Change from SQLite3 to PostgreSQL in a new Ruby on Rails project
[Ruby on Rails] How to display error messages
How to implement a slideshow using slick in Rails (one by one & multiple by one)
How to add / remove Ruby on Rails columns
How to create a theme in Liferay 7 / DXP
How to implement gem "summer note" in wysiwyg editor in Ruby on Rails
How to build a Ruby on Rails development environment with Docker (Rails 6.x)
How to implement a like feature in Rails
[Rails] How to create a Twitter share button
(Ruby on Rails6) Creating data in a table
How to debug the processing in the Ruby on Rails model only on the console
How to build a Ruby on Rails development environment with Docker (Rails 5.x)
How to make a follow function in Rails
[Ruby on Rails] How to use session method
[Ruby On Rails] How to search the contents of params using include?
How to implement Pagination in GraphQL (for ruby)
[Ruby on Rails] How to log in with only your name and password using the gem devise
[Ruby on Rails] When logging in for the first time ・ How to split the screen in half using jQuery
How to resolve errors that occur in the "Ruby on Rails" integration test
A memo to simply create a form using only HTML and CSS in Rails 6
[Ruby on Rails] Try to create a service that makes local cats happy
[Rails] How to create a signed URL for CloudFront
How to implement a like feature in Ajax in Rails
[Ruby on Rails] How to change the column name
How to create a Spring Boot project in IntelliJ
How to create a data URI (base64) in Java
How to launch another command in a Ruby program
[How to insert a video in haml with Rails]
How to write a date comparison search in Rails
How to convert A to a and a to A using AND and OR in Java
How to query Array in jsonb with Rails + postgres
[Rails 6] How to set a background image in Rails [CSS]
[Rails] How to load JavaScript in a specific view
[Rails] How to install a decorator using gem draper
Try using the query attribute of Ruby on Rails
Create a fortune using Ruby
How to create a method
Docker command to create Rails project with a single blow in environment without Ruby
How to implement a circular profile image in Rails using CarrierWave and R Magick
How to set environment variables when using Payjp with Rails