Confirmation and refactoring of the flow from request to controller in [httpclient]

Introduction

Previously, I implemented autocomplete using JQuery's autocomplete, ajax, and httpclient, but I was only vaguely aware of the content. Check the contents while refactoring.

First, cut out the part accessing the external API into a class and put it in the lib directory. lib/api_suggest.rb

require 'httpclient'
require 'json'

class ApiSuggest
  API_KEY = Rails.application.credentials.api[:API_KEY]
  API_URI = Rails.application.credentials.api[:API_URI]

  def self.suggest(keyword, max_num)
    uri = API_URI
    headers = {
      Authorization: "Bearer #{API_KEY}",
    }
    params = {
      keyword: keyword,
      max_num: max_num,
    }

    client = HTTPClient.new
    req = client.get(uri, body: params, header: headers)
    req
  end
end

Before refactoring

    client = HTTPClient.new
    req = client.get(uri, body: params, header: headers)
    res = JSON.parse(req.body)
    res

And I was doing JSON.parse (req.body), After refactoring

req = client.get(uri, body: params, header: headers)

Return the req part that is the result of client.get to the controller as it is,

On the controller side app/controllers/suggests_controller.rb

require 'api_suggest'
class SuggestsController < ApplicationController
  SUGGEST_MAX_COUNT = 5
  def search
    @suggests = ApiSuggest.suggest(params[:keyword], SUGGEST_MAX_COUNT)

    render body: @suggests.body, status: @suggests.code
  end
end

On line 7, render,

render body: @suggests.body, status: @suggests.code

By putting it in each parameter, it is no longer necessary to JSON.parse.

And that parameter is app/assets/javascripts/suggest.js

$("#form").autocomplete ({
  source: function (req, res) {
    $.ajax({
      url: '/suggest',
      type: 'GET',
      cache: false,
      dataType: "json",
      data: { keyword: req.term },
  n    success: function (data) {
        res(data);
      },
      error: function (xhr, ts, err) {
 n       res(xhr, ts, err);
      }
    });
  }
});

It is a flow that is returned under success of ajax.

Check the overall flow

Specified by ajax option ʻUrl: A request was sent to'/ suggest'`, By routing

get 'suggest',    to: 'suggests#search'

ʻThe search method of app / controllers / suggestionss_controller.rb` is called and

  def search
    @suggests = ApiSuggest.suggest(params[:keyword], SUGGEST_MAX_NUM)
    render body: @suggests.body, status: @suggests.code
  end

As a result of ʻApiSuggest.suggest` via an external API request on httpclient,

render body: @suggests.body, status: @suggests.code Is returned,

ʻAjax in app / assets / javascripts / suggestions.js`

success: function (res) {
  resp(res);
},
error: function (xhr, ts, err) {
  resp(xhr, ts, err);
}

It is returned in each case of success and failure. The flow.

Learn more about the ajax part

The render body option is returning the body of the return value, Returns the result of an external API whose status is a status code (200, 404, 500, etc.).

When you receive it on the ajax side, In ajax, refer to the status code, judge 200 series and 300 series as normal, and execute the success side.

If any other status code is received, execute the error side, Is being processed.

that's all.

At the end.

Thank you for reading to the end: bow_tone1: I am learning Rails from an inexperienced state because I am changing jobs. I want to steadily acquire the correct knowledge and become a competent engineer. As I continue to post, I think that the input for that will inevitably increase, leading to growth. Right now, I can't make excuses just because I'm a beginner, but I think there are many things that are wrong with the content of the post and that I should add, so I would appreciate it if you could point out. Thank you for reading this article.

Recommended Posts

Confirmation and refactoring of the flow from request to controller in [httpclient]
Understand the rough flow from request to response in SpringWebMVC
I want to understand the flow of Spring processing request parameters
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
[Java] Flow from introduction of STS to confirmation of dynamic page on localhost (2/3)
The story of forgetting to close a file in Java and failing
[Java] Flow from introduction of STS to confirmation of dynamic page on localhost (1/3)
How to change the maximum and maximum number of POST data in Spark
I translated the grammar of R and Java [Updated from time to time]
[Rails] Articles for beginners to organize and understand the flow of form_with
[Swift] How to change the order of Bar Items in Tab Bar Controller [Beginner]
The road from Git clone to building the environment and participating in the project (all in full)
ArrayList and the role of the interface seen from List
Json Request in Unit Test of Controller using MockMvc
From the introduction of devise to the creation of the users table
How to write Scala from the perspective of Java
[For beginners] DI ~ The basics of DI and DI in Spring ~
Convert the array of errors.full_messages to characters and output
Understand the characteristics of Scala in 5 minutes (Introduction to Scala)
Java language from the perspective of Kotlin and C #
Bind the request to any class and receive it
The objects in the List were references, right? Confirmation of
Java classes and instances to understand in the figure
How to determine the look-ahead request (Prefetch) from the browser
[Ruby On Rails] How to search and save the data of the parent table from the child table
In Java, I want to trim multiple specified characters from only the beginning and end.
I want to recreate the contents of assets from scratch in the environment built with capistrano
The story of raising Spring Boot from 1.5 series to 2.1 series part2
[Rails] How to temporarily save the request URL of a user who is not logged in and return to that URL after logging in
I tried to summarize the basics of kotlin and java
Get to the abbreviations from 5 examples of iterating Java lists
Command to check the number and status of Java threads
The story of throwing BLOB data from EXCEL in DBUnit
How to get the longest information from Twitter as of 12/12/2016
What I did in the version upgrade from Ruby 2.5.2 to 2.7.1
Correct the character code in Java and read from the URL
Contributed to Gradle and was named in the release notes
How to derive the last day of the month in Java
[Rails] Where to be careful in the description of validation
How to check the extension and size of uploaded files
Create more Tabs and Fragments in the Fragment of BottomNavigationView
Introduction purpose of ActiveHash and simple flow to application implementation
802.1X authentication to the network of Bonding setting in CentOS7
In order not to confuse the understanding of getters and setters, [Do not use accessors for anything! ]
I want to know the Method of the Controller where the Exception was thrown in the ExceptionHandler of Spring Boot
Method definition location Summary of how to check When defined in the project and Rails / Gem
[Java] Various summaries attached to the heads of classes and members
End of Docker and Kubernetes: Grace period from SIGTERM to SIGKILL
[Rails / Routing] How to refer to the controller in the directory you created
[Rails] How to get the URL of the transition source and redirect
It doesn't respond to the description in .js of the packs file
[Java] Get the dates of the past Monday and Sunday in order
[Swift5] How to get an array and the complement of arrays
How to set the IP address and host name of CentOS8
[Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0
Let's consider the meaning of "stream" and "collect" in Java's Stream API.
Fix the file name of war to the one set in Maven
What I did in the migration from Spring Boot 1.4 series to 2.0 series
[jOOQ] How to CASE WHEN in the WHERE / AND / OR clause
How to delete large amounts of data in Rails and concerns
Method to add the number of years and get the end of the month