Sha256: 9d7c03dc5a3aa836dbb512a16b6b2218893043a54f32e17dc2893357e2bd9d40

Contents?: true

Size: 1.64 KB

Versions: 5

Compression:

Stored size: 1.64 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")

      def initialize(app)
        @app = app
        spec = OpenapiFirst.load(SPEC_PATH)
        @response_validator = OpenapiFirst::ResponseValidator.new(spec)
        @request_validator = OpenapiFirst::RequestValidation.new(->(_env) {}, spec: SPEC_PATH, 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)

            return [PlugApp::HTTP::BAD_REQUEST_I, { "Content-Type" => "application/json" }, [error_hsh]]
          rescue => 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

5 entries across 5 versions & 1 rubygems

Version Path
hephaestus-0.1.3 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.1.2 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.1.1 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.0.2 templates/app/lib/plug_app/middleware/openapi_validation.rb
hephaestus-0.0.1 templates/app/lib/plug_app/middleware/openapi_validation.rb