rs_mongo_stream/
event.rs

1//! Event types for MongoDB change stream operations.
2//!
3//! This module defines the various event types that can be subscribed to
4//! from MongoDB change streams.
5
6use mongodb::change_stream::event::OperationType;
7
8/// Represents the types of events that can occur in a MongoDB collection.
9///
10/// These event types correspond to the MongoDB change stream operation types
11/// but are simplified to include only the most common operations.
12#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
13pub enum Event {
14    /// Document insertion event
15    Insert,
16    /// Document update event
17    Update,
18    /// Document deletion event
19    Delete,
20}
21
22impl Event {
23    /// Returns a string representation of the event type.
24    ///
25    /// This is useful for logging and debugging purposes.
26    ///
27    /// # Returns
28    ///
29    /// A static string representation of the event.
30    pub fn event_type_str(&self) -> &'static str {
31        match self {
32            Self::Insert => "insert",
33            Self::Update => "update",
34            Self::Delete => "delete",
35        }
36    }
37}
38
39// Conversion from MongoDB's OperationType
40impl From<OperationType> for Event {
41    fn from(op_type: OperationType) -> Self {
42        match op_type {
43            OperationType::Insert => Event::Insert,
44            OperationType::Update => Event::Update,
45            OperationType::Delete => Event::Delete,
46            // Default to Insert for unsupported types
47            // A more robust implementation could return Result<Event, Error>
48            _ => Event::Insert,
49        }
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use mongodb::change_stream::event::OperationType;
57
58    #[test]
59    fn test_event_type_str() {
60        assert_eq!(Event::Insert.event_type_str(), "insert");
61        assert_eq!(Event::Update.event_type_str(), "update");
62        assert_eq!(Event::Delete.event_type_str(), "delete");
63    }
64
65    #[test]
66    fn test_from_operation_type() {
67        assert_eq!(Event::from(OperationType::Insert), Event::Insert);
68        assert_eq!(Event::from(OperationType::Update), Event::Update);
69        assert_eq!(Event::from(OperationType::Delete), Event::Delete);
70    }
71
72    #[test]
73    fn test_unsupported_operation_type() {
74        // Test that unsupported operation types default to Insert
75        assert_eq!(Event::from(OperationType::Replace), Event::Insert);
76        assert_eq!(Event::from(OperationType::Invalidate), Event::Insert);
77    }
78}