Class: Pragma::Migration::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/pragma/migration/middleware.rb

Overview

Rack middleware for migrating requests and responses.

This middleware can be added to your Rack application in order to automatically migrate your users' requests up and your app's responses down.

Examples:

Configuring the middleware

use Pragma::Migration::Middleware,
  repository: API::V1::MigrationRepository,
  user_version_proc: (lambda do |request|
    # `request` here is a `Rack::Request` object.
    request.get_header 'X-Api-Version'
  end)

Constant Summary collapse

DEFAULT_VERSION_PROC =

The default for user_version_proc.

lambda do |request|
  request.get_header('X-Api-Version')
end

Instance Method Summary collapse

Constructor Details

#initialize(app, repository:, user_version_proc: DEFAULT_VERSION_PROC) ⇒ Middleware

Initializes the middleware.

Parameters:

  • app (Object)

    your app

  • repository (Repository)

    your migration repository

  • user_version_proc (Proc)

    a proc that takes a request and returns a version number


28
29
30
31
32
# File 'lib/pragma/migration/middleware.rb', line 28

def initialize(app, repository:, user_version_proc: DEFAULT_VERSION_PROC)
  @app = app
  @repository = repository
  @user_version_proc = user_version_proc
end

Instance Method Details

#call(env) ⇒ Array<Integer, Hash, Enumerable>

Executes the middleware.

This will take the provided environment, build a request with it and run the migrations upwards to make the request compatible with the latest API version.

It will then pass this request on so that it is handled by your application.

The response returned by your application will be migrated downwards so that it is compatible with the version of the API supported by the client.

Parameters:

  • env (Hash)

    the Rack env

Returns:

  • (Array<Integer, Hash, Enumerable>)

    an array with the status, headers and body of the final response for the user

See Also:


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/pragma/migration/middleware.rb', line 50

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

  runner = Runner.new(Bond.new(
    repository: @repository,
    request: original_request,
    user_version: user_version_from(original_request)
  ))

  migrated_request = runner.run_upwards

  status, headers, body = @app.call(migrated_request.env)
  original_response = Rack::Response.new(body, status, headers)
  migrated_response = runner.run_downwards(original_response)

  [migrated_response.status, migrated_response.headers, migrated_response.body]
end