1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use crate::{
    errors::Error,
    events::IEvent,
};

use super::i_command::ICommand;

/// Command handlers are usually the aggregates. It consumes the
/// command and emit all events resulting from this command.
///
/// # Example
///
/// For illustration only:
///
/// ```rust
/// use cqrs_es2::{
///     example_impl::{
///         AddressUpdated,
///         CustomerCommand,
///         CustomerEvent,
///         EmailUpdated,
///         NameAdded,
///     },
///     Error,
///     ICommandHandler,
/// };
///
/// pub struct CustomerCommandHandler {};
///
/// impl ICommandHandler<CustomerCommand, CustomerEvent>
///     for CustomerCommandHandler
/// {
///     fn handle(
///         &self,
///         command: CustomerCommand,
///     ) -> Result<Vec<CustomerEvent>, Error> {
///         match command {
///             CustomerCommand::AddCustomerName(payload) => {
///                 let payload = NameAdded {
///                     changed_name: payload.changed_name,
///                 };
///
///                 Ok(vec![CustomerEvent::NameAdded(payload)])
///             },
///             CustomerCommand::UpdateEmail(payload) => {
///                 let payload = EmailUpdated {
///                     new_email: payload.new_email,
///                 };
///
///                 Ok(vec![CustomerEvent::EmailUpdated(
///                     payload,
///                 )])
///             },
///             CustomerCommand::AddAddress(payload) => {
///                 let payload = AddressUpdated {
///                     new_address: payload.new_address,
///                 };
///
///                 Ok(vec![CustomerEvent::AddressUpdated(
///                     payload,
///                 )])
///             },
///         }
///     }
/// }
/// ```
pub trait ICommandHandler<C: ICommand, E: IEvent> {
    /// handle inbound command and return a vector of events or an
    /// error
    fn handle(
        &self,
        command: C,
    ) -> Result<Vec<E>, Error>;
}