Class: Hephaestus::Middleware::OpenapiValidation
- Defined in:
- lib/hephaestus/middleware/openapi_validation.rb
Constant Summary collapse
- API_PATH_PREFIX =
"/api/"
- API_SPEC_PATH =
Rails.root.join("lib/schemas/api/2023-03-06/openapi.json")
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, ignore_path: "/settings", match_path: API_PATH_PREFIX, limit_methods_to: nil, spec: API_SPEC_PATH) ⇒ OpenapiValidation
constructor
A new instance of OpenapiValidation.
Constructor Details
#initialize(app, ignore_path: "/settings", match_path: API_PATH_PREFIX, limit_methods_to: nil, spec: API_SPEC_PATH) ⇒ OpenapiValidation
Returns a new instance of OpenapiValidation.
12 13 14 15 16 17 18 |
# File 'lib/hephaestus/middleware/openapi_validation.rb', line 12 def initialize(app, ignore_path: "/settings", match_path: API_PATH_PREFIX, limit_methods_to: nil, spec: API_SPEC_PATH) @app = app @ignore_path = ignore_path @match_path = match_path @limit_methods_to = limit_methods_to @spec = OpenapiFirst.load(spec) end |
Instance Method Details
#call(env) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 |
# File 'lib/hephaestus/middleware/openapi_validation.rb', line 20 def call(env) request = Rack::Request.new(env) return @app.call(env) if request.path.include?(@ignore_path) return @app.call(env) unless request.path.starts_with?(@match_path) return @app.call(env) if @limit_methods_to.present? && @limit_methods_to.exclude?(request.request_method) begin # force content-type to JSON env["CONTENT_TYPE"] = "application/json" if env["CONTENT_TYPE"] != "application/json" validated_request = @spec.validate_request(request) return @app.call(env) if validated_request.valid? case validated_request.error when OpenapiFirst::Schema::ValidationError error_arr = format_arr(validated_request.error.errors.map(&:message)) Rails.logger.error(error_arr) if print_user_api_errors? [Hephaestus::HTTP::BAD_REQUEST_I, { "Content-Type" => "application/json" }, [error_arr]] else case validated_request.error.type when :not_found [Hephaestus::HTTP::NOT_FOUND_I, { "Content-Type" => "application/json" }, [format_str("Not Found")]] else = if validated_request.error.errors.present? format_arr(validated_request.error.errors.map(&:message)) else format_str(validated_request.error.) end Rails.logger.error() if print_user_api_errors? [Hephaestus::HTTP::BAD_REQUEST_I, { "Content-Type" => "application/json" }, []] end end rescue StandardError => e raise e unless Rails.env.production? Rails.logger.error( "openapi.request_validation.error", path: request.path, method: request.env["REQUEST_METHOD"], error_message: e., ) end end |