Skip to content

Middleware

Matt Muller edited this page Apr 10, 2024 · 1 revision

Middleware is used to handle the request from start to finish. Each middleware is responsible for performing some action (build, parse, validate, retry, etc) and then hand the request off to the next middleware. Middleware classes have a 1:1 mapping with Smithy operation shapes.

Middleware uses a MiddlewareStack for each operation. Middleware is added to the stack in a precise order. Each middleware may have arguments that come from Config or code generated class constants.

module HighScoreService
  # @api private
  module Middleware

    class CreateHighScore
      def self.build(config, stubs)
        stack = Hearth::MiddlewareStack.new
        stack.use(Hearth::Middleware::Initialize)
        stack.use(Hearth::Middleware::Validate,
          validator: Validators::CreateHighScoreInput,
          validate_input: config.validate_input
        )
        stack.use(Hearth::Middleware::Build,
          builder: Builders::CreateHighScore
        )
        stack.use(Hearth::Middleware::Auth,
          auth_params: Auth::Params.new(operation_name: :create_high_score),
          auth_resolver: config.auth_resolver,
          auth_schemes: config.auth_schemes
        )
        stack.use(Hearth::HTTP::Middleware::ContentLength)
        stack.use(Hearth::Middleware::Endpoint,
          param_builder: Endpoint::Parameters::CreateHighScore,
          endpoint: config.endpoint,
          endpoint_provider: config.endpoint_provider
        )
        stack.use(Hearth::Middleware::Retry,
          retry_strategy: config.retry_strategy,
          error_inspector_class: Hearth::HTTP::ErrorInspector
        )
        stack.use(Hearth::Middleware::Sign)
        stack.use(Hearth::Middleware::Parse,
          error_parser: Hearth::HTTP::ErrorParser.new(
            error_module: Errors,
            success_status: 201,
            errors: [Errors::UnprocessableEntityError]
          ),
          data_parser: Parsers::CreateHighScore
        )
        stack.use(Middleware::RequestId)
        stack.use(Hearth::Middleware::Send,
          stub_responses: config.stub_responses,
          client: config.http_client,
          stub_error_classes: [Stubs::UnprocessableEntityError],
          stub_data_class: Stubs::CreateHighScore,
          stubs: stubs
        )
        stack
      end
    end

  end
end