Class: FaaStRuby::RPC::Function

Inherits:
Object
  • Object
show all
Defined in:
lib/faastruby-rpc/function.rb

Instance Method Summary collapse

Constructor Details

#initialize(path, raise_errors: true) ⇒ Function

Returns a new instance of Function.



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/faastruby-rpc/function.rb', line 22

def initialize(path, raise_errors: true)
  @path = path
  @methods = {
    'post' => Net::HTTP::Post,
    'get' => Net::HTTP::Get,
    'put' => Net::HTTP::Put,
    'patch' => Net::HTTP::Patch,
    'delete' => Net::HTTP::Delete
  }
  @response = Struct.new(:body, :code, :headers, :klass)
  @raise_errors = raise_errors
end

Instance Method Details

#call(body: nil, query_params: {}, headers: {}, method: 'post') ⇒ Object



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
# File 'lib/faastruby-rpc/function.rb', line 38

def call(body: nil, query_params: {}, headers: {}, method: 'post')
  url = "#{FAASTRUBY_HOST}/#{@path}#{convert_query_params(query_params)}"
  uri = URI.parse(url)
  use_ssl = uri.scheme == 'https' ? true : false
  response = FaaStRuby::RPC.stub_call?(@path) ? FaaStRuby::RPC.response(@path) : fetch(use_ssl: use_ssl, uri: uri, headers: headers, method: @methods[method], body: body)
  resp_headers = {}
  response.each{|k,v| resp_headers[k] = v}
  case resp_headers['content-type']
  when 'application/json'
    begin
      resp_body = Oj.load(response.body)
    rescue Oj::ParseError => e
      if response.body.is_a?(String)
        resp_body = response.body
      else
        raise e if @raise_errors
        resp_body = {
          'error' => e.message,
          'location' => e.backtrace&.first
        }
      end
    end
  when 'application/yaml'
    resp_body = YAML.load(response.body)
  else
    resp_body = response.body
  end
  raise FaaStRuby::RPC::ExecutionError.new("Function #{@path} returned status code #{response.code} - #{resp_body['error']} - #{resp_body['location']}") if response.code.to_i >= 400 && @raise_errors
  @response.new(resp_body, response.code.to_i, resp_headers)
end

#with(*args) ⇒ Object



34
35
36
# File 'lib/faastruby-rpc/function.rb', line 34

def with(*args)
  call(body: Oj.dump(args), headers: {'Content-Type' => 'application/json', 'Faastruby-Rpc' => 'true'})
end