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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
/// Trait for representing a **Request**.
///
/// Requests are usually [Commands](Command) or [Queries](Query), and their sole requirement is to
/// have an associated `Response` type.
pub trait Request: Send {
/// Request response type.
type Response: Send;
}
/// Trait for a [Request] that represents a **Command**.
///
/// > Change the state of a system but do not return a value.
pub trait Command: Send {}
impl<T: Command> Request for T {
type Response = ();
}
/// Alias for a [Request] that represents a **Query**.
///
/// > Return a result and do not change the observable state of the system (are free of side
/// > effects).
pub use Request as Query;
/// Trait for representing a **Request Handler**.
///
/// See [Request] for more information about [Commands](Command) and [Queries](Query).
///
/// # Example
///
/// ```
/// use std::sync::Mutex;
///
/// use ddd_rs::application::{Command, CommandHandler, Query, QueryHandler};
///
/// // Error type for the Fibonacci service.
/// //
/// // It is required to implement the `std::error::Error` trait.
///
/// #[derive(Debug, PartialEq)]
/// struct FibonacciError(&'static str);
///
/// impl std::fmt::Display for FibonacciError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// self.0.fmt(f)
/// }
/// }
///
/// impl std::error::Error for FibonacciError {}
///
/// // Fibonacci service.
/// //
/// // For demonstration purposes, it is implemented as a stateful service.
///
/// #[derive(Default)]
/// struct FibonacciService {
/// n: Mutex<u32>,
/// }
///
/// impl FibonacciService {
/// fn set(&self, n: u32) {
/// let mut current = self.n.lock().unwrap();
///
/// *current = n;
/// }
///
/// fn get_next(&self) -> u32 {
/// let mut current = self.n.lock().unwrap();
///
/// let next = Self::fibonacci(*current);
///
/// *current = *current + 1;
///
/// next
/// }
///
/// fn fibonacci(n: u32) -> u32 {
/// match n {
/// 0 => 0,
/// 1 => 1,
/// _ => Self::fibonacci(n - 1) + Self::fibonacci(n - 2),
/// }
/// }
/// }
///
/// // Sets the current 0-based element of the Fibonacci sequence.
/// //
/// // `Command`s usually do not return a value, so their `Response` type is automatically `()`.
///
/// struct SetFibonacciCommand {
/// n: u32,
/// }
///
/// impl Command for SetFibonacciCommand {}
///
/// #[async_trait::async_trait]
/// impl CommandHandler<SetFibonacciCommand> for FibonacciService {
/// type Error = FibonacciError;
///
/// async fn handle(&self, command: SetFibonacciCommand) -> Result<(), Self::Error> {
/// self.set(command.n);
///
/// Ok(())
/// }
/// }
///
/// // Gets the next element of the Fibonacci sequence.
/// //
/// // `Query`s are issued in order to retrieve a value, but without causing any side-effects to the
/// // underlying state of the system.
/// //
/// // The more general `Request` trait can be used for actions that have side-effects but also
/// // require a value to be returned as its result.
///
/// struct GetNextFibonacciQuery;
///
/// impl Query for GetNextFibonacciQuery {
/// type Response = u32;
/// }
///
/// #[async_trait::async_trait]
/// impl QueryHandler<GetNextFibonacciQuery> for FibonacciService {
/// type Error = FibonacciError;
///
/// async fn handle(&self, _query: GetNextFibonacciQuery) -> Result<u32, Self::Error> {
/// Ok(self.get_next())
/// }
/// }
///
/// // Finally, instantiate and perform `Request`s to the `FibonacciService`.
///
/// # tokio_test::block_on(async {
/// let fibonacci = FibonacciService::default();
///
/// assert_eq!(fibonacci.handle(SetFibonacciCommand { n: 10 }).await, Ok(()));
/// assert_eq!(fibonacci.handle(GetNextFibonacciQuery).await, Ok(55));
/// assert_eq!(fibonacci.handle(GetNextFibonacciQuery).await, Ok(89));
/// assert_eq!(fibonacci.handle(GetNextFibonacciQuery).await, Ok(144));
/// # })
/// ```
#[async_trait::async_trait]
pub trait RequestHandler<T: Request>: Send + Sync {
/// Request handler error type.
type Error: std::error::Error;
/// Handles the incoming [Request], returning its [Response](Request::Response) as a [Result].
async fn handle(&self, request: T) -> Result<<T as Request>::Response, Self::Error>;
}
/// Alias for a [RequestHandler] specific to [Commands](Command).
pub use RequestHandler as CommandHandler;
/// Alias for a [RequestHandler] specific to [Queries](Query).
pub use RequestHandler as QueryHandler;