Class: AuthingRuby::Common::GraphqlClient

Inherits:
Object
  • Object
show all
Defined in:
lib/authing_ruby/common/GraphqlClient.rb

Instance Method Summary collapse

Constructor Details

#initialize(endpoint, options = {}) ⇒ GraphqlClient

Returns a new instance of GraphqlClient.



12
13
14
15
# File 'lib/authing_ruby/common/GraphqlClient.rb', line 12

def initialize(endpoint, options = {})
  @endpoint = endpoint # API 端点
  @options = options
end

Instance Method Details

#request(options) ⇒ Object

发请求 成功或失败都返回 Hash



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/authing_ruby/common/GraphqlClient.rb', line 19

def request(options)
  headers = {
    'content-type': 'application/json',
    'x-authing-sdk-version': "ruby:#{AuthingRuby::VERSION}",
    'x-authing-userpool-id': @options.fetch(:userPoolId, ''),
    'x-authing-request-from': @options.fetch(:requestFrom, 'sdk'),
    'x-authing-app-id': @options.fetch(:appId, ''),
    'x-authing-lang': @options.fetch(:lang, ''),
  };
  token = options.fetch(:token, nil)
  if token
    headers['Authorization'] = "Bearer #{token}"
  end

  option_json = options.fetch(:json, nil)
  response = HTTP.headers(headers).post(@endpoint, json: option_json)

  # 如果直接拿 body,它的类型是:
  # puts response.body
  # puts response.body.class.name # HTTP::Response::Body
  
  # 如果转成 String:
  # puts response.body.to_s
  # puts response.body.to_s.class.name # String

  hash = JSON.parse(response.body.to_s)

  # 这里的错误处理代码参照的 JS SDK (src/lib/common/GraphqlClient.ts)
  if hash['errors'] == nil
    # 如果没错误
    return hash
  else
    # 如果有错误, 最后返回这3个字段就行
    code = nil
    message = nil
    data = nil

    hash['errors'].each do |e|
      if e['message']
        message = e['message'] 
        code = message['code']
        message = message['message']
        data = message['data']
      end
    end

    # 返回 Hash
    obj = { 
      code: code,
      message: message,
      data: data
    }
    return obj
  end
end