Sha256: 3663961aff31e2fff176a9c46349006a4175e52fa9e10752728ffd9e7be65299

Contents?: true

Size: 1.72 KB

Versions: 8

Compression:

Stored size: 1.72 KB

Contents

# typed: false
# frozen_string_literal: true

require "openapi_first"

module PlugApp
  module Middleware
    class OpenapiValidation
      API_PATH_PREFIX = "/api/"
      SPEC_PATH = Rails.root.join("lib/plug_app/schemas/api/2023-03-06/openapi.json")
      SPEC = OpenapiFirst.load(SPEC_PATH)

      def initialize(app)
        @app = app
        @response_validator = OpenapiFirst::ResponseValidator.new(SPEC)
        @request_validator = OpenapiFirst::RequestValidation.new(->(_env) {}, spec: SPEC, raise_error: true)
      end

      def call(env)
        request = Rack::Request.new(env)

        if request.path.starts_with?(API_PATH_PREFIX)
          # force content-type to JSON
          if env["CONTENT_TYPE"] == "application/x-www-form-urlencoded"
            env["CONTENT_TYPE"] = "application/json"
          end

          begin
            @request_validator.call(env)
            # response = @app.call(env)
            # @response_validator.validate(request, response)
          rescue OpenapiFirst::NotFoundError
            PlugApp::Middleware::NotFound.new.call(env)
          rescue OpenapiFirst::RequestInvalidError => e
            error_hsh = ::ErrorSerializer.format(e.message)
            Rails.logger.error(error_hsh) if print_user_api_errors?
            return [PlugApp::HTTP::BAD_REQUEST_I, { "Content-Type" => "application/json" }, [error_hsh]]
          rescue StandardError => e
            raise e unless Rails.env.production?

            logger.error(
              "openapi.request_validation.error",
              path: request.path,
              method: request.env["REQUEST_METHOD"],
              error_message: e.message,
            )
          end
        end

        @app.call(env)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
hephaestus-0.6.0 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.5.2 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.5.1 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.5.0 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.4.0 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.3.1 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.2.3 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.2.2 templates/app/lib/plug_app/middleware/openapi_validation.rb