cqrs_es2/queries/
i_query.rs

1use serde::{
2    de::DeserializeOwned,
3    Serialize,
4};
5use std::fmt::Debug;
6
7use crate::{
8    commands::ICommand,
9    events::{
10        IEvent,
11        IEventConsumer,
12    },
13};
14
15/// A `Query` is a read element in a CQRS system. As events are
16/// emitted multiple downstream queries are updated to reflect the
17/// current state of the system. A query may also be referred to as a
18/// 'view', the concepts are identical but 'query' is used here to
19/// conform with CQRS nomenclature.
20///
21/// Queries are generally serialized for persistence, usually in a
22/// standard database, but a query could also utilize messaging
23/// platform or other asynchronous, eventually-consistent systems.
24/// # Examples
25/// ```rust
26/// use serde::{
27///     Deserialize,
28///     Serialize,
29/// };
30/// use std::fmt::Debug;
31///
32/// use cqrs_es2::{
33///     example_impl::{
34///         Customer,
35///         CustomerEvent,CustomerCommand
36///     },
37///     EventContext,
38///     IEventConsumer,
39///     IQuery,
40/// };
41///
42/// #[derive(
43///     Debug,
44///     PartialEq,
45///     Default,
46///     Clone,
47///     Serialize,
48///     Deserialize
49/// )]
50/// pub struct CustomerContactQuery {
51///     pub name: String,
52///     pub email: String,
53///     pub latest_address: String,
54/// }
55///
56/// impl IQuery<CustomerCommand, CustomerEvent> for CustomerContactQuery {
57///     fn query_type() -> &'static str {
58///         "customer_contact_query"
59///     }
60/// }
61///
62/// impl IEventConsumer<CustomerCommand, CustomerEvent> for CustomerContactQuery {
63///     fn update(
64///         &mut self,
65///         event: &EventContext<CustomerCommand, CustomerEvent>,
66///     ) {
67///         match &event.payload {
68///             CustomerEvent::NameAdded(payload) => {
69///                 self.name = payload.changed_name.clone();
70///             },
71///             CustomerEvent::EmailUpdated(payload) => {
72///                 self.email = payload.new_email.clone();
73///             },
74///             CustomerEvent::AddressUpdated(payload) => {
75///                 self.latest_address = payload.new_address.clone();
76///             },
77///         }
78///     }
79/// }
80/// ```
81pub trait IQuery<C: ICommand, E: IEvent>:
82    Debug
83    + PartialEq
84    + Default
85    + Clone
86    + Serialize
87    + DeserializeOwned
88    + IEventConsumer<C, E>
89    + Sync
90    + Send {
91    /// query_type is a unique identifier for this query
92    fn query_type() -> &'static str;
93}