Class: Aliyun::Opensearch::Client

Inherits:
Object
  • Object
show all
Includes:
Aliyun::Opensearch::ClientExt::Traffic::Behavior
Defined in:
lib/aliyun/opensearch/client.rb

Overview

Opensearch客户端

Author:

Constant Summary collapse

REQUEST_METHODS =

允许请求的action

[:get, :post].freeze

Constants included from Aliyun::Opensearch::ClientExt::Traffic::Behavior

Aliyun::Opensearch::ClientExt::Traffic::Behavior::ACTION_CMD_DELETE, Aliyun::Opensearch::ClientExt::Traffic::Behavior::ACTION_CMD_INSERT, Aliyun::Opensearch::ClientExt::Traffic::Behavior::ACTION_CMD_KEY, Aliyun::Opensearch::ClientExt::Traffic::Behavior::ACTION_CMD_UPDATE, Aliyun::Opensearch::ClientExt::Traffic::Behavior::API_ACTION, Aliyun::Opensearch::ClientExt::Traffic::Behavior::API_SEARCH

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Aliyun::Opensearch::ClientExt::Traffic::Behavior

#action, #delete, #insert, #search, #update

Constructor Details

#initialize(app) ⇒ Client

客户端初始化

Parameters:

  • app (String)

    应用名称, 即要访问的Opensearch应用的名称, 在实例管理里可以看到

Author:



31
32
33
34
35
36
# File 'lib/aliyun/opensearch/client.rb', line 31

def initialize(app)
  @app = app
  @connection = Faraday.new(url: Configuration.opensearch_url) do |faraday|
    faraday.response :raise_error
  end
end

Instance Attribute Details

#appObject (readonly)

应用名称



22
23
24
# File 'lib/aliyun/opensearch/client.rb', line 22

def app
  @app
end

Instance Method Details

#call(method, path, params) ⇒ Hash

发送请求

Parameters:

  • method (String|Symbol)

    接口请求方法

  • path (String)

    接口地址

  • params (Hash)

    接口参数

Returns:

  • (Hash)

    请求结果

Author:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/aliyun/opensearch/client.rb', line 49

def call(method, path, params)
  raise ArgumentError, "Not Allow Request Method #{method}; Only Allowed #{REQUEST_METHODS}" unless REQUEST_METHODS.map { |e| [e, e.to_s, e.to_s.upcase] }.flatten.include?(method)

  response = @connection.send(method.downcase, path, params) do |request|
    api_params = (request.http_method == :get ? request.params : request.body)
    request.headers = ClientExt::Traffic::Header.new(request.http_method, request.path, api_params: api_params).generate
  end
  body = response.body.empty? ? {} : JSON.parse(response.body)

  valid_response(response, body)
  body
rescue Error::AliyunService, Error::InvalidResponseBody => e
  raise e
rescue Faraday::Error => e
  raise Error::HttpBase, e
end

#valid_response(response, body) ⇒ Object

返回结果校验

Raises:

Author:



71
72
73
74
# File 'lib/aliyun/opensearch/client.rb', line 71

def valid_response(response, body)
  raise Error::InvalidResponseBody, response if body.empty? || !body.keys.include?('status')
  raise Error::AliyunService, response if body['status'] != 'OK'
end