Skip to content

Commit

Permalink
Add flash message supports Add support for flash message #158
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn committed Sep 28, 2022
1 parent 8eb0ceb commit bff3def
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 68 deletions.
8 changes: 4 additions & 4 deletions crates/flash/Cargo.toml
Expand Up @@ -19,17 +19,17 @@ rustdoc-args = ["--cfg", "docsrs"]

[features]
default = ["cookie_store"]
cookie_store = ["salvo_core/cookie"]
cookie_store = ["salvo_core/cookie", "dep:serde_json"]
session_store = ["dep:salvo-session"]

[dependencies]
async-session = { workspace = true, optional = true }
salvo_core = { workspace = true, default-features = false }
salvo_extra = { workspace = true, default-features = false }
salvo-session = { workspace = true, default-features = false, optional = true }
tracing = "0.1"
serde = "1"
serde_json = "1"
tracing.workspace = true
serde.workspace = true
serde_json = { workspace = true, optional = true }

[dev-dependencies]
salvo_core = {workspace = true, features = ["test"] }
Expand Down
23 changes: 6 additions & 17 deletions crates/flash/src/lib.rs
Expand Up @@ -12,23 +12,13 @@ cfg_feature! {

mod cookie_store;
pub use cookie_store::CookieStore;

/// Helper function to create a new `CookieStore`.
pub fn cookie_store() -> CookieStore {
CookieStore::new()
}
}

cfg_feature! {
#![feature = "session_store"]

mod session_store;
pub use session_store::SessionStore;

/// Helper function to create a new `SessionStore`.
pub fn session_store() -> SessionStore {
SessionStore::new()
}
}

/// Key for incoming flash messages in depot.
Expand Down Expand Up @@ -266,8 +256,10 @@ mod tests {
#[handler]
pub async fn get_flash(depot: &mut Depot, _res: &mut Response) -> String {
let mut body = String::new();
for message in depot.incoming_flash().unwrap().iter() {
writeln!(body, "{} - {}", message.value, message.level).unwrap();
if let Some(flash) = depot.incoming_flash() {
for message in flash.iter() {
writeln!(body, "{} - {}", message.value, message.level).unwrap();
}
}
body
}
Expand All @@ -277,7 +269,7 @@ mod tests {
async fn test_cookie_store() {
let cookie_name = "my-custom-cookie-name".to_string();
let router = Router::new()
.hoop(cookie_store().with_name(&cookie_name).into_handler())
.hoop(CookieStore::new().with_name(&cookie_name).into_handler())
.push(Router::with_path("get").get(get_flash))
.push(Router::with_path("set").get(set_flash));
let service = Service::new(router);
Expand All @@ -286,7 +278,6 @@ mod tests {
assert_eq!(respone.status_code(), Some(StatusCode::SEE_OTHER));

let cookie = respone.headers().get(SET_COOKIE).unwrap();
println!("cookie: {:?}", cookie);
assert!(cookie.to_str().unwrap().contains(&cookie_name));

let mut respone = TestClient::get("http://127.0.0.1:7878/get")
Expand Down Expand Up @@ -318,7 +309,7 @@ mod tests {
let session_name = "my-custom-session-name".to_string();
let router = Router::new()
.hoop(session_handler)
.hoop(session_store().with_name(&session_name).into_handler())
.hoop(SessionStore::new().with_name(&session_name).into_handler())
.push(Router::with_path("get").get(get_flash))
.push(Router::with_path("set").get(set_flash));
let service = Service::new(router);
Expand All @@ -334,8 +325,6 @@ mod tests {
.await;
assert!(respone.take_string().await.unwrap().contains("Hey there!"));

let cookie = respone.headers().get(SET_COOKIE).unwrap();

let mut respone = TestClient::get("http://127.0.0.1:7878/get")
.add_header(COOKIE, cookie, true)
.send(&service)
Expand Down
4 changes: 2 additions & 2 deletions crates/flash/src/session_store.rs
@@ -1,4 +1,4 @@
use salvo_core::{async_trait, Depot, Request, Response, Result};
use salvo_core::{async_trait, Depot, Request, Response};
use salvo_session::SessionDepotExt;

use super::{Flash, FlashHandler, FlashStore};
Expand Down Expand Up @@ -45,7 +45,7 @@ impl FlashStore for SessionStore {
if let Err(e) = depot
.session_mut()
.expect("session must be exist")
.insert(&self.name, &serde_json::to_string(&flash).unwrap_or_default())
.insert(&self.name, &flash)
{
tracing::error!(error = ?e, "save flash to session failed");
}
Expand Down
66 changes: 21 additions & 45 deletions examples/flash-cookie/src/main.rs
@@ -1,58 +1,34 @@
use std::fmt::Write;

use salvo::prelude::*;
use salvo_flash::{CookieStore, FlashDepotExt};

#[handler]
async fn hello_world() -> &'static str {
"Hello World"
}
#[handler]
async fn hello_world1() -> Result<&'static str, ()> {
Ok("Hello World1")
}
#[handler]
async fn hello_world2(res: &mut Response) {
res.render("Hello World2");
pub async fn set_flash(depot: &mut Depot, res: &mut Response) {
let flash = depot.outgoing_flash_mut();
flash.info("Hey there!").debug("How is it going?");
res.render(Redirect::other("/get").unwrap());
}

#[handler]
async fn hello_world3(_req: &mut Request, res: &mut Response) {
res.render(Text::Plain("Hello World3"));
pub async fn get_flash(depot: &mut Depot, _res: &mut Response) -> String {
let mut body = String::new();
if let Some(flash) = depot.incoming_flash() {
for message in flash.iter() {
writeln!(body, "{} - {}", message.value, message.level).unwrap();
}
}
body
}

#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();

tracing::info!("Listening on http://127.0.0.1:7878");
Server::new(TcpListener::bind("127.0.0.1:7878")).serve(route()).await;
}

fn route() -> Router {
Router::new()
.get(hello_world)
.push(Router::with_path("hello1").get(hello_world1))
.push(Router::with_path("hello2").get(hello_world2))
.push(Router::with_path("hello3").get(hello_world3))
}

#[cfg(test)]
mod tests {
use salvo::prelude::*;
use salvo::test::{ResponseExt, TestClient};

#[tokio::test]
async fn test_hello_world() {
let service = Service::new(super::route());

async fn access(service: &Service, name: &str) -> String {
TestClient::get(format!("http://127.0.0.1:7878/{}", name))
.send(service)
.await
.take_string()
.await
.unwrap()
}

assert_eq!(access(&service, "hello1").await, "Hello World1");
assert_eq!(access(&service, "hello2").await, "Hello World2");
assert_eq!(access(&service, "hello3").await, "Hello World3");
}
let router = Router::new()
.hoop(CookieStore::new().into_handler())
.push(Router::with_path("get").get(get_flash))
.push(Router::with_path("set").get(set_flash));
Server::new(TcpListener::bind("127.0.0.1:7878")).serve(router).await;
}

0 comments on commit bff3def

Please sign in to comment.