summaryrefslogtreecommitdiff
path: root/src/user/snapshot.rs
blob: d548e06453f8742cf5729cf959639a8644dd31d8 (plain)
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
use super::{
    Id,
    event::{Created, Event},
};
use crate::name::Name;

// This also implements FromRequestParts (see `./extract.rs`). As a result, it
// can be used as an extractor for endpoints that want to require a user, or for
// endpoints that need to behave differently depending on whether the client is
// or is not logged in.
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
pub struct User {
    pub id: Id,
    pub name: Name,
    // The omission of the hashed password is deliberate, to minimize the
    // chance that it ends up tangled up in debug output or in some other chunk
    // of logic elsewhere.
}

impl User {
    // Without this allow, clippy wants the `Option<Self>` return type to be `Self`. It's not a bad
    // suggestion, but we need `Option` here, for two reasons:
    //
    // 1. This is used to collect streams using a fold, below, which requires a type
    //    consistent with the fold, and
    // 2. It's also consistent with the other history state machine types.
    #[allow(clippy::unnecessary_wraps)]
    fn apply(state: Option<Self>, event: Event) -> Option<Self> {
        match (state, event) {
            (None, Event::Created(event)) => Some(event.into()),
            (state, event) => panic!("invalid message event {event:#?} for state {state:#?}"),
        }
    }
}

impl FromIterator<Event> for Option<User> {
    fn from_iter<I: IntoIterator<Item = Event>>(events: I) -> Self {
        events.into_iter().fold(None, User::apply)
    }
}

impl From<&Created> for User {
    fn from(event: &Created) -> Self {
        event.user.clone()
    }
}

impl From<Created> for User {
    fn from(event: Created) -> Self {
        event.user
    }
}