Module: WorkOS::Client

Extended by:
T::Sig
Includes:
Kernel
Included in:
AuditLog, SSO
Defined in:
lib/workos/client.rb

Instance Method Summary collapse

Instance Method Details

#clientObject



11
12
13
14
15
16
17
18
# File 'lib/workos/client.rb', line 11

def client
  return @client if defined?(@client)

  @client = Net::HTTP.new(WorkOS::API_HOSTNAME, 443)
  @client.use_ssl = true

  @client
end

#execute_request(request:) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/workos/client.rb', line 21

def execute_request(request:)
  response = client.request(request)

  http_status = response.code.to_i
  handle_error_response(response: response) if http_status >= 400

  response
end

#handle_error_response(response:) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/workos/client.rb', line 53

def handle_error_response(response:)
  http_status = response.code.to_i
  json = JSON.parse(response.body)

  case http_status
  when 400
    raise InvalidRequestError.new(
      message: json['message'],
      http_status: http_status,
      request_id: response['x-request-id'],
    )
  when 401
    raise AuthenticationError.new(
      message: json['message'],
      http_status: http_status,
      request_id: response['x-request-id'],
    )
  when 422
    errors = json['errors'].map do |error|
      "#{error['field']}: #{error['code']}"
    end.join('; ')

    message = "#{json['message']} (#{errors})"
    raise InvalidRequestError.new(
      message: message,
      http_status: http_status,
      request_id: response['x-request-id'],
    )
  end
end

#post_request(path:, body: nil) ⇒ Object



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

def post_request(path:, body: nil)
  request = Net::HTTP::Post.new(path, 'Content-Type' => 'application/json')
  request.body = body.to_json if body
  request['User-Agent'] = user_agent
  request
end

#user_agentObject



39
40
41
42
43
44
45
46
47
48
# File 'lib/workos/client.rb', line 39

def user_agent
  engine = defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : 'Ruby'

  [
    'WorkOS',
    "#{engine}/#{RUBY_VERSION}",
    RUBY_PLATFORM,
    "v#{WorkOS::VERSION}"
  ].join('; ')
end