class Netfira::WebConnect::RackApp
Public Instance Methods
call(env)
click to toggle source
# File lib/netfira/web_connect/rack_app.rb, line 7 def call(env) begin body, headers = handle_request(env) if headers['Content-Type'] [200, headers, [body]] else make_response 200, body, headers end rescue Exceptions::SendFile => e [ 200, { 'Content-Type' => MIME::Types.type_for(e.path.to_s.sub(/\.erb$/, '')).first.content_type, 'Content-Length' => e.content.length.to_s }, [e.content] ] rescue Exceptions::HttpException => e make_response e.code, e.body, e.headers, e.code rescue => e # TODO: provide a way to silence these (i.e. for prod environments) # TODO: log errors if Exceptions::UserException === e e = e.original_exception else raise e if defined? DONT_CATCH_ALL_EXCEPTIONS end body = { errorCode: 1, errorMessage: 'Uncaught Exception', exception: { class: e.class.name, message: e.message, backtrace: e.backtrace } } make_response 500, body end end
latest_api_version()
click to toggle source
# File lib/netfira/web_connect/rack_app.rb, line 47 def latest_api_version Action.latest_version end
Private Instance Methods
handle_request(env)
click to toggle source
# File lib/netfira/web_connect/rack_app.rb, line 53 def handle_request(env) # Match [/]<api-version-number>/<anything other than a forward slash> raise NotFound unless env['PATH_INFO'] =~ /\A\/?(\d+)\/([^\/]+)/ version = $1.to_i action_name = $2.underscore.to_sym action = Action.create(action_name, version) raise NotFound unless action action.import_env env body = action.call [body, action.headers] end
make_response(status, body = {}, headers = {}, error_code = 0)
click to toggle source
# File lib/netfira/web_connect/rack_app.rb, line 65 def make_response(status, body = {}, headers = {}, error_code = 0) begin body_string = {errorCode: error_code}.merge(body).to_json rescue Encoding::UndefinedConversionError body_string = {errorCode: error_code}.merge(sanitize_for_json body).to_json end [ status, { 'X-Netfira-Version' => PLATFORM_AND_VERSION, 'Content-Type' => 'application/json', 'Content-Length' => body_string.length.to_s }.merge(headers), [body_string] ] end
sanitize_for_json(data)
click to toggle source
# File lib/netfira/web_connect/rack_app.rb, line 82 def sanitize_for_json(data) case data when String then data.encode Encoding::UTF_8 rescue '<Invalid UTF-8>' when Hash then data.map { |k, v| [k, sanitize_for_json(v)] }.to_h when Array then data.map { |v| sanitize_for_json v } else data end end