Skip to main content

surrealdb_types/
notification.rs

1use std::fmt::{self, Debug, Display};
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5
6#[allow(unused_imports)]
7use crate as surrealdb_types;
8use crate::{SurrealValue, Uuid, Value};
9
10/// The action that caused the notification
11
12#[derive(
13	Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, SurrealValue,
14)]
15#[surreal(crate = "crate")]
16#[surreal(untagged, uppercase)]
17#[serde(rename_all = "UPPERCASE")]
18pub enum Action {
19	/// Record was created.
20	Create,
21	/// Record was updated.
22	Update,
23	/// Record was deleted.
24	Delete,
25	/// The live query was killed.
26	Killed,
27}
28
29impl Display for Action {
30	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
31		match *self {
32			Action::Create => write!(f, "CREATE"),
33			Action::Update => write!(f, "UPDATE"),
34			Action::Delete => write!(f, "DELETE"),
35			Action::Killed => write!(f, "KILLED"),
36		}
37	}
38}
39
40impl FromStr for Action {
41	type Err = crate::Error;
42
43	fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
44		match s {
45			"CREATE" => Ok(Action::Create),
46			"UPDATE" => Ok(Action::Update),
47			"DELETE" => Ok(Action::Delete),
48			"KILLED" => Ok(Action::Killed),
49			_ => Err(crate::Error::validation(format!("Invalid action: {s}"), None)),
50		}
51	}
52}
53
54/// A live query notification.
55#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SurrealValue)]
56#[surreal(crate = "crate")]
57#[non_exhaustive]
58pub struct Notification {
59	/// The id of the LIVE query to which this notification belongs
60	pub id: Uuid,
61	/// The ID of the session that sent this notification
62	pub session: Option<Uuid>,
63	/// The CREATE / UPDATE / DELETE action which caused this notification
64	pub action: Action,
65	/// The id of the document to which this notification has been made
66	pub record: Value,
67	/// The resulting notification content, usually the altered record content
68	pub result: Value,
69}
70
71impl Notification {
72	/// Construct a new notification.
73	pub fn new(
74		id: Uuid,
75		session: Option<Uuid>,
76		action: Action,
77		record: Value,
78		result: Value,
79	) -> Self {
80		Self {
81			id,
82			session,
83			action,
84			record,
85			result,
86		}
87	}
88}