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.
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.
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.
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