lib/faastruby-rpc/function.rb in faastruby-rpc-0.2.1 vs lib/faastruby-rpc/function.rb in faastruby-rpc-0.2.2
- old
+ new
@@ -1,7 +1,7 @@
module FaaStRuby
- FAASTRUBY_HOST = ENV['FAASTRUBY_HOST'] || "http://localhost:3000"
+ FAASTRUBY_WORKSPACE_BASE_HOST = ENV['FAASTRUBY_WORKSPACE_BASE_HOST']
module RPC
class ExecutionError < StandardError
end
class Response
attr_reader :body, :code, :headers, :klass
@@ -35,53 +35,69 @@
@response.body = yield(output) if block_given?
end
self
end
+ def get_endpoint(query_params)
+ return "https://#{FAASTRUBY_WORKSPACE_BASE_HOST}/#{@path}#{query_params}" if FAASTRUBY_WORKSPACE_BASE_HOST
+ return "http://localhost:3000/#{@path}#{query_params}"
+ end
+
def execute(req_body: nil, query_params: {}, headers: {}, method: 'post')
- url = "#{FAASTRUBY_HOST}/#{@path}#{convert_query_params(query_params)}"
+ url = get_endpoint(convert_query_params(query_params))
uri = URI.parse(url)
use_ssl = uri.scheme == 'https' ? true : false
- response = fetch(use_ssl: use_ssl, uri: uri, headers: headers, method: @methods[method], req_body: req_body)
+ function_response = fetch(use_ssl: use_ssl, uri: uri, headers: headers, method: @methods[method], req_body: req_body)
resp_headers = {}
- response.each{|k,v| resp_headers[k] = v}
+ function_response.each{|k,v| resp_headers[k] = v}
case resp_headers['content-type']
when 'application/json'
begin
- resp_body = Oj.load(response.body)
+ resp_body = Oj.load(function_response.body)
rescue Oj::ParseError => e
- if response.body.is_a?(String)
- resp_body = response.body
+ if function_response.body.is_a?(String)
+ resp_body = function_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)
+ resp_body = YAML.load(function_response.body)
else
- resp_body = response.body
+ resp_body = function_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 = FaaStRuby::RPC::Response.new(resp_body, response.code.to_i, resp_headers)
+ if function_response.code.to_i >= 400 && @raise_errors
+ location = resp_body['location'] ? " @ #{resp_body['location']}" : nil
+ error_msg = "#{resp_body['error']}#{location}"
+ raise FaaStRuby::RPC::ExecutionError.new("Function '#{@path}' returned status code #{function_response.code}: #{error_msg}")
+ end
+ @response = FaaStRuby::RPC::Response.new(resp_body, function_response.code.to_i, resp_headers)
self
end
def returned?
!@response.nil?
end
+ def method_missing(m, *args, &block)
+ rsp = response.body
+ rsp.send(m.to_sym, *args, &block)
+ end
+
def response
wait unless returned?
@response
end
def to_s
body.to_s || ""
end
+
+ # alias_method :read, :to_s
def body
# wait unless returned?
response.body
end