lib/meta/application/route.rb in meta-api-0.0.6 vs lib/meta/application/route.rb in meta-api-0.0.7

- old
+ new

@@ -8,10 +8,11 @@ class Route include PathMatchingMod.new(path_method: :path, matching_mode: :full) attr_reader :path, :method, :meta, :action + # path 是局部 path,不包含由父级定义的前缀 def initialize(path: '', method: :all, meta: {}, action: nil) @path = Utils::Path.normalize_path(path) @method = method @meta = Metadata.new(meta) @action = action @@ -23,13 +24,14 @@ execution.parse_parameters(@meta[:parameters]) if @meta[:parameters] execution.parse_request_body(@meta[:request_body]) if @meta[:request_body] action.execute(execution) if action + set_status(execution) render_entity(execution) if @meta[:responses] rescue Execution::Abort - nil + execution.response.status = 200 if execution.response.status == 0 end def match?(execution, remaining_path) request = execution.request remaining_path = '' if remaining_path == '/' @@ -40,16 +42,26 @@ return true end private + def set_status(execution) + response_definitions = @meta[:responses] + response = execution.response + if response.status == 0 + response.status = (response_definitions&.length > 0) ? response_definitions.keys[0] : 200 + end + end + def render_entity(execution) - responses = @meta[:responses] - status = execution.response.status - codes = responses.keys - return unless codes.include?(status) + response_definitions = @meta[:responses] + return if response_definitions.empty? # 未设定 status 宏时不需要执行 render_entity 方法 - entity_schema = responses[status] - execution.render_entity(entity_schema) if entity_schema + # 查找 entity schema + entity_schema = response_definitions[execution.response.status] + return if entity_schema.nil? + + # 执行面向 schema 的渲染 + execution.render_entity(entity_schema) end end end