Flockingbird/roost

View on GitHub
bin/sink

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby
# frozen_string_literal: true

$LOAD_PATH << '.'

require 'bundler/setup'
require 'bcrypt'
require 'logger'
require 'securerandom'
require 'yajl'

require_relative '../config/environment'
require_relative '../config/database'

require_relative '../app/aggregates/member'
require_relative '../app/commands/application_command'
require_relative '../app/commands/application_command_handler'
require_relative '../app/commands/member/add_member'

LOG_LEVEL = ENV['LOG_LEVEL'].to_i || Logger::DEBUG

# Handles a stream of nodes in STDIN emits them as events through the
# AddMemberCommand.
class EventSink
  include BCrypt

  def initialize
    @parser = Yajl::Parser.new(symbolize_keys: true)
    @parser.on_parse_complete = method(:object_parsed)

    @logger = Logger.new(STDOUT)
    EventSourcery.logger.level = @logger.level = LOG_LEVEL
  end

  def object_parsed(obj)
    log(Logger::DEBUG, '-- parsed object')

    obj[:aggregate_id] ||= SecureRandom.uuid

    obj[:password] = Password.create(obj[:password]) if obj.key?(:password)

    command = Commands::Member::AddMember::Command.new(obj)
    Commands::Member::AddMember::CommandHandler.new(command: command).handle
  rescue BadRequest => e
    log(Logger::ERROR, e.message)
  end

  def call(io)
    @parser.parse(io)
  rescue Yajl::ParseError => e
    log(Logger::ERROR, e.message)
    close_connection
  end

  private

  def log(severity, message = nil, progname = 'sink')
    @logger.add(severity, message, progname)
  end
end

EventSink.new.call(STDIN)