buckets_core/
macros.rs

1#[macro_export]
2macro_rules! auto_method {
3    ($name:ident($selector_t:ty as i64)@$select_fn:ident -> $query:literal --name=$name_:literal --returns=$returns_:tt --cache-key-tmpl=$cache_key_tmpl:literal) => {
4        pub async fn $name(&self, selector: $selector_t) -> Result<$returns_> {
5            if let Some(cached) = self
6                .0
7                .1
8                .get(format!($cache_key_tmpl, selector.to_string()))
9                .await
10            {
11                match serde_json::from_str(&cached) {
12                    Ok(x) => return Ok(x),
13                    Err(_) => {
14                        self.0
15                            .1
16                            .remove(format!($cache_key_tmpl, selector.to_string()))
17                            .await
18                    }
19                };
20            }
21
22            let conn = match self.0.connect().await {
23                Ok(c) => c,
24                Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
25            };
26
27            let res = oiseau::query_row!(&conn, $query, &[&(selector as i64)], |x| {
28                Ok(Self::$select_fn(x))
29            });
30
31            if res.is_err() {
32                return Err(Error::GeneralNotFound($name_.to_string()));
33            }
34
35            let x = res.unwrap();
36            self.0
37                .1
38                .set(
39                    format!($cache_key_tmpl, selector),
40                    serde_json::to_string(&x).unwrap(),
41                )
42                .await;
43
44            Ok(x)
45        }
46    };
47
48    ($name:ident($x:ty) -> $query:literal --serde --cache-key-tmpl=$cache_key_tmpl:literal) => {
49        pub async fn $name(&self, id: usize, x: $x) -> Result<()> {
50            let conn = match self.0.connect().await {
51                Ok(c) => c,
52                Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
53            };
54
55            let res = execute!(
56                &conn,
57                $query,
58                params![&serde_json::to_string(&x).unwrap(), &(id as i64)]
59            );
60
61            if let Err(e) = res {
62                return Err(Error::DatabaseError(e.to_string()));
63            }
64
65            self.0.1.remove(format!($cache_key_tmpl, id)).await;
66
67            Ok(())
68        }
69    };
70}