]> Untitled Git - lemmy.git/blob - crates/utils/src/lib.rs
Explicit error http status codes (#1362)
[lemmy.git] / crates / utils / src / lib.rs
1 #[macro_use]
2 extern crate lazy_static;
3 #[macro_use]
4 extern crate strum_macros;
5
6 pub mod apub;
7 pub mod email;
8 pub mod rate_limit;
9 pub mod request;
10 pub mod settings;
11 #[cfg(test)]
12 mod test;
13 pub mod utils;
14
15 use crate::settings::Settings;
16 use http::StatusCode;
17 use regex::Regex;
18 use thiserror::Error;
19
20 pub type ConnectionId = usize;
21 pub type PostId = i32;
22 pub type CommunityId = i32;
23 pub type UserId = i32;
24 pub type IPAddr = String;
25
26 #[macro_export]
27 macro_rules! location_info {
28   () => {
29     format!(
30       "None value at {}:{}, column {}",
31       file!(),
32       line!(),
33       column!()
34     )
35   };
36 }
37
38 #[derive(Debug, Error)]
39 #[error("{{\"error\":\"{message}\"}}")]
40 pub struct APIError {
41   pub message: String,
42 }
43
44 impl APIError {
45   pub fn err(msg: &str) -> Self {
46     APIError {
47       message: msg.to_string(),
48     }
49   }
50 }
51
52 #[derive(Debug)]
53 pub struct LemmyError {
54   pub inner: anyhow::Error,
55 }
56
57 impl<T> From<T> for LemmyError
58 where
59   T: Into<anyhow::Error>,
60 {
61   fn from(t: T) -> Self {
62     LemmyError { inner: t.into() }
63   }
64 }
65
66 impl std::fmt::Display for LemmyError {
67   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
68     self.inner.fmt(f)
69   }
70 }
71
72 impl actix_web::error::ResponseError for LemmyError {
73   fn status_code(&self) -> StatusCode {
74     match self.inner.downcast_ref::<diesel::result::Error>() {
75       Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
76       _ => StatusCode::INTERNAL_SERVER_ERROR,
77     }
78   }
79 }
80
81 lazy_static! {
82   pub static ref WEBFINGER_COMMUNITY_REGEX: Regex = Regex::new(&format!(
83     "^group:([a-z0-9_]{{3, 20}})@{}$",
84     Settings::get().hostname
85   ))
86   .unwrap();
87   pub static ref WEBFINGER_USER_REGEX: Regex = Regex::new(&format!(
88     "^acct:([a-z0-9_]{{3, 20}})@{}$",
89     Settings::get().hostname
90   ))
91   .unwrap();
92 }