use crate::middleware::OUTGOING_MAILBOX;
use std::fmt::{Debug, Display, Formatter};
#[derive(serde::Deserialize, serde::Serialize, Clone)]
#[must_use = "You must call `.send()` on a `FlashMessage` for it to have an effect"]
pub struct FlashMessage {
content: String,
level: Level,
}
impl FlashMessage {
pub fn new(content: String, level: Level) -> Self {
Self { content, level }
}
pub fn content(&self) -> &str {
&self.content
}
pub fn level(&self) -> Level {
self.level
}
pub fn info<S: Into<String>>(content: S) -> Self {
Self {
content: content.into(),
level: Level::Info,
}
}
pub fn debug<S: Into<String>>(content: S) -> Self {
Self {
content: content.into(),
level: Level::Debug,
}
}
pub fn success<S: Into<String>>(content: S) -> Self {
Self {
content: content.into(),
level: Level::Success,
}
}
pub fn warning<S: Into<String>>(content: S) -> Self {
Self {
content: content.into(),
level: Level::Warning,
}
}
pub fn error<S: Into<String>>(content: S) -> Self {
Self {
content: content.into(),
level: Level::Error,
}
}
pub fn send(self) {
let result = OUTGOING_MAILBOX.try_with(|mailbox| {
if self.level as u8 >= mailbox.minimum_level as u8 {
mailbox.messages.borrow_mut().push(self);
}
});
if result.is_err() {
panic!("Failed to send flash message!\n\
To use `FlashMessages::send` you need to add `FlashMessageFramework` as a middleware \
on your `actix-web` application using `wrap`. Check out `actix-web-flash-messages`'s documentation for more details.")
}
}
}
#[derive(serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, PartialOrd, Eq)]
pub enum Level {
Debug = 0,
Info = 1,
Success = 2,
Warning = 3,
Error = 4,
}
impl Debug for Level {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", level_to_str(self))
}
}
impl Display for Level {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", level_to_str(self))
}
}
fn level_to_str(l: &Level) -> &'static str {
match l {
Level::Debug => "debug",
Level::Info => "info",
Level::Success => "success",
Level::Warning => "warning",
Level::Error => "error",
}
}