class EventStoreClient::HTTP::Commands::Streams::Append

Public Instance Methods

call(stream_name, events, options: {}) click to toggle source
# File lib/event_store_client/adapters/http/commands/streams/append.rb, line 10
def call(stream_name, events, options: {})
  expected_version = options[:expected_version]
  serialized_events = events.map { |event| config.mapper.serialize(event) }
  headers = {
    'ES-ExpectedVersion' => expected_version&.to_s
  }.reject { |_key, val| val.nil? || val.empty? }

  data = build_events_data(serialized_events)
  response =
    connection.call(:post, "/streams/#{stream_name}", body: data, headers: headers)
  validate_response(response, expected_version)
end

Private Instance Methods

build_events_data(events) click to toggle source
# File lib/event_store_client/adapters/http/commands/streams/append.rb, line 25
def build_events_data(events)
  [events].flatten.map do |event|
    {
      eventId: event.id,
      eventType: event.type,
      data: event.data,
      metadata: event.metadata
    }
  end
end
validate_response(resp, expected_version) click to toggle source
# File lib/event_store_client/adapters/http/commands/streams/append.rb, line 36
def validate_response(resp, expected_version)
  wrong_version = resp.status == 400 && resp.reason_phrase == 'Wrong expected EventNumber'
  return Success() unless wrong_version

  Failure(
    "current version: #{resp.headers.fetch('es-currentversion')} | "\
    "expected: #{expected_version}"
  )
end