Skip to content

Commit

Permalink
Rearrange query string errors logic
Browse files Browse the repository at this point in the history
  • Loading branch information
SleeplessOne1917 committed Jan 11, 2024
1 parent 2dbff24 commit 463f778
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 38 deletions.
14 changes: 6 additions & 8 deletions integrations/actix/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ use actix_web::{
use futures::{Stream, StreamExt};
use leptos::{
leptos_server::{server_fn_by_path, Payload},
server_fn::Encoding,
server_fn::{Encoding, query_to_errors},
ssr::render_to_stream_with_prefix_undisposed_with_context_and_block_replacement,
*,
};
use leptos_integration_utils::{
build_async_response, filter_server_fn_url_errors, html_parts_separated,
build_async_response, html_parts_separated,
referrer_to_url, WithServerFn,
};
use leptos_meta::*;
Expand Down Expand Up @@ -761,12 +761,10 @@ fn provide_contexts(req: &HttpRequest, res_options: ResponseOptions) {
provide_context(MetaContext::new());
provide_context(res_options);
provide_context(req.clone());
if let Some(referrer) = req.headers().get(header::REFERER) {
leptos::logging::log!("Referrer = {referrer:?}");
provide_context(filter_server_fn_url_errors(
referrer
.to_str()
.expect("Invalid referer header from browser request"),
if let Some(query) = req.uri().query() {
leptos::logging::log!("query = {query}");
provide_context(query_to_errors(
query
));
}

Expand Down
21 changes: 0 additions & 21 deletions integrations/utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use leptos::{
use leptos_config::LeptosOptions;
use leptos_meta::MetaContext;
use regex::Regex;
use std::collections::HashSet;
use url::Url;

extern crate tracing;
Expand Down Expand Up @@ -165,26 +164,6 @@ pub async fn build_async_response(
format!("{head}<body{body_meta}>{buf}{tail}")
}

pub fn filter_server_fn_url_errors<'a>(
referrer: impl Into<&'a str>,
) -> HashSet<ServerFnUrlError> {
Url::parse(referrer.into())
.expect("Cannot parse referrer from page request")
.query_pairs()
.into_iter()
.filter_map(|(k, v)| {

let foo = if k.starts_with("server_fn_error_") {
serde_qs::from_str::<'_, ServerFnUrlError>(v.as_ref()).ok()
} else {
None
};
leptos::logging::log!("Parsed query key {k} with value {foo:?}");
foo
})
.collect()
}

pub fn referrer_to_url(referer: &HeaderValue, fn_name: &str) -> Option<Url> {
Url::parse(
&Regex::new(&format!(r"(?:\?|&)?server_fn_error_{fn_name}=[^&]+"))
Expand Down
2 changes: 1 addition & 1 deletion leptos/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ pub use leptos_server::{
create_server_multi_action, Action, MultiAction, ServerFn, ServerFnError,
ServerFnErrorErr,
};
pub use server_fn::{self, ServerFn as _};
pub use server_fn::{self, query_to_errors, ServerFn as _};
mod error_boundary;
pub use error_boundary::*;
mod animated_show;
Expand Down
16 changes: 9 additions & 7 deletions router/src/components/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,20 +450,22 @@ where
let version = action.version();
let value = action.value();
let input = action.input();
let errors = use_context::<HashSet<ServerFnUrlError>>();

if let (Some(url_error), Some(error)) = (
let effect_action_url = action_url.clone();
Effect::new_isomorphic(move |_| {
let errors = use_context::<HashSet<ServerFnUrlError>>();
if let Some(url_error) =
errors
.map(|errors| {
errors
.into_iter()
.find(|e| action_url.contains(e.fn_name()))
.find(|e| effect_action_url.contains(e.fn_name()))
})
.flatten(),
error,
) {
error.try_set(Some(Box::new(ServerFnErrorErr::from(url_error))));
.flatten() {
leptos::logging::log!("In iso effect with error = {url_error:?}");
value.try_set(Some(Err(url_error.error().clone())));
}
});

let on_error = Rc::new(move |e: &gloo_net::Error| {
batch(move || {
Expand Down
1 change: 1 addition & 0 deletions server_fn/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ xxhash-rust = { version = "0.8", features = ["const_xxh64"] }
const_format = "0.2"
inventory = { version = "0.3", optional = true }
lazy_static = "1"
url = "2.5.0"

[dev-dependencies]
server_fn = { version = "0.2" }
Expand Down
23 changes: 22 additions & 1 deletion server_fn/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
// used by the macro
#[doc(hidden)]
pub use const_format;
use error::ServerFnUrlError;
// used by the macro
#[cfg(feature = "ssr")]
#[doc(hidden)]
Expand All @@ -95,7 +96,8 @@ use quote::TokenStreamExt;
pub use serde;
use serde::{de::DeserializeOwned, Serialize};
pub use server_fn_macro_default::server;
use std::{future::Future, pin::Pin, str::FromStr};
use url::Url;
use std::{future::Future, pin::Pin, str::FromStr, collections::HashSet};
#[cfg(any(feature = "ssr", doc))]
use syn::parse_quote;
// used by the macro
Expand Down Expand Up @@ -619,3 +621,22 @@ fn get_server_url() -> &'static str {
.get()
.expect("Call set_root_url before calling a server function.")
}

#[doc(hidden)]
pub fn query_to_errors(query: &str) -> HashSet<ServerFnUrlError> {
// Url::parse needs an full absolute URL to parse correctly.
// Since this function is only interested in the query pairs,
// the specific scheme and domain do not matter.
Url::parse(&format!("http://base.com?{query}"))
.expect("Cannot parse referrer from page request")
.query_pairs()
.into_iter()
.filter_map(|(k, v)| {
if k.starts_with("server_fn_error_") {
serde_qs::from_str::<'_, ServerFnUrlError>(v.as_ref()).ok()
} else {
None
}
})
.collect()
}

0 comments on commit 463f778

Please sign in to comment.