Module: WorkOS::Client

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

Overview

A Net::HTTP based API client for interacting with the WorkOS API

Instance Method Summary collapse

Instance Method Details

#clientObject



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

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



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

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



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
83
# File 'lib/workos/client.rb', line 54

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



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

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



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

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

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