Class: Rack::PactBroker::DatabaseTransaction

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/pact_broker/database_transaction.rb

Constant Summary collapse

REQUEST_METHOD =
"REQUEST_METHOD".freeze
TRANS_METHODS =
%w{POST PUT PATCH DELETE}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, database_connection) ⇒ DatabaseTransaction

Returns a new instance of DatabaseTransaction.



12
13
14
15
16
17
18
19
20
# File 'lib/rack/pact_broker/database_transaction.rb', line 12

def initialize app, database_connection
  @app = app
  @database_connection = database_connection
  @default_database_connector = ->(&block) {
    database_connection.synchronize do
      block.call
    end
  }
end

Instance Method Details

#add_database_connector(env) ⇒ Object



30
31
32
33
# File 'lib/rack/pact_broker/database_transaction.rb', line 30

def add_database_connector(env)
  # maintain any existing one set by previous middleware
  { "pactbroker.database_connector" => @default_database_connector }.merge(env)
end

#call(env) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/rack/pact_broker/database_transaction.rb', line 22

def call env
  if use_transaction? env
    call_with_transaction(add_database_connector(env))
  else
    call_without_transaction(add_database_connector(env))
  end
end

#call_with_transaction(env) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/rack/pact_broker/database_transaction.rb', line 43

def call_with_transaction env
  response = nil
  @database_connection.transaction do
    response = @app.call(env)
    if response.first == 500
      raise Sequel::Rollback unless do_not_rollback?(response)
    end
  end
  response
end

#call_without_transaction(env) ⇒ Object



39
40
41
# File 'lib/rack/pact_broker/database_transaction.rb', line 39

def call_without_transaction env
  @app.call(env)
end

#do_not_rollback?(response) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/rack/pact_broker/database_transaction.rb', line 54

def do_not_rollback? response
  response[1].delete(::PactBroker::DO_NOT_ROLLBACK)
end

#use_transaction?(env) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/rack/pact_broker/database_transaction.rb', line 35

def use_transaction? env
  TRANS_METHODS.include? env[REQUEST_METHOD]
end