|
| 1 | +require_relative 'base_middleware' |
| 2 | + |
| 3 | +module CypressOnRails |
| 4 | + module Vcr |
| 5 | + # Middleware to handle vcr with insert/eject endpoints |
| 6 | + class InsertEjectMiddleware < BaseMiddleware |
| 7 | + def initialize(app, vcr = nil) |
| 8 | + @app = app |
| 9 | + @vcr = vcr |
| 10 | + @first_call = false |
| 11 | + end |
| 12 | + |
| 13 | + def call(env) |
| 14 | + request = Rack::Request.new(env) |
| 15 | + if request.path.start_with?('/__e2e__/vcr/insert') |
| 16 | + configuration.tagged_logged { handle_insert(request) } |
| 17 | + elsif request.path.start_with?('/__e2e__/vcr/eject') |
| 18 | + configuration.tagged_logged { handle_eject } |
| 19 | + else |
| 20 | + do_first_call unless @first_call |
| 21 | + @app.call(env) |
| 22 | + end |
| 23 | + end |
| 24 | + |
| 25 | + private |
| 26 | + |
| 27 | + def handle_insert(req) |
| 28 | + WebMock.enable! if defined?(WebMock) |
| 29 | + vcr.turn_on! |
| 30 | + logger.info "vcr insert cassette: #{body}" |
| 31 | + body = parse_request_body(req) |
| 32 | + cassette_name, options = extract_cassette_info(body) |
| 33 | + vcr.insert_cassette(cassette_name, options) |
| 34 | + [201, { 'Content-Type' => 'application/json' }, [{ 'message': 'OK' }.to_json]] |
| 35 | + rescue LoadError, ArgumentError => e |
| 36 | + [501, { 'Content-Type' => 'application/json' }, [{ 'message': e.message }.to_json]] |
| 37 | + end |
| 38 | + |
| 39 | + def parse_request_body(req) |
| 40 | + JSON.parse(req.body.read) |
| 41 | + end |
| 42 | + |
| 43 | + def extract_cassette_info(body) |
| 44 | + cassette_name = body[0] |
| 45 | + options = (body[1] || {}).symbolize_keys |
| 46 | + options[:record] = options[:record].to_sym if options[:record] |
| 47 | + options[:match_requests_on] = options[:match_requests_on].map(&:to_sym) if options[:match_requests_on] |
| 48 | + options[:serialize_with] = options[:serialize_with].to_sym if options[:serialize_with] |
| 49 | + options[:persist_with] = options[:persist_with].to_sym if options[:persist_with] |
| 50 | + [cassette_name, options] |
| 51 | + end |
| 52 | + |
| 53 | + def handle_eject |
| 54 | + logger.info 'vcr eject cassette' |
| 55 | + vcr.eject_cassette |
| 56 | + do_first_call |
| 57 | + [201, { 'Content-Type' => 'application/json' }, [{ 'message': 'OK' }.to_json]] |
| 58 | + rescue LoadError, ArgumentError => e |
| 59 | + [501, { 'Content-Type' => 'application/json' }, [{ 'message': e.message }.to_json]] |
| 60 | + end |
| 61 | + |
| 62 | + def do_first_call |
| 63 | + @first_call = true |
| 64 | + vcr.turn_off! |
| 65 | + WebMock.disable! if defined?(WebMock) |
| 66 | + rescue LoadError |
| 67 | + # nop |
| 68 | + end |
| 69 | + end |
| 70 | + end |
| 71 | +end |
0 commit comments