]> Untitled Git - lemmy.git/blob - crates/utils/src/lib.rs
Adding unique constraint for activity ap_id. Fixes #1878 (#1935)
[lemmy.git] / crates / utils / src / lib.rs
1 #[macro_use]
2 extern crate lazy_static;
3 #[macro_use]
4 extern crate strum_macros;
5 #[macro_use]
6 extern crate smart_default;
7
8 pub mod apub;
9 pub mod email;
10 pub mod rate_limit;
11 pub mod request;
12 pub mod settings;
13
14 pub mod claims;
15 #[cfg(test)]
16 mod test;
17 pub mod utils;
18 pub mod version;
19
20 use http::StatusCode;
21 use log::warn;
22 use std::{fmt, fmt::Display};
23 use thiserror::Error;
24
25 pub type ConnectionId = usize;
26
27 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
28 pub struct IpAddr(pub String);
29
30 impl fmt::Display for IpAddr {
31   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32     write!(f, "{}", self.0)
33   }
34 }
35
36 #[macro_export]
37 macro_rules! location_info {
38   () => {
39     format!(
40       "None value at {}:{}, column {}",
41       file!(),
42       line!(),
43       column!()
44     )
45   };
46 }
47
48 #[derive(Debug, Error)]
49 #[error("{{\"error\":\"{message}\"}}")]
50 pub struct ApiError {
51   message: String,
52 }
53
54 impl ApiError {
55   pub fn err_plain(msg: &str) -> Self {
56     ApiError {
57       message: msg.to_string(),
58     }
59   }
60   pub fn err<E: Display>(msg: &str, original_error: E) -> Self {
61     warn!("{}", original_error);
62     ApiError {
63       message: msg.to_string(),
64     }
65   }
66 }
67
68 #[derive(Debug)]
69 pub struct LemmyError {
70   pub inner: anyhow::Error,
71 }
72
73 impl<T> From<T> for LemmyError
74 where
75   T: Into<anyhow::Error>,
76 {
77   fn from(t: T) -> Self {
78     LemmyError { inner: t.into() }
79   }
80 }
81
82 impl Display for LemmyError {
83   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
84     self.inner.fmt(f)
85   }
86 }
87
88 impl actix_web::error::ResponseError for LemmyError {
89   fn status_code(&self) -> StatusCode {
90     match self.inner.downcast_ref::<diesel::result::Error>() {
91       Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
92       _ => StatusCode::INTERNAL_SERVER_ERROR,
93     }
94   }
95 }