mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-28 07:52:34 -05:00
Compare commits
20 Commits
result-ali
...
v0.7.7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7be6a9da86 | ||
|
|
c51e07b5a4 | ||
|
|
b17a4c92c7 | ||
|
|
03f9c6cb6d | ||
|
|
9e8b8886da | ||
|
|
6a6b3dee15 | ||
|
|
5d71913523 | ||
|
|
706617ab0a | ||
|
|
cd64bb9d67 | ||
|
|
f881c1877d | ||
|
|
8783f6a478 | ||
|
|
2add714c65 | ||
|
|
88b1b2d882 | ||
|
|
9d3a743d33 | ||
|
|
c6de7c714e | ||
|
|
6154199850 | ||
|
|
32be3a023a | ||
|
|
d9043e4f34 | ||
|
|
e3010c7f1f | ||
|
|
1dcc5838f7 |
2
.github/workflows/run-cargo-make-task.yml
vendored
2
.github/workflows/run-cargo-make-task.yml
vendored
@@ -55,7 +55,7 @@ jobs:
|
||||
- name: Install wasm-bindgen
|
||||
run: cargo binstall wasm-bindgen-cli --no-confirm
|
||||
- name: Install cargo-leptos
|
||||
run: cargo binstall cargo-leptos --no-confirm
|
||||
run: cargo binstall cargo-leptos --locked --no-confirm
|
||||
- name: Install Trunk
|
||||
uses: jetli/trunk-action@v0.5.0
|
||||
with:
|
||||
|
||||
560
Cargo.lock
generated
560
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
36
Cargo.toml
36
Cargo.toml
@@ -40,7 +40,7 @@ members = [
|
||||
exclude = ["benchmarks", "examples", "projects"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.8.0-alpha"
|
||||
version = "0.7.7"
|
||||
edition = "2021"
|
||||
rust-version = "1.76"
|
||||
|
||||
@@ -50,26 +50,26 @@ any_spawner = { path = "./any_spawner/", version = "0.2.0" }
|
||||
const_str_slice_concat = { path = "./const_str_slice_concat", version = "0.1" }
|
||||
either_of = { path = "./either_of/", version = "0.1.0" }
|
||||
hydration_context = { path = "./hydration_context", version = "0.2.0" }
|
||||
leptos = { path = "./leptos", version = "0.8.0-alpha" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.8.0-alpha" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.8.0-alpha" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.8.0-alpha" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.8.0-alpha" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.8.0-alpha" }
|
||||
leptos_router = { path = "./router", version = "0.8.0-alpha" }
|
||||
leptos_router_macro = { path = "./router_macro", version = "0.8.0-alpha" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.8.0-alpha" }
|
||||
leptos_meta = { path = "./meta", version = "0.8.0-alpha" }
|
||||
leptos = { path = "./leptos", version = "0.7.7" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.7.7" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.7.7" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.7" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.7" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.7.7" }
|
||||
leptos_router = { path = "./router", version = "0.7.7" }
|
||||
leptos_router_macro = { path = "./router_macro", version = "0.7.7" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.7.7" }
|
||||
leptos_meta = { path = "./meta", version = "0.7.7" }
|
||||
next_tuple = { path = "./next_tuple", version = "0.1.0" }
|
||||
oco_ref = { path = "./oco", version = "0.2.0" }
|
||||
or_poisoned = { path = "./or_poisoned", version = "0.1.0" }
|
||||
reactive_graph = { path = "./reactive_graph", version = "0.1.4" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.1.3" }
|
||||
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.0" }
|
||||
server_fn = { path = "./server_fn", version = "0.8.0-alpha" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.8.0-alpha" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.8.0-alpha" }
|
||||
tachys = { path = "./tachys", version = "0.1.4" }
|
||||
reactive_graph = { path = "./reactive_graph", version = "0.1.7" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.1.7" }
|
||||
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.7" }
|
||||
server_fn = { path = "./server_fn", version = "0.7.7" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.7.7" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.7" }
|
||||
tachys = { path = "./tachys", version = "0.1.7" }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "throw_error"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -17,6 +17,11 @@ use std::{
|
||||
|
||||
/* Wrapper Types */
|
||||
|
||||
/// This is a result type into which any error can be converted.
|
||||
///
|
||||
/// Results are stored as [`Error`].
|
||||
pub type Result<T, E = Error> = core::result::Result<T, E>;
|
||||
|
||||
/// A generic wrapper for any error.
|
||||
#[derive(Debug, Clone)]
|
||||
#[repr(transparent)]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "either_of"
|
||||
version = "0.1.4"
|
||||
version = "0.1.5"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -15,4 +15,4 @@ paste = "1.0.15"
|
||||
|
||||
[features]
|
||||
default = ["no_std"]
|
||||
no_std = []
|
||||
no_std = []
|
||||
|
||||
@@ -7,7 +7,7 @@ edition = "2021"
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
console_error_panic_hook = "0.1.7"
|
||||
console_log = "1.0"
|
||||
gloo-utils = "0.2.0"
|
||||
@@ -20,27 +20,18 @@ leptos_axum = { path = "../../integrations/axum", optional = true }
|
||||
leptos_router = { path = "../../router" }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1.39", features = [
|
||||
"rt-multi-thread",
|
||||
"macros",
|
||||
"time",
|
||||
], optional = true }
|
||||
tokio = { version = "1.39", features = [ "rt-multi-thread", "macros", "time" ], optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
wasm-bindgen = "0.2.92"
|
||||
web-sys = { version = "0.3.69", features = [
|
||||
"AddEventListenerOptions",
|
||||
"Document",
|
||||
"Element",
|
||||
"Event",
|
||||
"EventListener",
|
||||
"EventTarget",
|
||||
"Performance",
|
||||
"Window",
|
||||
], optional = true }
|
||||
web-sys = { version = "0.3.69", features = [ "AddEventListenerOptions", "Document", "Element", "Event", "EventListener", "EventTarget", "Performance", "Window" ], optional = true }
|
||||
|
||||
[features]
|
||||
hydrate = ["leptos/hydrate", "dep:js-sys", "dep:web-sys"]
|
||||
hydrate = [
|
||||
"leptos/hydrate",
|
||||
"dep:js-sys",
|
||||
"dep:web-sys",
|
||||
]
|
||||
ssr = [
|
||||
"dep:axum",
|
||||
"dep:http-body-util",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
[tasks.install-cargo-leptos]
|
||||
install_crate = { crate_name = "cargo-leptos", binary = "cargo-leptos", test_arg = "--help" }
|
||||
args = ["--locked"]
|
||||
|
||||
[tasks.cargo-leptos-e2e]
|
||||
command = "cargo"
|
||||
|
||||
@@ -19,7 +19,7 @@ async fn clear() {
|
||||
// note that we start at the initial value of 10
|
||||
let _dispose = mount_to(
|
||||
test_wrapper.clone().unchecked_into(),
|
||||
|| view! { <SimpleCounter initial_value=10 step=1 /> },
|
||||
|| view! { <SimpleCounter initial_value=10 step=1/> },
|
||||
);
|
||||
|
||||
// now we extract the buttons by iterating over the DOM
|
||||
@@ -59,9 +59,9 @@ async fn clear() {
|
||||
// .into_view() here is just a convenient way of specifying "use the regular DOM renderer"
|
||||
.into_view()
|
||||
// views are lazy -- they describe a DOM tree but don't create it yet
|
||||
// calling .build(None) will actually build the DOM elements
|
||||
.build(None)
|
||||
// .build(None) returned an ElementState, which is a smart pointer for
|
||||
// calling .build() will actually build the DOM elements
|
||||
.build()
|
||||
// .build() returned an ElementState, which is a smart pointer for
|
||||
// a DOM element. So we can still just call .outer_html(), which access the outerHTML on
|
||||
// the actual DOM element
|
||||
.outer_html()
|
||||
@@ -87,7 +87,7 @@ async fn inc() {
|
||||
|
||||
let _dispose = mount_to(
|
||||
test_wrapper.clone().unchecked_into(),
|
||||
|| view! { <SimpleCounter initial_value=0 step=1 /> },
|
||||
|| view! { <SimpleCounter initial_value=0 step=1/> },
|
||||
);
|
||||
|
||||
// You can do testing with vanilla DOM operations
|
||||
@@ -150,7 +150,7 @@ async fn inc() {
|
||||
}
|
||||
}
|
||||
.into_view()
|
||||
.build(None)
|
||||
.build()
|
||||
.outer_html()
|
||||
);
|
||||
|
||||
@@ -173,7 +173,7 @@ async fn inc() {
|
||||
}
|
||||
}
|
||||
.into_view()
|
||||
.build(None)
|
||||
.build()
|
||||
.outer_html()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ leptos_axum = { path = "../../integrations/axum", optional = true }
|
||||
leptos_meta = { path = "../../meta" }
|
||||
leptos_router = { path = "../../router" }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = ["full"], optional = true }
|
||||
|
||||
@@ -45,7 +45,7 @@ async fn main() {
|
||||
|
||||
// build our application with a route
|
||||
let app = Router::new()
|
||||
.route("/special/{id}", get(custom_handler))
|
||||
.route("/special/:id", get(custom_handler))
|
||||
.leptos_routes(&leptos_options, routes, {
|
||||
let leptos_options = leptos_options.clone();
|
||||
move || shell(leptos_options.clone())
|
||||
|
||||
@@ -20,7 +20,7 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
tracing = "0.1.40"
|
||||
gloo-net = { version = "0.6.0", features = ["http"] }
|
||||
reqwest = { version = "0.12.5", features = ["json"] }
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = ["full"], optional = true }
|
||||
|
||||
@@ -20,7 +20,7 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
tracing = "0.1.40"
|
||||
gloo-net = { version = "0.6.0", features = ["http"] }
|
||||
reqwest = { version = "0.12.5", features = ["json"] }
|
||||
axum = { version = "0.8.1", optional = true, features = ["http2"] }
|
||||
axum = { version = "0.7.5", optional = true, features = ["http2"] }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = [
|
||||
"fs",
|
||||
|
||||
@@ -23,7 +23,7 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
tracing = "0.1.40"
|
||||
gloo-net = { version = "0.6.0", features = ["http"] }
|
||||
reqwest = { version = "0.12.5", features = ["json"] }
|
||||
axum = { version = "0.8.1", default-features = false, optional = true }
|
||||
axum = { version = "0.7.5", default-features = false, optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
http = { version = "1.1", optional = true }
|
||||
web-sys = { version = "0.3.70", features = [
|
||||
|
||||
@@ -10,12 +10,15 @@ crate-type = ["cdylib", "rlib"]
|
||||
console_error_panic_hook = "0.1.7"
|
||||
futures = "0.3.30"
|
||||
http = "1.1"
|
||||
leptos = { path = "../../leptos", features = ["tracing", "islands"] }
|
||||
leptos = { path = "../../leptos", features = [
|
||||
"tracing",
|
||||
"islands",
|
||||
] }
|
||||
server_fn = { path = "../../server_fn", features = ["serde-lite"] }
|
||||
leptos_axum = { path = "../../integrations/axum", optional = true }
|
||||
log = "0.4.22"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = ["full"], optional = true }
|
||||
|
||||
@@ -10,7 +10,10 @@ crate-type = ["cdylib", "rlib"]
|
||||
console_error_panic_hook = "0.1.7"
|
||||
futures = "0.3.30"
|
||||
http = "1.1"
|
||||
leptos = { path = "../../leptos", features = ["tracing", "islands"] }
|
||||
leptos = { path = "../../leptos", features = [
|
||||
"tracing",
|
||||
"islands",
|
||||
] }
|
||||
leptos_router = { path = "../../router" }
|
||||
server_fn = { path = "../../server_fn", features = ["serde-lite"] }
|
||||
leptos_axum = { path = "../../integrations/axum", features = [
|
||||
@@ -18,7 +21,7 @@ leptos_axum = { path = "../../integrations/axum", features = [
|
||||
], optional = true }
|
||||
log = "0.4.22"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = ["full"], optional = true }
|
||||
|
||||
@@ -21,7 +21,7 @@ server_fn = { path = "../../server_fn", features = [
|
||||
log = "0.4.22"
|
||||
simple_logger = "5.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = [
|
||||
"fs",
|
||||
|
||||
@@ -9,9 +9,8 @@ use server_fn::{
|
||||
MultipartFormData, Postcard, Rkyv, SerdeLite, StreamingText,
|
||||
TextStream,
|
||||
},
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
request::{browser::BrowserRequest, ClientReq, Req},
|
||||
response::{browser::BrowserResponse, ClientRes, TryRes},
|
||||
response::{browser::BrowserResponse, ClientRes, Res},
|
||||
};
|
||||
use std::future::Future;
|
||||
#[cfg(feature = "ssr")]
|
||||
@@ -653,72 +652,32 @@ pub fn FileWatcher() -> impl IntoView {
|
||||
/// implementations if you'd like. However, it's much lighter weight to use something like `strum`
|
||||
/// simply to generate those trait implementations.
|
||||
#[server]
|
||||
pub async fn ascii_uppercase(text: String) -> Result<String, MyErrors> {
|
||||
other_error()?;
|
||||
Ok(ascii_uppercase_inner(text)?)
|
||||
}
|
||||
|
||||
pub fn other_error() -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn ascii_uppercase_inner(text: String) -> Result<String, InvalidArgument> {
|
||||
pub async fn ascii_uppercase(
|
||||
text: String,
|
||||
) -> Result<String, ServerFnError<InvalidArgument>> {
|
||||
if text.len() < 5 {
|
||||
Err(InvalidArgument::TooShort)
|
||||
Err(InvalidArgument::TooShort.into())
|
||||
} else if text.len() > 15 {
|
||||
Err(InvalidArgument::TooLong)
|
||||
Err(InvalidArgument::TooLong.into())
|
||||
} else if text.is_ascii() {
|
||||
Ok(text.to_ascii_uppercase())
|
||||
} else {
|
||||
Err(InvalidArgument::NotAscii)
|
||||
Err(InvalidArgument::NotAscii.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn ascii_uppercase_classic(
|
||||
text: String,
|
||||
) -> Result<String, ServerFnError<InvalidArgument>> {
|
||||
Ok(ascii_uppercase_inner(text)?)
|
||||
}
|
||||
|
||||
// The EnumString and Display derive macros are provided by strum
|
||||
#[derive(Debug, Clone, Display, EnumString, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, EnumString, Display)]
|
||||
pub enum InvalidArgument {
|
||||
TooShort,
|
||||
TooLong,
|
||||
NotAscii,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Display, Serialize, Deserialize)]
|
||||
pub enum MyErrors {
|
||||
InvalidArgument(InvalidArgument),
|
||||
ServerFnError(ServerFnErrorErr),
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl From<InvalidArgument> for MyErrors {
|
||||
fn from(value: InvalidArgument) -> Self {
|
||||
MyErrors::InvalidArgument(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for MyErrors {
|
||||
fn from(value: String) -> Self {
|
||||
MyErrors::Other(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromServerFnError for MyErrors {
|
||||
fn from_server_fn_error(value: ServerFnErrorErr) -> Self {
|
||||
MyErrors::ServerFnError(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn CustomErrorTypes() -> impl IntoView {
|
||||
let input_ref = NodeRef::<Input>::new();
|
||||
let (result, set_result) = signal(None);
|
||||
let (result_classic, set_result_classic) = signal(None);
|
||||
|
||||
view! {
|
||||
<h3>Using custom error types</h3>
|
||||
@@ -733,17 +692,14 @@ pub fn CustomErrorTypes() -> impl IntoView {
|
||||
<button on:click=move |_| {
|
||||
let value = input_ref.get().unwrap().value();
|
||||
spawn_local(async move {
|
||||
let data = ascii_uppercase(value.clone()).await;
|
||||
let data_classic = ascii_uppercase_classic(value).await;
|
||||
let data = ascii_uppercase(value).await;
|
||||
set_result.set(Some(data));
|
||||
set_result_classic.set(Some(data_classic));
|
||||
});
|
||||
}>
|
||||
|
||||
"Submit"
|
||||
</button>
|
||||
<p>{move || format!("{:?}", result.get())}</p>
|
||||
<p>{move || format!("{:?}", result_classic.get())}</p>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -770,12 +726,14 @@ impl<T, Request, Err> IntoReq<Toml, Request, Err> for TomlEncoded<T>
|
||||
where
|
||||
Request: ClientReq<Err>,
|
||||
T: Serialize,
|
||||
Err: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, Err> {
|
||||
let data = toml::to_string(&self.0).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<Err>> {
|
||||
let data = toml::to_string(&self.0)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Request::try_new_post(path, Toml::CONTENT_TYPE, accepts, data)
|
||||
}
|
||||
}
|
||||
@@ -784,26 +742,23 @@ impl<T, Request, Err> FromReq<Toml, Request, Err> for TomlEncoded<T>
|
||||
where
|
||||
Request: Req<Err> + Send,
|
||||
T: DeserializeOwned,
|
||||
Err: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, Err> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<Err>> {
|
||||
let string_data = req.try_into_string().await?;
|
||||
toml::from_str::<T>(&string_data)
|
||||
.map(TomlEncoded)
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Response, Err> IntoRes<Toml, Response, Err> for TomlEncoded<T>
|
||||
where
|
||||
Response: TryRes<Err>,
|
||||
Response: Res<Err>,
|
||||
T: Serialize + Send,
|
||||
Err: FromServerFnError,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, Err> {
|
||||
let data = toml::to_string(&self.0).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<Err>> {
|
||||
let data = toml::to_string(&self.0)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Response::try_from_string(Toml::CONTENT_TYPE, data)
|
||||
}
|
||||
}
|
||||
@@ -812,13 +767,12 @@ impl<T, Response, Err> FromRes<Toml, Response, Err> for TomlEncoded<T>
|
||||
where
|
||||
Response: ClientRes<Err> + Send,
|
||||
T: DeserializeOwned,
|
||||
Err: FromServerFnError,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, Err> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<Err>> {
|
||||
let data = res.try_into_string().await?;
|
||||
toml::from_str(&data).map(TomlEncoded).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
toml::from_str(&data)
|
||||
.map(TomlEncoded)
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -881,10 +835,7 @@ pub fn CustomClientExample() -> impl IntoView {
|
||||
pub struct CustomClient;
|
||||
|
||||
// Implement the `Client` trait for it.
|
||||
impl<E> Client<E> for CustomClient
|
||||
where
|
||||
E: FromServerFnError,
|
||||
{
|
||||
impl<CustErr> Client<CustErr> for CustomClient {
|
||||
// BrowserRequest and BrowserResponse are the defaults used by other server functions.
|
||||
// They are wrappers for the underlying Web Fetch API types.
|
||||
type Request = BrowserRequest;
|
||||
@@ -893,7 +844,8 @@ pub fn CustomClientExample() -> impl IntoView {
|
||||
// Our custom `send()` implementation does all the work.
|
||||
fn send(
|
||||
req: Self::Request,
|
||||
) -> impl Future<Output = Result<Self::Response, E>> + Send {
|
||||
) -> impl Future<Output = Result<Self::Response, ServerFnError<CustErr>>>
|
||||
+ Send {
|
||||
// BrowserRequest derefs to the underlying Request type from gloo-net,
|
||||
// so we can get access to the headers here
|
||||
let headers = req.headers();
|
||||
|
||||
@@ -20,7 +20,7 @@ leptos_router = { path = "../../router" }
|
||||
log = "0.4.22"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
thiserror = "1.0"
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = [
|
||||
|
||||
@@ -18,7 +18,7 @@ leptos_router = { path = "../../router" }
|
||||
log = "0.4.22"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
thiserror = "1.0"
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = [
|
||||
@@ -45,7 +45,7 @@ ssr = [
|
||||
"dep:leptos_axum",
|
||||
"leptos_router/ssr",
|
||||
"dep:notify",
|
||||
"dep:http",
|
||||
"dep:http"
|
||||
]
|
||||
|
||||
[profile.release]
|
||||
|
||||
@@ -7,7 +7,7 @@ edition = "2021"
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
console_error_panic_hook = "0.1.7"
|
||||
leptos = { path = "../../leptos" }
|
||||
leptos_meta = { path = "../../meta" }
|
||||
|
||||
@@ -16,7 +16,7 @@ leptos_axum = { path = "../../integrations/axum", optional = true }
|
||||
log = "0.4.22"
|
||||
simple_logger = "5.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = ["full"], optional = true }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#[cfg(feature = "ssr")]
|
||||
use crate::todo::*;
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::Path,
|
||||
@@ -8,9 +8,10 @@ use axum::{
|
||||
Router,
|
||||
};
|
||||
use leptos::prelude::*;
|
||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||
use todo_app_sqlite_axum::*;
|
||||
|
||||
//Define a handler to test extractor with state
|
||||
#[cfg(feature = "ssr")]
|
||||
async fn custom_handler(
|
||||
Path(id): Path<String>,
|
||||
req: Request<Body>,
|
||||
@@ -19,16 +20,14 @@ async fn custom_handler(
|
||||
move || {
|
||||
provide_context(id.clone());
|
||||
},
|
||||
todo::TodoApp,
|
||||
TodoApp,
|
||||
);
|
||||
handler(req).await.into_response()
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
use crate::todo::{ssr::db, *};
|
||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||
use crate::todo::ssr::db;
|
||||
|
||||
simple_logger::init_with_level(log::Level::Error)
|
||||
.expect("couldn't initialize logging");
|
||||
@@ -46,7 +45,7 @@ async fn main() {
|
||||
|
||||
// build our application with a route
|
||||
let app = Router::new()
|
||||
.route("/special/{id}", get(custom_handler))
|
||||
.route("/special/:id", get(custom_handler))
|
||||
.leptos_routes(&leptos_options, routes, {
|
||||
let leptos_options = leptos_options.clone();
|
||||
move || shell(leptos_options.clone())
|
||||
@@ -62,12 +61,3 @@ async fn main() {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
pub fn main() {
|
||||
use leptos::mount::mount_to_body;
|
||||
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
console_error_panic_hook::set_once();
|
||||
mount_to_body(todo::TodoApp);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ leptos_meta = { path = "../../meta" }
|
||||
leptos_router = { path = "../../router" }
|
||||
leptos_integration_utils = { path = "../../integrations/utils", optional = true }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.5.1", features = ["util"], optional = true }
|
||||
tower-http = { version = "0.6.1", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = ["full"], optional = true }
|
||||
|
||||
@@ -34,7 +34,7 @@ async fn main() {
|
||||
// here, we're not actually doing server side rendering, so we set up a manual
|
||||
// handler for the server fns
|
||||
// this should include a get() handler if you have any GetUrl-based server fns
|
||||
.route("/api/{*fn_name}", post(leptos_axum::handle_server_fns))
|
||||
.route("/api/*fn_name", post(leptos_axum::handle_server_fns))
|
||||
.fallback(file_or_index_handler)
|
||||
.with_state(leptos_options);
|
||||
|
||||
|
||||
@@ -369,6 +369,7 @@ pub fn handle_server_fns_with_context(
|
||||
// actually run the server fn
|
||||
let mut res = ActixResponse(
|
||||
service
|
||||
.0
|
||||
.run(ActixRequest::from((req, payload)))
|
||||
.await
|
||||
.take(),
|
||||
|
||||
@@ -11,7 +11,7 @@ edition.workspace = true
|
||||
[dependencies]
|
||||
any_spawner = { workspace = true, features = ["tokio"] }
|
||||
hydration_context = { workspace = true }
|
||||
axum = { version = "0.8.1", default-features = false, features = [
|
||||
axum = { version = "0.7.9", default-features = false, features = [
|
||||
"matched-path",
|
||||
] }
|
||||
dashmap = "6"
|
||||
@@ -30,7 +30,7 @@ tower-http = "0.6.2"
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
axum = "0.8.1"
|
||||
axum = "0.7.9"
|
||||
tokio = { version = "1.41", features = ["net", "rt-multi-thread"] }
|
||||
|
||||
[features]
|
||||
|
||||
@@ -368,6 +368,8 @@ async fn handle_server_fns_inner(
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
req: Request<Body>,
|
||||
) -> impl IntoResponse {
|
||||
use server_fn::middleware::Service;
|
||||
|
||||
let method = req.method().clone();
|
||||
let path = req.uri().path().to_string();
|
||||
let (req, parts) = generate_request_and_parts(req);
|
||||
@@ -482,7 +484,7 @@ pub type PinnedHtmlStream =
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_to_stream<IV>(
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
@@ -506,7 +508,7 @@ where
|
||||
)]
|
||||
pub fn render_route<S, IV>(
|
||||
paths: Vec<AxumRouteListing>,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
State<S>,
|
||||
Request<Body>,
|
||||
@@ -570,7 +572,7 @@ where
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_to_stream_in_order<IV>(
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
@@ -623,14 +625,13 @@ where
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_to_stream_with_context<IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
+ Clone
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
@@ -653,8 +654,8 @@ where
|
||||
)]
|
||||
pub fn render_route_with_context<S, IV>(
|
||||
paths: Vec<AxumRouteListing>,
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
State<S>,
|
||||
Request<Body>,
|
||||
@@ -755,15 +756,14 @@ where
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_to_stream_with_context_and_replace_blocks<IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
replace_blocks: bool,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
+ Clone
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
@@ -823,8 +823,8 @@ where
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_to_stream_in_order_with_context<IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
@@ -847,17 +847,13 @@ where
|
||||
}
|
||||
|
||||
fn handle_response<IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
stream_builder: fn(
|
||||
IV,
|
||||
BoxedFnOnce<PinnedStream<String>>,
|
||||
) -> PinnedFuture<PinnedStream<String>>,
|
||||
) -> impl Fn(Request<Body>) -> PinnedFuture<Response<Body>>
|
||||
+ Clone
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static
|
||||
) -> impl Fn(Request<Body>) -> PinnedFuture<Response<Body>> + Clone + Send + 'static
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
{
|
||||
@@ -984,7 +980,7 @@ fn provide_contexts(
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_async<IV>(
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
@@ -1038,8 +1034,8 @@ where
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_async_stream_with_context<IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
@@ -1105,8 +1101,8 @@ where
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_async_with_context<IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
@@ -1645,7 +1641,7 @@ where
|
||||
self,
|
||||
options: &S,
|
||||
paths: Vec<AxumRouteListing>,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
IV: IntoView + 'static;
|
||||
@@ -1660,8 +1656,8 @@ where
|
||||
self,
|
||||
options: &S,
|
||||
paths: Vec<AxumRouteListing>,
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
IV: IntoView + 'static;
|
||||
@@ -1694,15 +1690,12 @@ impl AxumPath for Vec<PathSegment> {
|
||||
match segment {
|
||||
PathSegment::Static(s) => path.push_str(s),
|
||||
PathSegment::Param(s) => {
|
||||
path.push('{');
|
||||
path.push(':');
|
||||
path.push_str(s);
|
||||
path.push('}');
|
||||
}
|
||||
PathSegment::Splat(s) => {
|
||||
path.push('{');
|
||||
path.push('*');
|
||||
path.push_str(s);
|
||||
path.push('}');
|
||||
}
|
||||
PathSegment::Unit => {}
|
||||
PathSegment::OptionalParam(_) => {
|
||||
@@ -1734,7 +1727,7 @@ where
|
||||
self,
|
||||
state: &S,
|
||||
paths: Vec<AxumRouteListing>,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
@@ -1750,8 +1743,8 @@ where
|
||||
self,
|
||||
state: &S,
|
||||
paths: Vec<AxumRouteListing>,
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
@@ -1988,7 +1981,8 @@ where
|
||||
/// This is provided as a convenience, but is a fairly simple function. If you need to adapt it,
|
||||
/// simply reuse the source code of this function in your own application.
|
||||
#[cfg(feature = "default")]
|
||||
pub fn file_and_error_handler<S, IV>(
|
||||
pub fn file_and_error_handler_with_context<S, IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
shell: fn(LeptosOptions) -> IV,
|
||||
) -> impl Fn(
|
||||
Uri,
|
||||
@@ -2004,40 +1998,68 @@ where
|
||||
LeptosOptions: FromRef<S>,
|
||||
{
|
||||
move |uri: Uri, State(state): State<S>, req: Request<Body>| {
|
||||
Box::pin(async move {
|
||||
let options = LeptosOptions::from_ref(&state);
|
||||
let res = get_static_file(uri, &options.site_root, req.headers());
|
||||
let res = res.await.unwrap();
|
||||
Box::pin({
|
||||
let additional_context = additional_context.clone();
|
||||
async move {
|
||||
let options = LeptosOptions::from_ref(&state);
|
||||
let res =
|
||||
get_static_file(uri, &options.site_root, req.headers());
|
||||
let res = res.await.unwrap();
|
||||
|
||||
if res.status() == StatusCode::OK {
|
||||
res.into_response()
|
||||
} else {
|
||||
let mut res = handle_response_inner(
|
||||
move || {
|
||||
provide_context(state.clone());
|
||||
},
|
||||
move || shell(options),
|
||||
req,
|
||||
|app, chunks| {
|
||||
Box::pin(async move {
|
||||
let app = app
|
||||
.to_html_stream_in_order()
|
||||
.collect::<String>()
|
||||
.await;
|
||||
let chunks = chunks();
|
||||
Box::pin(once(async move { app }).chain(chunks))
|
||||
as PinnedStream<String>
|
||||
})
|
||||
},
|
||||
)
|
||||
.await;
|
||||
*res.status_mut() = StatusCode::NOT_FOUND;
|
||||
res
|
||||
if res.status() == StatusCode::OK {
|
||||
res.into_response()
|
||||
} else {
|
||||
let mut res = handle_response_inner(
|
||||
move || {
|
||||
additional_context();
|
||||
provide_context(state.clone());
|
||||
},
|
||||
move || shell(options),
|
||||
req,
|
||||
|app, chunks| {
|
||||
Box::pin(async move {
|
||||
let app = app
|
||||
.to_html_stream_in_order()
|
||||
.collect::<String>()
|
||||
.await;
|
||||
let chunks = chunks();
|
||||
Box::pin(once(async move { app }).chain(chunks))
|
||||
as PinnedStream<String>
|
||||
})
|
||||
},
|
||||
)
|
||||
.await;
|
||||
*res.status_mut() = StatusCode::NOT_FOUND;
|
||||
res
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A reasonable handler for serving static files (like JS/WASM/CSS) and 404 errors.
|
||||
///
|
||||
/// This is provided as a convenience, but is a fairly simple function. If you need to adapt it,
|
||||
/// simply reuse the source code of this function in your own application.
|
||||
#[cfg(feature = "default")]
|
||||
pub fn file_and_error_handler<S, IV>(
|
||||
shell: fn(LeptosOptions) -> IV,
|
||||
) -> impl Fn(
|
||||
Uri,
|
||||
State<S>,
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
+ Clone
|
||||
+ Send
|
||||
+ 'static
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
S: Send + Sync + Clone + 'static,
|
||||
LeptosOptions: FromRef<S>,
|
||||
{
|
||||
file_and_error_handler_with_context(move || (), shell)
|
||||
}
|
||||
|
||||
#[cfg(feature = "default")]
|
||||
async fn get_static_file(
|
||||
uri: Uri,
|
||||
|
||||
@@ -3,7 +3,6 @@ use crate::attr::{
|
||||
Attribute, NextAttribute,
|
||||
};
|
||||
use leptos::prelude::*;
|
||||
use tachys::view::any_view::ExtraAttrsMut;
|
||||
|
||||
/// Function stored to build/rebuild the wrapped children when attributes are added.
|
||||
type ChildBuilder<T> = dyn Fn(AnyAttribute) -> T + Send + Sync + 'static;
|
||||
@@ -44,7 +43,7 @@ pub fn AttributeInterceptor<Chil, T>(
|
||||
) -> impl IntoView
|
||||
where
|
||||
Chil: Fn(AnyAttribute) -> T + Send + Sync + 'static,
|
||||
T: IntoView + 'static,
|
||||
T: IntoView,
|
||||
{
|
||||
AttributeInterceptorInner::new(children)
|
||||
}
|
||||
@@ -78,20 +77,16 @@ impl<T: IntoView> AttributeInterceptorInner<T, ()> {
|
||||
impl<T: IntoView, A: Attribute> Render for AttributeInterceptorInner<T, A> {
|
||||
type State = <T as Render>::State;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
self.children.build(extra_attrs)
|
||||
fn build(self) -> Self::State {
|
||||
self.children.build()
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
self.children.rebuild(state, extra_attrs);
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
self.children.rebuild(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoView + 'static, A> AddAnyAttr for AttributeInterceptorInner<T, A>
|
||||
impl<T: IntoView, A> AddAnyAttr for AttributeInterceptorInner<T, A>
|
||||
where
|
||||
A: Attribute,
|
||||
{
|
||||
@@ -119,23 +114,19 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoView + 'static, A: Attribute> RenderHtml
|
||||
for AttributeInterceptorInner<T, A>
|
||||
{
|
||||
impl<T: IntoView, A: Attribute> RenderHtml for AttributeInterceptorInner<T, A> {
|
||||
type AsyncOutput = T::AsyncOutput;
|
||||
type Owned = AttributeInterceptorInner<T, A::CloneableOwned>;
|
||||
|
||||
const MIN_LENGTH: usize = T::MIN_LENGTH;
|
||||
|
||||
fn dry_resolve(&mut self, extra_attrs: ExtraAttrsMut<'_>) {
|
||||
self.children.dry_resolve(extra_attrs)
|
||||
fn dry_resolve(&mut self) {
|
||||
self.children.dry_resolve()
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
self,
|
||||
extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> impl std::future::Future<Output = Self::AsyncOutput> + Send {
|
||||
self.children.resolve(extra_attrs)
|
||||
self.children.resolve()
|
||||
}
|
||||
|
||||
fn to_html_with_buf(
|
||||
@@ -144,32 +135,16 @@ impl<T: IntoView + 'static, A: Attribute> RenderHtml
|
||||
position: &mut leptos::tachys::view::Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
self.children.to_html_with_buf(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
)
|
||||
self.children
|
||||
.to_html_with_buf(buf, position, escape, mark_branches)
|
||||
}
|
||||
|
||||
fn hydrate<const FROM_SERVER: bool>(
|
||||
self,
|
||||
cursor: &leptos::tachys::hydration::Cursor,
|
||||
position: &leptos::tachys::view::PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
self.children
|
||||
.hydrate::<FROM_SERVER>(cursor, position, extra_attrs)
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
AttributeInterceptorInner {
|
||||
children_builder: self.children_builder,
|
||||
children: self.children,
|
||||
attributes: self.attributes.into_cloneable_owned(),
|
||||
}
|
||||
self.children.hydrate::<FROM_SERVER>(cursor, position)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,20 +43,13 @@
|
||||
|
||||
use reactive_graph::{
|
||||
owner::{LocalStorage, StoredValue},
|
||||
traits::{Dispose, WithValue},
|
||||
traits::WithValue,
|
||||
};
|
||||
use std::{fmt, rc::Rc, sync::Arc};
|
||||
|
||||
/// A wrapper trait for calling callbacks.
|
||||
pub trait Callable<In: 'static, Out: 'static = ()> {
|
||||
/// calls the callback with the specified argument.
|
||||
///
|
||||
/// Returns None if the callback has been disposed
|
||||
fn try_run(&self, input: In) -> Option<Out>;
|
||||
/// calls the callback with the specified argument.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if you try to run a callback that has been disposed
|
||||
fn run(&self, input: In) -> Out;
|
||||
}
|
||||
|
||||
@@ -79,12 +72,6 @@ impl<In, Out> Clone for UnsyncCallback<In, Out> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<In, Out> Dispose for UnsyncCallback<In, Out> {
|
||||
fn dispose(self) {
|
||||
self.0.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
impl<In, Out> UnsyncCallback<In, Out> {
|
||||
/// Creates a new callback from the given function.
|
||||
pub fn new<F>(f: F) -> UnsyncCallback<In, Out>
|
||||
@@ -106,10 +93,6 @@ impl<In, Out> UnsyncCallback<In, Out> {
|
||||
}
|
||||
|
||||
impl<In: 'static, Out: 'static> Callable<In, Out> for UnsyncCallback<In, Out> {
|
||||
fn try_run(&self, input: In) -> Option<Out> {
|
||||
self.0.try_with_value(|fun| fun(input))
|
||||
}
|
||||
|
||||
fn run(&self, input: In) -> Out {
|
||||
self.0.with_value(|fun| fun(input))
|
||||
}
|
||||
@@ -185,12 +168,10 @@ impl<In, Out> fmt::Debug for Callback<In, Out> {
|
||||
}
|
||||
|
||||
impl<In, Out> Callable<In, Out> for Callback<In, Out> {
|
||||
fn try_run(&self, input: In) -> Option<Out> {
|
||||
self.0.try_with_value(|fun| fun(input))
|
||||
}
|
||||
|
||||
fn run(&self, input: In) -> Out {
|
||||
self.0.with_value(|f| f(input))
|
||||
self.0
|
||||
.try_with_value(|f| f(input))
|
||||
.expect("called a callback that has been disposed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,12 +181,6 @@ impl<In, Out> Clone for Callback<In, Out> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<In, Out> Dispose for Callback<In, Out> {
|
||||
fn dispose(self) {
|
||||
self.0.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
impl<In, Out> Copy for Callback<In, Out> {}
|
||||
|
||||
macro_rules! impl_callable_from_fn {
|
||||
@@ -264,9 +239,7 @@ impl<In: 'static, Out: 'static> Callback<In, Out> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Callable;
|
||||
use crate::callback::{Callback, UnsyncCallback};
|
||||
use reactive_graph::traits::Dispose;
|
||||
|
||||
struct NoClone {}
|
||||
|
||||
@@ -297,22 +270,6 @@ mod tests {
|
||||
(|num, s| format!("{num} {s}")).into();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_callback_try_run() {
|
||||
let callback = Callback::new(move |arg| arg);
|
||||
assert_eq!(callback.try_run((0,)), Some((0,)));
|
||||
callback.dispose();
|
||||
assert_eq!(callback.try_run((0,)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsync_callback_try_run() {
|
||||
let callback = UnsyncCallback::new(move |arg| arg);
|
||||
assert_eq!(callback.try_run((0,)), Some((0,)));
|
||||
callback.dispose();
|
||||
assert_eq!(callback.try_run((0,)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_matches_same() {
|
||||
let callback1 = Callback::new(|x: i32| x * 2);
|
||||
|
||||
@@ -11,13 +11,13 @@ use reactive_graph::{
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::{fmt::Debug, sync::Arc};
|
||||
use tachys::{
|
||||
html::attribute::{any_attribute::AnyAttribute, Attribute},
|
||||
html::attribute::Attribute,
|
||||
hydration::Cursor,
|
||||
reactive_graph::OwnedView,
|
||||
ssr::StreamBuilder,
|
||||
view::{
|
||||
add_attr::AddAnyAttr, any_view::ExtraAttrsMut, Mountable, Position,
|
||||
PositionState, Render, RenderHtml,
|
||||
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
|
||||
RenderHtml,
|
||||
},
|
||||
};
|
||||
use throw_error::{Error, ErrorHook, ErrorId};
|
||||
@@ -173,10 +173,10 @@ where
|
||||
{
|
||||
type State = RenderEffect<ErrorBoundaryViewState<Chil::State, Fal::State>>;
|
||||
|
||||
fn build(mut self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(mut self) -> Self::State {
|
||||
let hook = Arc::clone(&self.hook);
|
||||
let _hook = throw_error::set_error_hook(Arc::clone(&hook));
|
||||
let mut children = Some(self.children.build(extra_attrs.clone()));
|
||||
let mut children = Some(self.children.build());
|
||||
RenderEffect::new(
|
||||
move |prev: Option<
|
||||
ErrorBoundaryViewState<Chil::State, Fal::State>,
|
||||
@@ -193,8 +193,7 @@ where
|
||||
// yes errors, and was showing children
|
||||
(false, None) => {
|
||||
state.fallback = Some(
|
||||
(self.fallback)(self.errors.clone())
|
||||
.build(extra_attrs.clone()),
|
||||
(self.fallback)(self.errors.clone()).build(),
|
||||
);
|
||||
state
|
||||
.children
|
||||
@@ -208,10 +207,8 @@ where
|
||||
}
|
||||
state
|
||||
} else {
|
||||
let fallback = (!self.errors_empty.get()).then(|| {
|
||||
(self.fallback)(self.errors.clone())
|
||||
.build(extra_attrs.clone())
|
||||
});
|
||||
let fallback = (!self.errors_empty.get())
|
||||
.then(|| (self.fallback)(self.errors.clone()).build());
|
||||
ErrorBoundaryViewState {
|
||||
children: children.take().unwrap(),
|
||||
fallback,
|
||||
@@ -221,12 +218,8 @@ where
|
||||
)
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
let new = self.build(extra_attrs);
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
let new = self.build();
|
||||
let mut old = std::mem::replace(state, new);
|
||||
old.insert_before_this(state);
|
||||
old.unmount();
|
||||
@@ -275,18 +268,14 @@ where
|
||||
Fal: RenderHtml + Send + 'static,
|
||||
{
|
||||
type AsyncOutput = ErrorBoundaryView<Chil::AsyncOutput, FalFn>;
|
||||
type Owned = Self;
|
||||
|
||||
const MIN_LENGTH: usize = Chil::MIN_LENGTH;
|
||||
|
||||
fn dry_resolve(&mut self, extra_attrs: ExtraAttrsMut<'_>) {
|
||||
self.children.dry_resolve(extra_attrs);
|
||||
fn dry_resolve(&mut self) {
|
||||
self.children.dry_resolve();
|
||||
}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
let ErrorBoundaryView {
|
||||
hook,
|
||||
boundary_id,
|
||||
@@ -300,7 +289,7 @@ where
|
||||
hook,
|
||||
boundary_id,
|
||||
errors_empty,
|
||||
children: children.resolve(extra_attrs).await,
|
||||
children: children.resolve().await,
|
||||
fallback,
|
||||
errors,
|
||||
}
|
||||
@@ -312,7 +301,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
// first, attempt to serialize the children to HTML, then check for errors
|
||||
let _hook = throw_error::set_error_hook(self.hook);
|
||||
@@ -323,7 +311,6 @@ where
|
||||
&mut new_pos,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs.clone(),
|
||||
);
|
||||
|
||||
// any thrown errors would've been caught here
|
||||
@@ -336,7 +323,6 @@ where
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -347,7 +333,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -360,7 +345,6 @@ where
|
||||
&mut new_pos,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs.clone(),
|
||||
);
|
||||
|
||||
// any thrown errors would've been caught here
|
||||
@@ -374,7 +358,6 @@ where
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
buf.push_sync(&fallback);
|
||||
}
|
||||
@@ -384,7 +367,6 @@ where
|
||||
mut self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let mut children = Some(self.children);
|
||||
let hook = Arc::clone(&self.hook);
|
||||
@@ -406,8 +388,7 @@ where
|
||||
// yes errors, and was showing children
|
||||
(false, None) => {
|
||||
state.fallback = Some(
|
||||
(self.fallback)(self.errors.clone())
|
||||
.build(extra_attrs.clone()),
|
||||
(self.fallback)(self.errors.clone()).build(),
|
||||
);
|
||||
state
|
||||
.children
|
||||
@@ -424,23 +405,15 @@ where
|
||||
let children = children.take().unwrap();
|
||||
let (children, fallback) = if self.errors_empty.get() {
|
||||
(
|
||||
children.hydrate::<FROM_SERVER>(
|
||||
&cursor,
|
||||
&position,
|
||||
extra_attrs.clone(),
|
||||
),
|
||||
children.hydrate::<FROM_SERVER>(&cursor, &position),
|
||||
None,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
children.build(extra_attrs.clone()),
|
||||
children.build(),
|
||||
Some(
|
||||
(self.fallback)(self.errors.clone())
|
||||
.hydrate::<FROM_SERVER>(
|
||||
&cursor,
|
||||
&position,
|
||||
extra_attrs.clone(),
|
||||
),
|
||||
.hydrate::<FROM_SERVER>(&cursor, &position),
|
||||
),
|
||||
)
|
||||
};
|
||||
@@ -450,10 +423,6 @@ where
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -3,11 +3,7 @@ use leptos_dom::helpers::window;
|
||||
use leptos_server::{ServerAction, ServerMultiAction};
|
||||
use serde::de::DeserializeOwned;
|
||||
use server_fn::{
|
||||
client::Client,
|
||||
codec::PostUrl,
|
||||
error::{IntoAppError, ServerFnErrorErr},
|
||||
request::ClientReq,
|
||||
ServerFn,
|
||||
client::Client, codec::PostUrl, request::ClientReq, ServerFn, ServerFnError,
|
||||
};
|
||||
use tachys::{
|
||||
either::Either,
|
||||
@@ -125,10 +121,9 @@ where
|
||||
"Error converting form field into server function \
|
||||
arguments: {err:?}"
|
||||
);
|
||||
value.set(Some(Err(ServerFnErrorErr::Serialization(
|
||||
value.set(Some(Err(ServerFnError::Serialization(
|
||||
err.to_string(),
|
||||
)
|
||||
.into_app_error())));
|
||||
))));
|
||||
version.update(|n| *n += 1);
|
||||
}
|
||||
}
|
||||
@@ -192,10 +187,9 @@ where
|
||||
action.dispatch(new_input);
|
||||
}
|
||||
Err(err) => {
|
||||
action.dispatch_sync(Err(ServerFnErrorErr::Serialization(
|
||||
action.dispatch_sync(Err(ServerFnError::Serialization(
|
||||
err.to_string(),
|
||||
)
|
||||
.into_app_error()));
|
||||
)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::borrow::Cow;
|
||||
use tachys::{
|
||||
html::attribute::{any_attribute::AnyAttribute, Attribute},
|
||||
html::attribute::Attribute,
|
||||
hydration::Cursor,
|
||||
ssr::StreamBuilder,
|
||||
view::{
|
||||
add_attr::AddAnyAttr, any_view::ExtraAttrsMut, Position, PositionState,
|
||||
Render, RenderHtml, ToTemplate,
|
||||
add_attr::AddAnyAttr, Position, PositionState, Render, RenderHtml,
|
||||
ToTemplate,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -76,34 +76,26 @@ where
|
||||
impl<T: Render> Render for View<T> {
|
||||
type State = T::State;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
self.inner.build(extra_attrs)
|
||||
fn build(self) -> Self::State {
|
||||
self.inner.build()
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
self.inner.rebuild(state, extra_attrs)
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
self.inner.rebuild(state)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RenderHtml> RenderHtml for View<T> {
|
||||
type AsyncOutput = T::AsyncOutput;
|
||||
type Owned = View<T::Owned>;
|
||||
|
||||
const MIN_LENGTH: usize = <T as RenderHtml>::MIN_LENGTH;
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
self.inner.resolve(extra_attrs).await
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self.inner.resolve().await
|
||||
}
|
||||
|
||||
fn dry_resolve(&mut self, extra_attrs: ExtraAttrsMut<'_>) {
|
||||
self.inner.dry_resolve(extra_attrs);
|
||||
fn dry_resolve(&mut self) {
|
||||
self.inner.dry_resolve();
|
||||
}
|
||||
|
||||
fn to_html_with_buf(
|
||||
@@ -112,7 +104,6 @@ impl<T: RenderHtml> RenderHtml for View<T> {
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
#[cfg(debug_assertions)]
|
||||
let vm = self.view_marker.to_owned();
|
||||
@@ -121,13 +112,8 @@ impl<T: RenderHtml> RenderHtml for View<T> {
|
||||
buf.push_str(&format!("<!--hot-reload|{vm}|open-->"));
|
||||
}
|
||||
|
||||
self.inner.to_html_with_buf(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
self.inner
|
||||
.to_html_with_buf(buf, position, escape, mark_branches);
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
if let Some(vm) = vm.as_ref() {
|
||||
@@ -141,7 +127,6 @@ impl<T: RenderHtml> RenderHtml for View<T> {
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -157,7 +142,6 @@ impl<T: RenderHtml> RenderHtml for View<T> {
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
@@ -170,18 +154,8 @@ impl<T: RenderHtml> RenderHtml for View<T> {
|
||||
self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
self.inner
|
||||
.hydrate::<FROM_SERVER>(cursor, position, extra_attrs)
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
View {
|
||||
inner: self.inner.into_owned(),
|
||||
#[cfg(debug_assertions)]
|
||||
view_marker: self.view_marker,
|
||||
}
|
||||
self.inner.hydrate::<FROM_SERVER>(cursor, position)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -172,7 +172,7 @@ pub mod prelude {
|
||||
actions::*, computed::*, effect::*, graph::untrack, owner::*,
|
||||
signal::*, wrappers::read::*,
|
||||
};
|
||||
pub use server_fn::{self, error::ServerFnError};
|
||||
pub use server_fn::{self, ServerFnError};
|
||||
pub use tachys::{
|
||||
reactive_graph::{bind::BindAttribute, node_ref::*, Suspend},
|
||||
view::{
|
||||
|
||||
@@ -71,7 +71,6 @@ where
|
||||
view.hydrate::<true>(
|
||||
&Cursor::new(parent.unchecked_into()),
|
||||
&PositionState::default(),
|
||||
None,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -125,7 +124,7 @@ where
|
||||
let owner = Owner::new();
|
||||
let mountable = owner.with(move || {
|
||||
let view = f().into_view();
|
||||
let mut mountable = view.build(None);
|
||||
let mut mountable = view.build();
|
||||
mountable.mount(&parent, None);
|
||||
mountable
|
||||
});
|
||||
@@ -153,7 +152,7 @@ where
|
||||
let owner = Owner::new();
|
||||
let mountable = owner.with(move || {
|
||||
let view = f();
|
||||
let mut mountable = view.build(None);
|
||||
let mut mountable = view.build();
|
||||
mountable.mount(parent, None);
|
||||
mountable
|
||||
});
|
||||
|
||||
@@ -19,13 +19,12 @@ use slotmap::{DefaultKey, SlotMap};
|
||||
use std::sync::Arc;
|
||||
use tachys::{
|
||||
either::Either,
|
||||
html::attribute::{any_attribute::AnyAttribute, Attribute},
|
||||
html::attribute::Attribute,
|
||||
hydration::Cursor,
|
||||
reactive_graph::{OwnedView, OwnedViewState},
|
||||
ssr::StreamBuilder,
|
||||
view::{
|
||||
add_attr::AddAnyAttr,
|
||||
any_view::ExtraAttrsMut,
|
||||
either::{EitherKeepAlive, EitherKeepAliveState},
|
||||
Mountable, Position, PositionState, Render, RenderHtml,
|
||||
},
|
||||
@@ -163,7 +162,7 @@ where
|
||||
OwnedViewState<EitherKeepAliveState<Chil::State, Fal::State>>,
|
||||
>;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(self) -> Self::State {
|
||||
let mut children = Some(self.children);
|
||||
let mut fallback = Some(self.fallback);
|
||||
let none_pending = self.none_pending;
|
||||
@@ -188,20 +187,16 @@ where
|
||||
);
|
||||
|
||||
if let Some(mut state) = prev {
|
||||
this.rebuild(&mut state, extra_attrs.clone());
|
||||
this.rebuild(&mut state);
|
||||
state
|
||||
} else {
|
||||
this.build(extra_attrs.clone())
|
||||
this.build()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
let new = self.build(extra_attrs);
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
let new = self.build();
|
||||
let mut old = std::mem::replace(state, new);
|
||||
old.insert_before_this(state);
|
||||
old.unmount();
|
||||
@@ -252,16 +247,12 @@ where
|
||||
// i.e., if this is the child of another Suspense during SSR, don't wait for it: it will handle
|
||||
// itself
|
||||
type AsyncOutput = Self;
|
||||
type Owned = Self;
|
||||
|
||||
const MIN_LENGTH: usize = Chil::MIN_LENGTH;
|
||||
|
||||
fn dry_resolve(&mut self, _extra_attrs: ExtraAttrsMut<'_>) {}
|
||||
fn dry_resolve(&mut self) {}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
_extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self
|
||||
}
|
||||
|
||||
@@ -271,15 +262,9 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
self.fallback.to_html_with_buf(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
self.fallback
|
||||
.to_html_with_buf(buf, position, escape, mark_branches);
|
||||
}
|
||||
|
||||
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
|
||||
@@ -288,7 +273,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
mut extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -313,8 +297,7 @@ where
|
||||
provide_context(LocalResourceNotifier::from(local_tx));
|
||||
|
||||
// walk over the tree of children once to make sure that all resource loads are registered
|
||||
self.children
|
||||
.dry_resolve(ExtraAttrsMut::from_owned(&mut extra_attrs));
|
||||
self.children.dry_resolve();
|
||||
|
||||
// check the set of tasks to see if it is empty, now or later
|
||||
let eff = reactive_graph::effect::Effect::new_isomorphic({
|
||||
@@ -330,8 +313,7 @@ where
|
||||
}
|
||||
});
|
||||
|
||||
let mut fut = Box::pin(ScopedFuture::new(ErrorHookFuture::new({
|
||||
let mut extra_attrs = extra_attrs.clone();
|
||||
let mut fut = Box::pin(ScopedFuture::new(ErrorHookFuture::new(
|
||||
async move {
|
||||
// race the local resource notifier against the set of tasks
|
||||
//
|
||||
@@ -358,7 +340,7 @@ where
|
||||
// but in situations like a <For each=|| some_resource.snapshot()/> we actually
|
||||
// want to be able to 1) synchronously read a resource's value, but still 2) wait
|
||||
// for it to load before we render everything
|
||||
let mut children = Box::pin(self.children.resolve(ExtraAttrsMut::from_owned(&mut extra_attrs)).fuse());
|
||||
let mut children = Box::pin(self.children.resolve().fuse());
|
||||
|
||||
// we continue racing the children against the "do we have any local
|
||||
// resources?" Future
|
||||
@@ -377,8 +359,8 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})));
|
||||
},
|
||||
)));
|
||||
match fut.as_mut().now_or_never() {
|
||||
Some(Some(resolved)) => {
|
||||
Either::<Fal, _>::Right(resolved)
|
||||
@@ -387,7 +369,6 @@ where
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
}
|
||||
Some(None) => {
|
||||
@@ -397,7 +378,6 @@ where
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
@@ -411,14 +391,12 @@ where
|
||||
self.fallback,
|
||||
&mut fallback_position,
|
||||
mark_branches,
|
||||
extra_attrs.clone(),
|
||||
);
|
||||
buf.push_async_out_of_order_with_nonce(
|
||||
fut,
|
||||
position,
|
||||
mark_branches,
|
||||
nonce_or_not(),
|
||||
extra_attrs,
|
||||
);
|
||||
} else {
|
||||
buf.push_async({
|
||||
@@ -434,7 +412,6 @@ where
|
||||
&mut position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
builder.finish().take_chunks()
|
||||
}
|
||||
@@ -449,7 +426,6 @@ where
|
||||
self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let cursor = cursor.to_owned();
|
||||
let position = position.to_owned();
|
||||
@@ -478,21 +454,13 @@ where
|
||||
);
|
||||
|
||||
if let Some(mut state) = prev {
|
||||
this.rebuild(&mut state, extra_attrs.clone());
|
||||
this.rebuild(&mut state);
|
||||
state
|
||||
} else {
|
||||
this.hydrate::<FROM_SERVER>(
|
||||
&cursor,
|
||||
&position,
|
||||
extra_attrs.clone(),
|
||||
)
|
||||
this.hydrate::<FROM_SERVER>(&cursor, &position)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper that prevents [`Suspense`] from waiting for any resource reads that happen inside
|
||||
@@ -512,16 +480,12 @@ where
|
||||
{
|
||||
type State = T::State;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
(self.0)().build(extra_attrs)
|
||||
fn build(self) -> Self::State {
|
||||
(self.0)().build()
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
(self.0)().rebuild(state, extra_attrs);
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
(self.0)().rebuild(state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -549,16 +513,12 @@ where
|
||||
T: RenderHtml + 'static,
|
||||
{
|
||||
type AsyncOutput = Self;
|
||||
type Owned = Self;
|
||||
|
||||
const MIN_LENGTH: usize = T::MIN_LENGTH;
|
||||
|
||||
fn dry_resolve(&mut self, _extra_attrs: ExtraAttrsMut<'_>) {}
|
||||
fn dry_resolve(&mut self) {}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
_extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self
|
||||
}
|
||||
|
||||
@@ -568,15 +528,8 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
(self.0)().to_html_with_buf(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
(self.0)().to_html_with_buf(buf, position, escape, mark_branches);
|
||||
}
|
||||
|
||||
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
|
||||
@@ -585,7 +538,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -594,7 +546,6 @@ where
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -602,12 +553,7 @@ where
|
||||
self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
(self.0)().hydrate::<FROM_SERVER>(cursor, position, extra_attrs)
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
self
|
||||
(self.0)().hydrate::<FROM_SERVER>(cursor, position)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,9 +12,8 @@ use typed_builder::TypedBuilder;
|
||||
|
||||
/// A Struct to allow us to parse LeptosOptions from the file. Not really needed, most interactions should
|
||||
/// occur with LeptosOptions
|
||||
#[derive(Clone, Debug, serde::Deserialize)]
|
||||
#[derive(Clone, Debug, serde::Deserialize, Default)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
#[non_exhaustive]
|
||||
pub struct ConfFile {
|
||||
pub leptos_options: LeptosOptions,
|
||||
}
|
||||
@@ -25,14 +24,9 @@ pub struct ConfFile {
|
||||
/// It shares keys with cargo-leptos, to allow for easy interoperability
|
||||
#[derive(TypedBuilder, Debug, Clone, serde::Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
#[non_exhaustive]
|
||||
pub struct LeptosOptions {
|
||||
/// The name of the WASM and JS files generated by wasm-bindgen.
|
||||
///
|
||||
/// This should match the name that will be output when building your application.
|
||||
///
|
||||
/// You can easily set this using `env!("CARGO_CRATE_NAME")`.
|
||||
#[builder(setter(into))]
|
||||
/// The name of the WASM and JS files generated by wasm-bindgen. Defaults to the crate name with underscores instead of dashes
|
||||
#[builder(setter(into), default=default_output_name())]
|
||||
pub output_name: Arc<str>,
|
||||
/// The path of the all the files generated by cargo-leptos. This defaults to '.' for convenience when integrating with other
|
||||
/// tools.
|
||||
@@ -84,40 +78,6 @@ pub struct LeptosOptions {
|
||||
#[builder(default = default_hash_files())]
|
||||
#[serde(default = "default_hash_files")]
|
||||
pub hash_files: bool,
|
||||
/// The default prefix to use for server functions when generating API routes. Can be
|
||||
/// overridden for individual functions using `#[server(prefix = "...")]` as usual.
|
||||
///
|
||||
/// This is useful to override the default prefix (`/api`) for all server functions without
|
||||
/// needing to manually specify via `#[server(prefix = "...")]` on every server function.
|
||||
#[builder(default, setter(strip_option))]
|
||||
#[serde(default)]
|
||||
pub server_fn_prefix: Option<String>,
|
||||
/// Whether to disable appending the server functions' hashes to the end of their API names.
|
||||
///
|
||||
/// This is useful when an app's client side needs a stable server API. For example, shipping
|
||||
/// the CSR WASM binary in a Tauri app. Tauri app releases are dependent on each platform's
|
||||
/// distribution method (e.g., the Apple App Store or the Google Play Store), which typically
|
||||
/// are much slower than the frequency at which a website can be updated. In addition, it's
|
||||
/// common for users to not have the latest app version installed. In these cases, the CSR WASM
|
||||
/// app would need to be able to continue calling the backend server function API, so the API
|
||||
/// path needs to be consistent and not have a hash appended.
|
||||
///
|
||||
/// Note that the hash suffixes is intended as a way to ensure duplicate API routes are created.
|
||||
/// Without the hash, server functions will need to have unique names to avoid creating
|
||||
/// duplicate routes. Axum will throw an error if a duplicate route is added to the router, but
|
||||
/// Actix will not.
|
||||
#[builder(default)]
|
||||
#[serde(default)]
|
||||
pub disable_server_fn_hash: bool,
|
||||
/// Include the module path of the server function in the API route. This is an alternative
|
||||
/// strategy to prevent duplicate server function API routes (the default strategy is to add
|
||||
/// a hash to the end of the route). Each element of the module path will be separated by a `/`.
|
||||
/// For example, a server function with a fully qualified name of `parent::child::server_fn`
|
||||
/// would have an API route of `/api/parent/child/server_fn` (possibly with a
|
||||
/// different prefix and a hash suffix depending on the values of the other server fn configs).
|
||||
#[builder(default)]
|
||||
#[serde(default)]
|
||||
pub server_fn_mod_path: bool,
|
||||
}
|
||||
|
||||
impl LeptosOptions {
|
||||
@@ -160,14 +120,20 @@ impl LeptosOptions {
|
||||
hash_file: env_w_default("LEPTOS_HASH_FILE_NAME", "hash.txt")?
|
||||
.into(),
|
||||
hash_files: env_w_default("LEPTOS_HASH_FILES", "false")?.parse()?,
|
||||
server_fn_prefix: env_wo_default("SERVER_FN_PREFIX")?,
|
||||
disable_server_fn_hash: env_wo_default("DISABLE_SERVER_FN_HASH")?
|
||||
.is_some(),
|
||||
server_fn_mod_path: env_wo_default("SERVER_FN_MOD_PATH")?.is_some(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for LeptosOptions {
|
||||
fn default() -> Self {
|
||||
LeptosOptions::builder().build()
|
||||
}
|
||||
}
|
||||
|
||||
fn default_output_name() -> Arc<str> {
|
||||
env!("CARGO_CRATE_NAME").replace('-', "_").into()
|
||||
}
|
||||
|
||||
fn default_site_root() -> Arc<str> {
|
||||
".".into()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_macro"
|
||||
version = "0.8.0-alpha"
|
||||
version = { workspace = true }
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
@@ -34,7 +34,7 @@ log = "0.4.22"
|
||||
typed-builder = "0.20.0"
|
||||
trybuild = "1.0"
|
||||
leptos = { path = "../leptos" }
|
||||
leptos_router = { path = "../router", features= ["ssr"] }
|
||||
leptos_router = { path = "../router", features = ["ssr"] }
|
||||
server_fn = { path = "../server_fn", features = ["cbor"] }
|
||||
insta = "1.41"
|
||||
serde = "1.0"
|
||||
|
||||
@@ -144,8 +144,6 @@ impl ToTokens for Model {
|
||||
let (impl_generics, generics, where_clause) =
|
||||
body.sig.generics.split_for_impl();
|
||||
|
||||
let lifetimes = body.sig.generics.lifetimes();
|
||||
|
||||
let props_name = format_ident!("{name}Props");
|
||||
let props_builder_name = format_ident!("{name}PropsBuilder");
|
||||
let props_serialized_name = format_ident!("{name}PropsSerialized");
|
||||
@@ -570,7 +568,7 @@ impl ToTokens for Model {
|
||||
#tracing_instrument_attr
|
||||
#vis fn #name #impl_generics (
|
||||
#props_arg
|
||||
) #ret #(+ #lifetimes)*
|
||||
) #ret
|
||||
#where_clause
|
||||
{
|
||||
#body
|
||||
|
||||
@@ -677,17 +677,21 @@ fn component_macro(
|
||||
#[allow(non_snake_case, dead_code, clippy::too_many_arguments, clippy::needless_lifetimes)]
|
||||
#unexpanded
|
||||
}
|
||||
} else if let Ok(mut dummy) = dummy {
|
||||
dummy.sig.ident = unmodified_fn_name_from_fn_name(&dummy.sig.ident);
|
||||
quote! {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_snake_case, dead_code, clippy::too_many_arguments, clippy::needless_lifetimes)]
|
||||
#dummy
|
||||
}
|
||||
} else {
|
||||
quote! {}
|
||||
}
|
||||
.into()
|
||||
match dummy {
|
||||
Ok(mut dummy) => {
|
||||
dummy.sig.ident = unmodified_fn_name_from_fn_name(&dummy.sig.ident);
|
||||
quote! {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_snake_case, dead_code, clippy::too_many_arguments, clippy::needless_lifetimes)]
|
||||
#dummy
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
proc_macro_error2::abort!(e.span(), e);
|
||||
}
|
||||
}
|
||||
}.into()
|
||||
}
|
||||
|
||||
/// Annotates a struct so that it can be used with your Component as a `slot`.
|
||||
@@ -919,7 +923,7 @@ pub fn server(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
|
||||
args.into(),
|
||||
s.into(),
|
||||
Some(syn::parse_quote!(::leptos::server_fn)),
|
||||
option_env!("SERVER_FN_PREFIX").unwrap_or("/api"),
|
||||
"/api",
|
||||
None,
|
||||
None,
|
||||
) {
|
||||
|
||||
@@ -154,7 +154,12 @@ fn is_inert_element(orig_node: &Node<impl CustomNode>) -> bool {
|
||||
Some(value) => {
|
||||
matches!(&value.value, KVAttributeValue::Expr(expr) if {
|
||||
if let Expr::Lit(lit) = expr {
|
||||
matches!(&lit.lit, Lit::Str(_))
|
||||
let key = attr.key.to_string();
|
||||
if key.starts_with("style:") || key.starts_with("prop:") || key.starts_with("on:") || key.starts_with("use:") || key.starts_with("bind") {
|
||||
false
|
||||
} else {
|
||||
matches!(&lit.lit, Lit::Str(_))
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
@@ -1174,8 +1179,7 @@ pub(crate) fn event_type_and_handler(
|
||||
) -> (TokenStream, TokenStream, TokenStream) {
|
||||
let handler = attribute_value(node, false);
|
||||
|
||||
let (event_type, is_custom, is_force_undelegated, is_targeted) =
|
||||
parse_event_name(name);
|
||||
let (event_type, is_custom, options) = parse_event_name(name);
|
||||
|
||||
let event_name_ident = match &node.key {
|
||||
NodeName::Punctuated(parts) => {
|
||||
@@ -1193,11 +1197,17 @@ pub(crate) fn event_type_and_handler(
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let capture_ident = match &node.key {
|
||||
NodeName::Punctuated(parts) => {
|
||||
parts.iter().find(|part| part.to_string() == "capture")
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let on = match &node.key {
|
||||
NodeName::Punctuated(parts) => &parts[0],
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let on = if is_targeted {
|
||||
let on = if options.targeted {
|
||||
Ident::new("on_target", on.span()).to_token_stream()
|
||||
} else {
|
||||
on.to_token_stream()
|
||||
@@ -1210,15 +1220,29 @@ pub(crate) fn event_type_and_handler(
|
||||
event_type
|
||||
};
|
||||
|
||||
let event_type = if is_force_undelegated {
|
||||
let event_type = quote! {
|
||||
::leptos::tachys::html::event::#event_type
|
||||
};
|
||||
let event_type = if options.captured {
|
||||
let capture = if let Some(capture) = capture_ident {
|
||||
quote! { #capture }
|
||||
} else {
|
||||
quote! { capture }
|
||||
};
|
||||
quote! { ::leptos::tachys::html::event::#capture(#event_type) }
|
||||
} else {
|
||||
event_type
|
||||
};
|
||||
|
||||
let event_type = if options.undelegated {
|
||||
let undelegated = if let Some(undelegated) = undelegated_ident {
|
||||
quote! { #undelegated }
|
||||
} else {
|
||||
quote! { undelegated }
|
||||
};
|
||||
quote! { ::leptos::tachys::html::event::#undelegated(::leptos::tachys::html::event::#event_type) }
|
||||
quote! { ::leptos::tachys::html::event::#undelegated(#event_type) }
|
||||
} else {
|
||||
quote! { ::leptos::tachys::html::event::#event_type }
|
||||
event_type
|
||||
};
|
||||
|
||||
(on, event_type, handler)
|
||||
@@ -1424,13 +1448,22 @@ fn is_ambiguous_element(tag: &str) -> bool {
|
||||
tag == "a" || tag == "script" || tag == "title"
|
||||
}
|
||||
|
||||
fn parse_event(event_name: &str) -> (String, bool, bool) {
|
||||
let is_undelegated = event_name.contains(":undelegated");
|
||||
let is_targeted = event_name.contains(":target");
|
||||
fn parse_event(event_name: &str) -> (String, EventNameOptions) {
|
||||
let undelegated = event_name.contains(":undelegated");
|
||||
let targeted = event_name.contains(":target");
|
||||
let captured = event_name.contains(":capture");
|
||||
let event_name = event_name
|
||||
.replace(":undelegated", "")
|
||||
.replace(":target", "");
|
||||
(event_name, is_undelegated, is_targeted)
|
||||
.replace(":target", "")
|
||||
.replace(":capture", "");
|
||||
(
|
||||
event_name,
|
||||
EventNameOptions {
|
||||
undelegated,
|
||||
targeted,
|
||||
captured,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Escapes Rust keywords that are also HTML attribute names
|
||||
@@ -1622,8 +1655,17 @@ const TYPED_EVENTS: [&str; 126] = [
|
||||
|
||||
const CUSTOM_EVENT: &str = "Custom";
|
||||
|
||||
pub(crate) fn parse_event_name(name: &str) -> (TokenStream, bool, bool, bool) {
|
||||
let (name, is_force_undelegated, is_targeted) = parse_event(name);
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct EventNameOptions {
|
||||
undelegated: bool,
|
||||
targeted: bool,
|
||||
captured: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn parse_event_name(
|
||||
name: &str,
|
||||
) -> (TokenStream, bool, EventNameOptions) {
|
||||
let (name, options) = parse_event(name);
|
||||
|
||||
let (event_type, is_custom) = TYPED_EVENTS
|
||||
.binary_search(&name.as_str())
|
||||
@@ -1639,7 +1681,7 @@ pub(crate) fn parse_event_name(name: &str) -> (TokenStream, bool, bool, bool) {
|
||||
} else {
|
||||
event_type
|
||||
};
|
||||
(event_type, is_custom, is_force_undelegated, is_targeted)
|
||||
(event_type, is_custom, options)
|
||||
}
|
||||
|
||||
fn convert_to_snake_case(name: String) -> String {
|
||||
|
||||
@@ -104,3 +104,18 @@ fn component_nostrip() {
|
||||
/>
|
||||
};
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn WithLifetime<'a>(data: &'a str) -> impl IntoView {
|
||||
_ = data;
|
||||
"static lifetime"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_static_lifetime() {
|
||||
#[allow(unused)]
|
||||
fn can_return_impl_intoview_from_body() -> impl IntoView {
|
||||
let val = String::from("non_static_lifetime");
|
||||
WithLifetime(WithLifetimeProps::builder().data(&val).build())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use reactive_graph::{
|
||||
owner::use_context,
|
||||
traits::DefinedAt,
|
||||
};
|
||||
use server_fn::{error::FromServerFnError, ServerFn};
|
||||
use server_fn::{error::ServerFnErrorSerde, ServerFn, ServerFnError};
|
||||
use std::{ops::Deref, panic::Location, sync::Arc};
|
||||
|
||||
/// An error that can be caused by a server action.
|
||||
@@ -42,7 +42,7 @@ where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
inner: ArcAction<S, Result<S::Output, S::Error>>,
|
||||
inner: ArcAction<S, Result<S::Output, ServerFnError<S::Error>>>,
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
@@ -52,14 +52,13 @@ where
|
||||
S: ServerFn + Clone + Send + Sync + 'static,
|
||||
S::Output: Send + Sync + 'static,
|
||||
S::Error: Send + Sync + 'static,
|
||||
S::Error: FromServerFnError,
|
||||
{
|
||||
/// Creates a new [`ArcAction`] that will call the server function `S` when dispatched.
|
||||
#[track_caller]
|
||||
pub fn new() -> Self {
|
||||
let err = use_context::<ServerActionError>().and_then(|error| {
|
||||
(error.path() == S::PATH)
|
||||
.then(|| S::Error::de(error.err()))
|
||||
.then(|| ServerFnError::<S::Error>::de(error.err()))
|
||||
.map(Err)
|
||||
});
|
||||
Self {
|
||||
@@ -77,7 +76,7 @@ where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
type Target = ArcAction<S, Result<S::Output, S::Error>>;
|
||||
type Target = ArcAction<S, Result<S::Output, ServerFnError<S::Error>>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
@@ -132,7 +131,7 @@ where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
inner: Action<S, Result<S::Output, S::Error>>,
|
||||
inner: Action<S, Result<S::Output, ServerFnError<S::Error>>>,
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
@@ -147,7 +146,7 @@ where
|
||||
pub fn new() -> Self {
|
||||
let err = use_context::<ServerActionError>().and_then(|error| {
|
||||
(error.path() == S::PATH)
|
||||
.then(|| S::Error::de(error.err()))
|
||||
.then(|| ServerFnError::<S::Error>::de(error.err()))
|
||||
.map(Err)
|
||||
});
|
||||
Self {
|
||||
@@ -183,14 +182,15 @@ where
|
||||
S::Output: Send + Sync + 'static,
|
||||
S::Error: Send + Sync + 'static,
|
||||
{
|
||||
type Target = Action<S, Result<S::Output, S::Error>>;
|
||||
type Target = Action<S, Result<S::Output, ServerFnError<S::Error>>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<ServerAction<S>> for Action<S, Result<S::Output, S::Error>>
|
||||
impl<S> From<ServerAction<S>>
|
||||
for Action<S, Result<S::Output, ServerFnError<S::Error>>>
|
||||
where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
|
||||
@@ -79,13 +79,12 @@ mod view_implementations {
|
||||
use reactive_graph::traits::Read;
|
||||
use std::future::Future;
|
||||
use tachys::{
|
||||
html::attribute::{any_attribute::AnyAttribute, Attribute},
|
||||
html::attribute::Attribute,
|
||||
hydration::Cursor,
|
||||
reactive_graph::{RenderEffectState, Suspend, SuspendState},
|
||||
ssr::StreamBuilder,
|
||||
view::{
|
||||
add_attr::AddAnyAttr, any_view::ExtraAttrsMut, Position,
|
||||
PositionState, Render, RenderHtml,
|
||||
add_attr::AddAnyAttr, Position, PositionState, Render, RenderHtml,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -96,17 +95,12 @@ mod view_implementations {
|
||||
{
|
||||
type State = RenderEffectState<SuspendState<T>>;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
(move || Suspend::new(async move { self.await })).build(extra_attrs)
|
||||
fn build(self) -> Self::State {
|
||||
(move || Suspend::new(async move { self.await })).build()
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
(move || Suspend::new(async move { self.await }))
|
||||
.rebuild(state, extra_attrs)
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
(move || Suspend::new(async move { self.await })).rebuild(state)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,20 +135,15 @@ mod view_implementations {
|
||||
Ser: Send + 'static,
|
||||
{
|
||||
type AsyncOutput = Option<T>;
|
||||
type Owned = Self;
|
||||
|
||||
const MIN_LENGTH: usize = 0;
|
||||
|
||||
fn dry_resolve(&mut self, _extra_attrs: ExtraAttrsMut<'_>) {
|
||||
fn dry_resolve(&mut self) {
|
||||
self.read();
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
self,
|
||||
extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> impl Future<Output = Self::AsyncOutput> + Send {
|
||||
(move || Suspend::new(async move { self.await }))
|
||||
.resolve(extra_attrs)
|
||||
fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send {
|
||||
(move || Suspend::new(async move { self.await })).resolve()
|
||||
}
|
||||
|
||||
fn to_html_with_buf(
|
||||
@@ -163,14 +152,12 @@ mod view_implementations {
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
(move || Suspend::new(async move { self.await })).to_html_with_buf(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -180,7 +167,6 @@ mod view_implementations {
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -190,7 +176,6 @@ mod view_implementations {
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -198,14 +183,9 @@ mod view_implementations {
|
||||
self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
(move || Suspend::new(async move { self.await }))
|
||||
.hydrate::<FROM_SERVER>(cursor, position, extra_attrs)
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
self
|
||||
.hydrate::<FROM_SERVER>(cursor, position)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use reactive_graph::{
|
||||
actions::{ArcMultiAction, MultiAction},
|
||||
traits::DefinedAt,
|
||||
};
|
||||
use server_fn::ServerFn;
|
||||
use server_fn::{ServerFn, ServerFnError};
|
||||
use std::{ops::Deref, panic::Location};
|
||||
|
||||
/// An [`ArcMultiAction`] that can be used to call a server function.
|
||||
@@ -11,7 +11,7 @@ where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
inner: ArcMultiAction<S, Result<S::Output, S::Error>>,
|
||||
inner: ArcMultiAction<S, Result<S::Output, ServerFnError<S::Error>>>,
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
@@ -40,7 +40,7 @@ where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
type Target = ArcMultiAction<S, Result<S::Output, S::Error>>;
|
||||
type Target = ArcMultiAction<S, Result<S::Output, ServerFnError<S::Error>>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
@@ -95,13 +95,13 @@ where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
inner: MultiAction<S, Result<S::Output, S::Error>>,
|
||||
inner: MultiAction<S, Result<S::Output, ServerFnError<S::Error>>>,
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
impl<S> From<ServerMultiAction<S>>
|
||||
for MultiAction<S, Result<S::Output, S::Error>>
|
||||
for MultiAction<S, Result<S::Output, ServerFnError<S::Error>>>
|
||||
where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
@@ -152,7 +152,7 @@ where
|
||||
S::Output: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
type Target = MultiAction<S, Result<S::Output, S::Error>>;
|
||||
type Target = MultiAction<S, Result<S::Output, ServerFnError<S::Error>>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_meta"
|
||||
version = "0.8.0-alpha"
|
||||
version = "0.7.7"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use crate::ServerMetaContext;
|
||||
use leptos::{
|
||||
attr::{
|
||||
any_attribute::{AnyAttribute, AnyAttributeState},
|
||||
NextAttribute,
|
||||
},
|
||||
attr::NextAttribute,
|
||||
component, html,
|
||||
reactive::owner::use_context,
|
||||
tachys::{
|
||||
@@ -11,8 +8,8 @@ use leptos::{
|
||||
html::attribute::Attribute,
|
||||
hydration::Cursor,
|
||||
view::{
|
||||
add_attr::AddAnyAttr, any_view::ExtraAttrsMut, Mountable, Position,
|
||||
PositionState, Render, RenderHtml,
|
||||
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
|
||||
RenderHtml,
|
||||
},
|
||||
},
|
||||
IntoView,
|
||||
@@ -61,7 +58,6 @@ where
|
||||
At: Attribute,
|
||||
{
|
||||
attributes: At::State,
|
||||
extra_attrs: Option<Vec<AnyAttributeState>>,
|
||||
}
|
||||
|
||||
impl<At> Render for BodyView<At>
|
||||
@@ -70,27 +66,15 @@ where
|
||||
{
|
||||
type State = BodyViewState<At>;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(self) -> Self::State {
|
||||
let el = document().body().expect("there to be a <body> element");
|
||||
let attributes = self.attributes.build(&el);
|
||||
let extra_attrs = extra_attrs.map(|attrs| attrs.build(&el));
|
||||
BodyViewState {
|
||||
attributes,
|
||||
extra_attrs,
|
||||
}
|
||||
|
||||
BodyViewState { attributes }
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
self.attributes.rebuild(&mut state.attributes);
|
||||
if let (Some(extra_attrs), Some(extra_attr_states)) =
|
||||
(extra_attrs, &mut state.extra_attrs)
|
||||
{
|
||||
extra_attrs.rebuild(extra_attr_states);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,24 +103,17 @@ where
|
||||
At: Attribute,
|
||||
{
|
||||
type AsyncOutput = BodyView<At::AsyncOutput>;
|
||||
type Owned = BodyView<At::CloneableOwned>;
|
||||
|
||||
const MIN_LENGTH: usize = At::MIN_LENGTH;
|
||||
|
||||
fn dry_resolve(&mut self, mut extra_attrs: ExtraAttrsMut<'_>) {
|
||||
fn dry_resolve(&mut self) {
|
||||
self.attributes.dry_resolve();
|
||||
extra_attrs.iter_mut().for_each(Attribute::dry_resolve);
|
||||
}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
let (attributes, _) = futures::join!(
|
||||
self.attributes.resolve(),
|
||||
ExtraAttrsMut::resolve(extra_attrs)
|
||||
);
|
||||
BodyView { attributes }
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
BodyView {
|
||||
attributes: self.attributes.resolve().await,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_html_with_buf(
|
||||
@@ -145,15 +122,10 @@ where
|
||||
_position: &mut Position,
|
||||
_escape: bool,
|
||||
_mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
if let Some(meta) = use_context::<ServerMetaContext>() {
|
||||
let mut buf = String::new();
|
||||
_ = html::attributes_to_html(
|
||||
self.attributes,
|
||||
extra_attrs,
|
||||
&mut buf,
|
||||
);
|
||||
_ = html::attributes_to_html(self.attributes, &mut buf);
|
||||
if !buf.is_empty() {
|
||||
_ = meta.body.send(buf);
|
||||
}
|
||||
@@ -164,23 +136,11 @@ where
|
||||
self,
|
||||
_cursor: &Cursor,
|
||||
_position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let el = document().body().expect("there to be a <body> element");
|
||||
let attributes = self.attributes.hydrate::<FROM_SERVER>(&el);
|
||||
let extra_attrs =
|
||||
extra_attrs.map(|attrs| attrs.hydrate::<FROM_SERVER>(&el));
|
||||
|
||||
BodyViewState {
|
||||
attributes,
|
||||
extra_attrs,
|
||||
}
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
BodyView {
|
||||
attributes: self.attributes.into_cloneable_owned(),
|
||||
}
|
||||
BodyViewState { attributes }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use crate::ServerMetaContext;
|
||||
use leptos::{
|
||||
attr::{
|
||||
any_attribute::{AnyAttribute, AnyAttributeState},
|
||||
NextAttribute,
|
||||
},
|
||||
attr::NextAttribute,
|
||||
component, html,
|
||||
reactive::owner::use_context,
|
||||
tachys::{
|
||||
@@ -11,8 +8,8 @@ use leptos::{
|
||||
html::attribute::Attribute,
|
||||
hydration::Cursor,
|
||||
view::{
|
||||
add_attr::AddAnyAttr, any_view::ExtraAttrsMut, Mountable, Position,
|
||||
PositionState, Render, RenderHtml,
|
||||
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
|
||||
RenderHtml,
|
||||
},
|
||||
},
|
||||
IntoView,
|
||||
@@ -58,7 +55,6 @@ where
|
||||
At: Attribute,
|
||||
{
|
||||
attributes: At::State,
|
||||
extra_attrs: Option<Vec<AnyAttributeState>>,
|
||||
}
|
||||
|
||||
impl<At> Render for HtmlView<At>
|
||||
@@ -67,33 +63,18 @@ where
|
||||
{
|
||||
type State = HtmlViewState<At>;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(self) -> Self::State {
|
||||
let el = document()
|
||||
.document_element()
|
||||
.expect("there to be a <html> element");
|
||||
|
||||
let attributes = self.attributes.build(&el);
|
||||
let extra_attrs = extra_attrs.map(|attrs| {
|
||||
attrs.into_iter().map(|attr| attr.build(&el)).collect()
|
||||
});
|
||||
|
||||
HtmlViewState {
|
||||
attributes,
|
||||
extra_attrs,
|
||||
}
|
||||
HtmlViewState { attributes }
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
self.attributes.rebuild(&mut state.attributes);
|
||||
if let (Some(extra_attrs), Some(extra_attr_states)) =
|
||||
(extra_attrs, &mut state.extra_attrs)
|
||||
{
|
||||
extra_attrs.rebuild(extra_attr_states);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,24 +103,17 @@ where
|
||||
At: Attribute,
|
||||
{
|
||||
type AsyncOutput = HtmlView<At::AsyncOutput>;
|
||||
type Owned = HtmlView<At::CloneableOwned>;
|
||||
|
||||
const MIN_LENGTH: usize = At::MIN_LENGTH;
|
||||
|
||||
fn dry_resolve(&mut self, mut extra_attrs: ExtraAttrsMut<'_>) {
|
||||
fn dry_resolve(&mut self) {
|
||||
self.attributes.dry_resolve();
|
||||
extra_attrs.iter_mut().for_each(Attribute::dry_resolve);
|
||||
}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
let (attributes, _) = futures::join!(
|
||||
self.attributes.resolve(),
|
||||
ExtraAttrsMut::resolve(extra_attrs)
|
||||
);
|
||||
HtmlView { attributes }
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
HtmlView {
|
||||
attributes: self.attributes.resolve().await,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_html_with_buf(
|
||||
@@ -148,15 +122,10 @@ where
|
||||
_position: &mut Position,
|
||||
_escape: bool,
|
||||
_mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
if let Some(meta) = use_context::<ServerMetaContext>() {
|
||||
let mut buf = String::new();
|
||||
_ = html::attributes_to_html(
|
||||
self.attributes,
|
||||
extra_attrs,
|
||||
&mut buf,
|
||||
);
|
||||
_ = html::attributes_to_html(self.attributes, &mut buf);
|
||||
if !buf.is_empty() {
|
||||
_ = meta.html.send(buf);
|
||||
}
|
||||
@@ -167,30 +136,14 @@ where
|
||||
self,
|
||||
_cursor: &Cursor,
|
||||
_position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let el = document()
|
||||
.document_element()
|
||||
.expect("there to be a <html> element");
|
||||
|
||||
let attributes = self.attributes.hydrate::<FROM_SERVER>(&el);
|
||||
let extra_attrs = extra_attrs.map(|attrs| {
|
||||
attrs
|
||||
.into_iter()
|
||||
.map(|attr| attr.hydrate::<FROM_SERVER>(&el))
|
||||
.collect()
|
||||
});
|
||||
|
||||
HtmlViewState {
|
||||
attributes,
|
||||
extra_attrs,
|
||||
}
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
HtmlView {
|
||||
attributes: self.attributes.into_cloneable_owned(),
|
||||
}
|
||||
HtmlViewState { attributes }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
|
||||
use futures::{Stream, StreamExt};
|
||||
use leptos::{
|
||||
attr::{any_attribute::AnyAttribute, NextAttribute},
|
||||
attr::NextAttribute,
|
||||
component,
|
||||
logging::debug_warn,
|
||||
oco::Oco,
|
||||
@@ -57,8 +57,8 @@ use leptos::{
|
||||
},
|
||||
hydration::Cursor,
|
||||
view::{
|
||||
add_attr::AddAnyAttr, any_view::ExtraAttrsMut, Mountable, Position,
|
||||
PositionState, Render, RenderHtml,
|
||||
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
|
||||
RenderHtml,
|
||||
},
|
||||
},
|
||||
IntoView,
|
||||
@@ -334,7 +334,6 @@ where
|
||||
&mut Position::NextChild,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
);
|
||||
_ = cx.elements.send(buf); // fails only if the receiver is already dropped
|
||||
} else {
|
||||
@@ -391,17 +390,13 @@ where
|
||||
{
|
||||
type State = RegisteredMetaTagState<E, At, Ch>;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
let state = self.el.unwrap().build(extra_attrs);
|
||||
fn build(self) -> Self::State {
|
||||
let state = self.el.unwrap().build();
|
||||
RegisteredMetaTagState { state }
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
self.el.unwrap().rebuild(&mut state.state, extra_attrs);
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
self.el.unwrap().rebuild(&mut state.state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,18 +429,14 @@ where
|
||||
Ch: RenderHtml + Send,
|
||||
{
|
||||
type AsyncOutput = Self;
|
||||
type Owned = RegisteredMetaTag<E, At::CloneableOwned, Ch::Owned>;
|
||||
|
||||
const MIN_LENGTH: usize = 0;
|
||||
|
||||
fn dry_resolve(&mut self, extra_attrs: ExtraAttrsMut<'_>) {
|
||||
self.el.dry_resolve(extra_attrs)
|
||||
fn dry_resolve(&mut self) {
|
||||
self.el.dry_resolve()
|
||||
}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
_extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self // TODO?
|
||||
}
|
||||
|
||||
@@ -455,7 +446,6 @@ where
|
||||
_position: &mut Position,
|
||||
_escape: bool,
|
||||
_mark_branches: bool,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
// meta tags are rendered into the buffer stored into the context
|
||||
// the value has already been taken out, when we're on the server
|
||||
@@ -465,7 +455,6 @@ where
|
||||
self,
|
||||
_cursor: &Cursor,
|
||||
_position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let cursor = use_context::<MetaContext>()
|
||||
.expect(
|
||||
@@ -476,16 +465,9 @@ where
|
||||
let state = self.el.unwrap().hydrate::<FROM_SERVER>(
|
||||
&cursor,
|
||||
&PositionState::new(Position::NextChild),
|
||||
extra_attrs,
|
||||
);
|
||||
RegisteredMetaTagState { state }
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
RegisteredMetaTag {
|
||||
el: self.el.map(|inner| inner.into_owned()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, At, Ch> Mountable for RegisteredMetaTagState<E, At, Ch>
|
||||
@@ -538,14 +520,9 @@ struct MetaTagsView;
|
||||
impl Render for MetaTagsView {
|
||||
type State = ();
|
||||
|
||||
fn build(self, _extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {}
|
||||
fn build(self) -> Self::State {}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
_state: &mut Self::State,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
}
|
||||
fn rebuild(self, _state: &mut Self::State) {}
|
||||
}
|
||||
|
||||
impl AddAnyAttr for MetaTagsView {
|
||||
@@ -564,16 +541,12 @@ impl AddAnyAttr for MetaTagsView {
|
||||
|
||||
impl RenderHtml for MetaTagsView {
|
||||
type AsyncOutput = Self;
|
||||
type Owned = Self;
|
||||
|
||||
const MIN_LENGTH: usize = 0;
|
||||
|
||||
fn dry_resolve(&mut self, _extra_attrs: ExtraAttrsMut<'_>) {}
|
||||
fn dry_resolve(&mut self) {}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
_extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self
|
||||
}
|
||||
|
||||
@@ -583,7 +556,6 @@ impl RenderHtml for MetaTagsView {
|
||||
_position: &mut Position,
|
||||
_escape: bool,
|
||||
_mark_branches: bool,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
buf.push_str("<!--HEAD-->");
|
||||
}
|
||||
@@ -592,13 +564,8 @@ impl RenderHtml for MetaTagsView {
|
||||
self,
|
||||
_cursor: &Cursor,
|
||||
_position: &PositionState,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait OrDefaultNonce {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{use_head, MetaContext, ServerMetaContext};
|
||||
use leptos::{
|
||||
attr::{any_attribute::AnyAttribute, Attribute},
|
||||
attr::Attribute,
|
||||
component,
|
||||
oco::Oco,
|
||||
reactive::{
|
||||
@@ -11,8 +11,8 @@ use leptos::{
|
||||
dom::document,
|
||||
hydration::Cursor,
|
||||
view::{
|
||||
add_attr::AddAnyAttr, any_view::ExtraAttrsMut, Mountable, Position,
|
||||
PositionState, Render, RenderHtml,
|
||||
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
|
||||
RenderHtml,
|
||||
},
|
||||
},
|
||||
text_prop::TextProp,
|
||||
@@ -189,7 +189,7 @@ struct TitleViewState {
|
||||
impl Render for TitleView {
|
||||
type State = TitleViewState;
|
||||
|
||||
fn build(mut self, _extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(mut self) -> Self::State {
|
||||
let el = self.el();
|
||||
let meta = self.meta;
|
||||
if let Some(formatter) = self.formatter.take() {
|
||||
@@ -213,12 +213,8 @@ impl Render for TitleView {
|
||||
TitleViewState { effect }
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
*state = self.build(extra_attrs);
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
*state = self.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,16 +234,12 @@ impl AddAnyAttr for TitleView {
|
||||
|
||||
impl RenderHtml for TitleView {
|
||||
type AsyncOutput = Self;
|
||||
type Owned = Self;
|
||||
|
||||
const MIN_LENGTH: usize = 0;
|
||||
|
||||
fn dry_resolve(&mut self, _extra_attrs: ExtraAttrsMut<'_>) {}
|
||||
fn dry_resolve(&mut self) {}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
_extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self
|
||||
}
|
||||
|
||||
@@ -257,7 +249,6 @@ impl RenderHtml for TitleView {
|
||||
_position: &mut Position,
|
||||
_escape: bool,
|
||||
_mark_branches: bool,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
// meta tags are rendered into the buffer stored into the context
|
||||
// the value has already been taken out, when we're on the server
|
||||
@@ -267,7 +258,6 @@ impl RenderHtml for TitleView {
|
||||
mut self,
|
||||
_cursor: &Cursor,
|
||||
_position: &PositionState,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let el = self.el();
|
||||
let meta = self.meta;
|
||||
@@ -292,10 +282,6 @@ impl RenderHtml for TitleView {
|
||||
});
|
||||
TitleViewState { effect }
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Mountable for TitleViewState {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_graph"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -939,7 +939,8 @@ where
|
||||
#[track_caller]
|
||||
pub fn dispatch(&self, input: I) -> ActionAbortHandle {
|
||||
self.inner
|
||||
.try_with_value(|inner| inner.dispatch(input))
|
||||
.try_get_value()
|
||||
.map(|inner| inner.dispatch(input))
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
}
|
||||
}
|
||||
@@ -954,7 +955,8 @@ where
|
||||
#[track_caller]
|
||||
pub fn dispatch_local(&self, input: I) -> ActionAbortHandle {
|
||||
self.inner
|
||||
.try_with_value(|inner| inner.dispatch_local(input))
|
||||
.try_get_value()
|
||||
.map(|inner| inner.dispatch_local(input))
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_stores"
|
||||
version = "0.1.3"
|
||||
version = "0.1.7"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -10,7 +10,6 @@ use reactive_graph::{
|
||||
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
|
||||
Write,
|
||||
},
|
||||
unwrap_signal,
|
||||
};
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
@@ -44,14 +43,14 @@ where
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|inner| inner.get_trigger(path))
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|inner| inner.path().into_iter().collect::<Vec<_>>())
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn reader(&self) -> Option<Self::Reader> {
|
||||
@@ -82,6 +81,21 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> From<ArcField<T>> for Field<T, S>
|
||||
where
|
||||
T: 'static,
|
||||
S: Storage<ArcField<T>>,
|
||||
{
|
||||
#[track_caller]
|
||||
fn from(value: ArcField<T>) -> Self {
|
||||
Field {
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
inner: ArenaItem::new_with_storage(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> From<ArcStore<T>> for Field<T, S>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
|
||||
@@ -148,11 +148,8 @@ where
|
||||
{
|
||||
fn latest_keys(&self) -> Vec<K> {
|
||||
self.reader()
|
||||
.expect("trying to update keys")
|
||||
.deref()
|
||||
.into_iter()
|
||||
.map(|n| (self.key_fn)(n))
|
||||
.collect()
|
||||
.map(|r| r.deref().into_iter().map(|n| (self.key_fn)(n)).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,8 +480,7 @@ where
|
||||
|| self.inner.latest_keys(),
|
||||
)
|
||||
.flatten()
|
||||
.map(|(_, idx)| idx)
|
||||
.expect("reading from a keyed field that has not yet been created");
|
||||
.map(|(_, idx)| idx)?;
|
||||
|
||||
Some(WriteGuard::new(
|
||||
trigger.children,
|
||||
@@ -654,13 +650,15 @@ where
|
||||
self.track_field();
|
||||
|
||||
// get the current length of the field by accessing slice
|
||||
let reader = self
|
||||
.reader()
|
||||
.expect("creating iterator from unavailable store field");
|
||||
let reader = self.reader();
|
||||
|
||||
let keys = reader
|
||||
.into_iter()
|
||||
.map(|item| (self.key_fn)(item))
|
||||
.collect::<VecDeque<_>>();
|
||||
.map(|r| {
|
||||
r.into_iter()
|
||||
.map(|item| (self.key_fn)(item))
|
||||
.collect::<VecDeque<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// return the iterator
|
||||
StoreFieldKeyedIter { inner: self, keys }
|
||||
|
||||
@@ -77,11 +77,12 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{self as reactive_stores, Store};
|
||||
use crate::{self as reactive_stores, Patch as _, Store};
|
||||
use reactive_graph::{
|
||||
effect::Effect,
|
||||
traits::{Get, Read, ReadUntracked, Set, Write},
|
||||
};
|
||||
use reactive_stores_macro::Patch;
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc,
|
||||
@@ -237,4 +238,115 @@ mod tests {
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(inner_count.load(Ordering::Relaxed), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn patch() {
|
||||
use crate::OptionStoreExt;
|
||||
|
||||
#[derive(Debug, Clone, Store, Patch)]
|
||||
struct Outer {
|
||||
inner: Option<Inner>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Store, Patch)]
|
||||
struct Inner {
|
||||
first: String,
|
||||
second: String,
|
||||
}
|
||||
|
||||
let store = Store::new(Outer {
|
||||
inner: Some(Inner {
|
||||
first: "A".to_owned(),
|
||||
second: "B".to_owned(),
|
||||
}),
|
||||
});
|
||||
|
||||
_ = any_spawner::Executor::init_tokio();
|
||||
|
||||
let parent_count = Arc::new(AtomicUsize::new(0));
|
||||
let inner_first_count = Arc::new(AtomicUsize::new(0));
|
||||
let inner_second_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
Effect::new_sync({
|
||||
let parent_count = Arc::clone(&parent_count);
|
||||
move |prev: Option<()>| {
|
||||
if prev.is_none() {
|
||||
println!("parent: first run");
|
||||
} else {
|
||||
println!("parent: next run");
|
||||
}
|
||||
|
||||
println!(" value = {:?}", store.inner().get());
|
||||
parent_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
Effect::new_sync({
|
||||
let inner_first_count = Arc::clone(&inner_first_count);
|
||||
move |prev: Option<()>| {
|
||||
if prev.is_none() {
|
||||
println!("inner_first: first run");
|
||||
} else {
|
||||
println!("inner_first: next run");
|
||||
}
|
||||
|
||||
println!(
|
||||
" value = {:?}",
|
||||
store.inner().map(|inner| inner.first().get())
|
||||
);
|
||||
inner_first_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
Effect::new_sync({
|
||||
let inner_second_count = Arc::clone(&inner_second_count);
|
||||
move |prev: Option<()>| {
|
||||
if prev.is_none() {
|
||||
println!("inner_second: first run");
|
||||
} else {
|
||||
println!("inner_second: next run");
|
||||
}
|
||||
|
||||
println!(
|
||||
" value = {:?}",
|
||||
store.inner().map(|inner| inner.second().get())
|
||||
);
|
||||
inner_second_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(inner_first_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(inner_second_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
store.patch(Outer {
|
||||
inner: Some(Inner {
|
||||
first: "A".to_string(),
|
||||
second: "C".to_string(),
|
||||
}),
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(inner_first_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(inner_second_count.load(Ordering::Relaxed), 2);
|
||||
|
||||
store.patch(Outer { inner: None });
|
||||
|
||||
tick().await;
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(inner_first_count.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(inner_second_count.load(Ordering::Relaxed), 3);
|
||||
|
||||
store.patch(Outer {
|
||||
inner: Some(Inner {
|
||||
first: "A".to_string(),
|
||||
second: "B".to_string(),
|
||||
}),
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(inner_first_count.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(inner_second_count.load(Ordering::Relaxed), 4);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +114,35 @@ patch_primitives! {
|
||||
NonZeroUsize
|
||||
}
|
||||
|
||||
impl<T> PatchField for Option<T>
|
||||
where
|
||||
T: PatchField,
|
||||
{
|
||||
fn patch_field(
|
||||
&mut self,
|
||||
new: Self,
|
||||
path: &StorePath,
|
||||
notify: &mut dyn FnMut(&StorePath),
|
||||
) {
|
||||
match (self, new) {
|
||||
(None, None) => {}
|
||||
(old @ Some(_), None) => {
|
||||
old.take();
|
||||
notify(path);
|
||||
}
|
||||
(old @ None, new @ Some(_)) => {
|
||||
*old = new;
|
||||
notify(path);
|
||||
}
|
||||
(Some(old), Some(new)) => {
|
||||
let mut new_path = path.to_owned();
|
||||
new_path.push(0);
|
||||
old.patch_field(new, &new_path, notify);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PatchField for Vec<T>
|
||||
where
|
||||
T: PatchField,
|
||||
|
||||
@@ -9,8 +9,7 @@ use reactive_graph::{
|
||||
guards::{Plain, UntrackedWriteGuard, WriteGuard},
|
||||
ArcTrigger,
|
||||
},
|
||||
traits::{DefinedAt, Track, UntrackableGuard},
|
||||
unwrap_signal,
|
||||
traits::{Track, UntrackableGuard},
|
||||
};
|
||||
use std::{iter, ops::Deref, sync::Arc};
|
||||
|
||||
@@ -105,7 +104,7 @@ where
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|n| n.get_trigger(path))
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
@@ -113,7 +112,7 @@ where
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|n| n.path().into_iter().collect::<Vec<_>>())
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_stores_macro"
|
||||
version = "0.1.0"
|
||||
version = "0.1.7"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -87,15 +87,15 @@ impl Parse for SubfieldMode {
|
||||
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
|
||||
let mode: Ident = input.parse()?;
|
||||
if mode == "key" {
|
||||
let _col: Token!(:) = input.parse()?;
|
||||
let _col: Token![:] = input.parse()?;
|
||||
let ty: Type = input.parse()?;
|
||||
let _eq: Token!(=) = input.parse()?;
|
||||
let ident: ExprClosure = input.parse()?;
|
||||
Ok(SubfieldMode::Keyed(ident, ty))
|
||||
let _eq: Token![=] = input.parse()?;
|
||||
let closure: ExprClosure = input.parse()?;
|
||||
Ok(SubfieldMode::Keyed(closure, ty))
|
||||
} else if mode == "skip" {
|
||||
Ok(SubfieldMode::Skip)
|
||||
} else {
|
||||
Err(input.error("expected `key = <ident>: <Type>`"))
|
||||
Err(input.error("expected `key: <Type> = <closure>`"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_router"
|
||||
version = "0.8.0-alpha"
|
||||
version = "0.7.7"
|
||||
authors = ["Greg Johnston", "Ben Wishovich"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -10,7 +10,6 @@ use crate::{
|
||||
use any_spawner::Executor;
|
||||
use either_of::Either;
|
||||
use futures::FutureExt;
|
||||
use leptos::attr::any_attribute::AnyAttribute;
|
||||
use reactive_graph::{
|
||||
computed::{ArcMemo, ScopedFuture},
|
||||
owner::{provide_context, Owner},
|
||||
@@ -26,7 +25,7 @@ use tachys::{
|
||||
ssr::StreamBuilder,
|
||||
view::{
|
||||
add_attr::AddAnyAttr,
|
||||
any_view::{AnyView, AnyViewState, ExtraAttrsMut, IntoAny},
|
||||
any_view::{AnyView, AnyViewState, IntoAny},
|
||||
Mountable, Position, PositionState, Render, RenderHtml,
|
||||
},
|
||||
};
|
||||
@@ -80,7 +79,7 @@ where
|
||||
{
|
||||
type State = Rc<RefCell<FlatRoutesViewState>>;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(self) -> Self::State {
|
||||
let FlatRoutesView {
|
||||
current_url,
|
||||
routes,
|
||||
@@ -118,7 +117,7 @@ where
|
||||
|
||||
match new_match {
|
||||
None => Rc::new(RefCell::new(FlatRoutesViewState {
|
||||
view: fallback().into_any().build(extra_attrs),
|
||||
view: fallback().into_any().build(),
|
||||
id,
|
||||
owner,
|
||||
params,
|
||||
@@ -151,7 +150,7 @@ where
|
||||
|
||||
match view.as_mut().now_or_never() {
|
||||
Some(view) => Rc::new(RefCell::new(FlatRoutesViewState {
|
||||
view: view.into_any().build(extra_attrs),
|
||||
view: view.into_any().build(),
|
||||
id,
|
||||
owner,
|
||||
params,
|
||||
@@ -162,7 +161,7 @@ where
|
||||
None => {
|
||||
let state =
|
||||
Rc::new(RefCell::new(FlatRoutesViewState {
|
||||
view: ().into_any().build(extra_attrs.clone()),
|
||||
view: ().into_any().build(),
|
||||
id,
|
||||
owner,
|
||||
params,
|
||||
@@ -175,10 +174,8 @@ where
|
||||
let state = Rc::clone(&state);
|
||||
async move {
|
||||
let view = view.await;
|
||||
view.into_any().rebuild(
|
||||
&mut state.borrow_mut().view,
|
||||
extra_attrs,
|
||||
);
|
||||
view.into_any()
|
||||
.rebuild(&mut state.borrow_mut().view);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -189,11 +186,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
let FlatRoutesView {
|
||||
current_url,
|
||||
location,
|
||||
@@ -271,9 +264,7 @@ where
|
||||
provide_context(url);
|
||||
provide_context(params_memo);
|
||||
provide_context(Matched(ArcMemo::from(new_matched)));
|
||||
fallback()
|
||||
.into_any()
|
||||
.rebuild(&mut state.borrow_mut().view, extra_attrs)
|
||||
fallback().into_any().rebuild(&mut state.borrow_mut().view)
|
||||
});
|
||||
if let Some(location) = location {
|
||||
location.ready_to_complete();
|
||||
@@ -323,10 +314,8 @@ where
|
||||
== spawned_path
|
||||
{
|
||||
let rebuild = move || {
|
||||
view.into_any().rebuild(
|
||||
&mut state.borrow_mut().view,
|
||||
extra_attrs,
|
||||
);
|
||||
view.into_any()
|
||||
.rebuild(&mut state.borrow_mut().view);
|
||||
};
|
||||
if transition {
|
||||
start_view_transition(0, is_back, rebuild);
|
||||
@@ -354,7 +343,7 @@ impl<Loc, Defs, FalFn, Fal> AddAnyAttr for FlatRoutesView<Loc, Defs, FalFn>
|
||||
where
|
||||
Loc: LocationProvider + Send,
|
||||
Defs: MatchNestedRoutes + Send + 'static,
|
||||
FalFn: FnOnce() -> Fal + Send + 'static,
|
||||
FalFn: FnOnce() -> Fal + Send,
|
||||
Fal: RenderHtml + 'static,
|
||||
{
|
||||
type Output<SomeNewAttr: leptos::attr::Attribute> =
|
||||
@@ -427,20 +416,16 @@ impl<Loc, Defs, FalFn, Fal> RenderHtml for FlatRoutesView<Loc, Defs, FalFn>
|
||||
where
|
||||
Loc: LocationProvider + Send,
|
||||
Defs: MatchNestedRoutes + Send + 'static,
|
||||
FalFn: FnOnce() -> Fal + Send + 'static,
|
||||
FalFn: FnOnce() -> Fal + Send,
|
||||
Fal: RenderHtml + 'static,
|
||||
{
|
||||
type AsyncOutput = Self;
|
||||
type Owned = Self;
|
||||
|
||||
const MIN_LENGTH: usize = <Either<Fal, AnyView> as RenderHtml>::MIN_LENGTH;
|
||||
|
||||
fn dry_resolve(&mut self, _extra_attrs: ExtraAttrsMut<'_>) {}
|
||||
fn dry_resolve(&mut self) {}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
_extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self
|
||||
}
|
||||
|
||||
@@ -450,7 +435,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
// if this is being run on the server for the first time, generating all possible routes
|
||||
if RouteList::is_generating() {
|
||||
@@ -497,13 +481,7 @@ where
|
||||
RouteList::register(RouteList::from(routes));
|
||||
} else {
|
||||
let view = self.choose_ssr();
|
||||
view.to_html_with_buf(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
view.to_html_with_buf(buf, position, escape, mark_branches);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,7 +491,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -523,7 +500,6 @@ where
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -531,7 +507,6 @@ where
|
||||
self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
// this can be mostly the same as the build() implementation, but with hydrate()
|
||||
//
|
||||
@@ -576,11 +551,9 @@ where
|
||||
|
||||
match new_match {
|
||||
None => Rc::new(RefCell::new(FlatRoutesViewState {
|
||||
view: fallback().into_any().hydrate::<FROM_SERVER>(
|
||||
cursor,
|
||||
position,
|
||||
extra_attrs,
|
||||
),
|
||||
view: fallback()
|
||||
.into_any()
|
||||
.hydrate::<FROM_SERVER>(cursor, position),
|
||||
id,
|
||||
owner,
|
||||
params,
|
||||
@@ -613,11 +586,9 @@ where
|
||||
|
||||
match view.as_mut().now_or_never() {
|
||||
Some(view) => Rc::new(RefCell::new(FlatRoutesViewState {
|
||||
view: view.into_any().hydrate::<FROM_SERVER>(
|
||||
cursor,
|
||||
position,
|
||||
extra_attrs,
|
||||
),
|
||||
view: view
|
||||
.into_any()
|
||||
.hydrate::<FROM_SERVER>(cursor, position),
|
||||
id,
|
||||
owner,
|
||||
params,
|
||||
@@ -633,8 +604,4 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use super::{PartialPathMatch, PathSegment};
|
||||
use std::sync::Arc;
|
||||
mod param_segments;
|
||||
mod static_segment;
|
||||
mod tuples;
|
||||
@@ -12,37 +11,9 @@ pub use static_segment::*;
|
||||
/// This is a "horizontal" matching: i.e., it treats a tuple of route segments
|
||||
/// as subsequent segments of the URL and tries to match them all.
|
||||
pub trait PossibleRouteMatch {
|
||||
fn optional(&self) -> bool;
|
||||
const OPTIONAL: bool = false;
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>>;
|
||||
|
||||
fn generate_path(&self, path: &mut Vec<PathSegment>);
|
||||
}
|
||||
|
||||
impl PossibleRouteMatch for Box<dyn PossibleRouteMatch + Send + Sync> {
|
||||
fn optional(&self) -> bool {
|
||||
(**self).optional()
|
||||
}
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
(**self).test(path)
|
||||
}
|
||||
|
||||
fn generate_path(&self, path: &mut Vec<PathSegment>) {
|
||||
(**self).generate_path(path);
|
||||
}
|
||||
}
|
||||
|
||||
impl PossibleRouteMatch for Arc<dyn PossibleRouteMatch + Send + Sync> {
|
||||
fn optional(&self) -> bool {
|
||||
(**self).optional()
|
||||
}
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
(**self).test(path)
|
||||
}
|
||||
|
||||
fn generate_path(&self, path: &mut Vec<PathSegment>) {
|
||||
(**self).generate_path(path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,10 +35,6 @@ use std::borrow::Cow;
|
||||
pub struct ParamSegment(pub &'static str);
|
||||
|
||||
impl PossibleRouteMatch for ParamSegment {
|
||||
fn optional(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
let mut matched_len = 0;
|
||||
let mut param_offset = 0;
|
||||
@@ -125,10 +121,6 @@ impl PossibleRouteMatch for ParamSegment {
|
||||
pub struct WildcardSegment(pub &'static str);
|
||||
|
||||
impl PossibleRouteMatch for WildcardSegment {
|
||||
fn optional(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
let mut matched_len = 0;
|
||||
let mut param_offset = 0;
|
||||
@@ -166,9 +158,7 @@ impl PossibleRouteMatch for WildcardSegment {
|
||||
pub struct OptionalParamSegment(pub &'static str);
|
||||
|
||||
impl PossibleRouteMatch for OptionalParamSegment {
|
||||
fn optional(&self) -> bool {
|
||||
true
|
||||
}
|
||||
const OPTIONAL: bool = true;
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
let mut matched_len = 0;
|
||||
|
||||
@@ -2,10 +2,6 @@ use super::{PartialPathMatch, PathSegment, PossibleRouteMatch};
|
||||
use std::fmt::Debug;
|
||||
|
||||
impl PossibleRouteMatch for () {
|
||||
fn optional(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
Some(PartialPathMatch::new(path, vec![], ""))
|
||||
}
|
||||
@@ -58,10 +54,6 @@ impl AsPath for &'static str {
|
||||
pub struct StaticSegment<T: AsPath>(pub T);
|
||||
|
||||
impl<T: AsPath> PossibleRouteMatch for StaticSegment<T> {
|
||||
fn optional(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
let mut matched_len = 0;
|
||||
let mut test = path.chars().peekable();
|
||||
|
||||
@@ -8,21 +8,15 @@ macro_rules! tuples {
|
||||
$first: PossibleRouteMatch,
|
||||
$($ty: PossibleRouteMatch),*,
|
||||
{
|
||||
fn optional(&self) -> bool {
|
||||
#[allow(non_snake_case)]
|
||||
let ($first, $($ty,)*) = &self;
|
||||
[$first.optional(), $($ty.optional()),*].into_iter().any(|n| n)
|
||||
}
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
#[allow(non_snake_case)]
|
||||
let ($first, $($ty,)*) = &self;
|
||||
|
||||
// on the first run, include all optionals
|
||||
let mut include_optionals = {
|
||||
[$first.optional(), $($ty.optional()),*].into_iter().filter(|n| *n).count()
|
||||
[$first::OPTIONAL, $($ty::OPTIONAL),*].into_iter().filter(|n| *n).count()
|
||||
};
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
let ($first, $($ty,)*) = &self;
|
||||
|
||||
loop {
|
||||
let mut nth_field = 0;
|
||||
let mut matched_len = 0;
|
||||
@@ -31,7 +25,7 @@ macro_rules! tuples {
|
||||
let mut p = Vec::new();
|
||||
let mut m = String::new();
|
||||
|
||||
if !$first.optional() || nth_field < include_optionals {
|
||||
if !$first::OPTIONAL || nth_field < include_optionals {
|
||||
match $first.test(r) {
|
||||
None => {
|
||||
return None;
|
||||
@@ -46,16 +40,16 @@ macro_rules! tuples {
|
||||
|
||||
matched_len += m.len();
|
||||
$(
|
||||
if $ty.optional() {
|
||||
if $ty::OPTIONAL {
|
||||
nth_field += 1;
|
||||
}
|
||||
if !$ty.optional() || nth_field < include_optionals {
|
||||
if !$ty::OPTIONAL || nth_field < include_optionals {
|
||||
let PartialPathMatch {
|
||||
remaining,
|
||||
matched,
|
||||
params
|
||||
} = match $ty.test(r) {
|
||||
None => if $ty.optional() {
|
||||
None => if $ty::OPTIONAL {
|
||||
return None;
|
||||
} else {
|
||||
if include_optionals == 0 {
|
||||
@@ -96,10 +90,6 @@ where
|
||||
Self: core::fmt::Debug,
|
||||
A: PossibleRouteMatch,
|
||||
{
|
||||
fn optional(&self) -> bool {
|
||||
self.0.optional()
|
||||
}
|
||||
|
||||
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
|
||||
let remaining = path;
|
||||
let PartialPathMatch {
|
||||
|
||||
@@ -151,7 +151,7 @@ impl<Segments, Children, Data, View> MatchNestedRoutes
|
||||
for NestedRoute<Segments, Children, Data, View>
|
||||
where
|
||||
Self: 'static,
|
||||
Segments: PossibleRouteMatch,
|
||||
Segments: PossibleRouteMatch + std::fmt::Debug,
|
||||
Children: MatchNestedRoutes,
|
||||
Children::Match: MatchParams,
|
||||
Children: 'static,
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
use any_spawner::Executor;
|
||||
use either_of::{Either, EitherOf3};
|
||||
use futures::{channel::oneshot, future::join_all, FutureExt};
|
||||
use leptos::{attr::any_attribute::AnyAttribute, component, oco::Oco};
|
||||
use leptos::{component, oco::Oco};
|
||||
use or_poisoned::OrPoisoned;
|
||||
use reactive_graph::{
|
||||
computed::{ArcMemo, ScopedFuture},
|
||||
@@ -36,7 +36,7 @@ use tachys::{
|
||||
ssr::StreamBuilder,
|
||||
view::{
|
||||
add_attr::AddAnyAttr,
|
||||
any_view::{AnyView, ExtraAttrsMut, IntoAny},
|
||||
any_view::{AnyView, IntoAny},
|
||||
either::EitherOf3State,
|
||||
Mountable, Position, PositionState, Render, RenderHtml,
|
||||
},
|
||||
@@ -76,7 +76,7 @@ where
|
||||
// TODO support fallback while loading
|
||||
type State = NestedRouteViewState<Fal>;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(self) -> Self::State {
|
||||
let NestedRoutesView {
|
||||
routes,
|
||||
outer_owner,
|
||||
@@ -95,7 +95,7 @@ where
|
||||
let new_match = routes.match_route(url.path());
|
||||
|
||||
// start with an empty view because we'll be loading routes async
|
||||
let view = EitherOf3::A(()).build(extra_attrs.clone());
|
||||
let view = EitherOf3::A(()).build();
|
||||
let view = Rc::new(RefCell::new(view));
|
||||
let matched_view = match new_match {
|
||||
None => EitherOf3::B(fallback()),
|
||||
@@ -120,7 +120,7 @@ where
|
||||
for trigger in triggers {
|
||||
trigger.notify();
|
||||
}
|
||||
matched_view.rebuild(&mut *view.borrow_mut(), extra_attrs);
|
||||
matched_view.rebuild(&mut *view.borrow_mut());
|
||||
})
|
||||
});
|
||||
|
||||
@@ -132,11 +132,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
let url_snapshot = self.current_url.get_untracked();
|
||||
|
||||
// if the path is the same, we do not need to re-route
|
||||
@@ -158,7 +154,7 @@ where
|
||||
match new_match {
|
||||
None => {
|
||||
EitherOf3::<(), Fal, AnyView>::B((self.fallback)())
|
||||
.rebuild(&mut state.view.borrow_mut(), extra_attrs);
|
||||
.rebuild(&mut state.view.borrow_mut());
|
||||
state.outlets.clear();
|
||||
if let Some(loc) = self.location {
|
||||
loc.ready_to_complete();
|
||||
@@ -217,10 +213,7 @@ where
|
||||
if matches!(state.view.borrow().state, EitherOf3::B(_)) {
|
||||
self.outer_owner.with(|| {
|
||||
EitherOf3::<(), Fal, AnyView>::C(Outlet().into_any())
|
||||
.rebuild(
|
||||
&mut *state.view.borrow_mut(),
|
||||
extra_attrs,
|
||||
);
|
||||
.rebuild(&mut *state.view.borrow_mut());
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -235,8 +228,8 @@ where
|
||||
impl<Loc, Defs, Fal, FalFn> AddAnyAttr for NestedRoutesView<Loc, Defs, FalFn>
|
||||
where
|
||||
Loc: LocationProvider + Send,
|
||||
Defs: MatchNestedRoutes + Send + 'static,
|
||||
FalFn: FnOnce() -> Fal + Send + 'static,
|
||||
Defs: MatchNestedRoutes + Send,
|
||||
FalFn: FnOnce() -> Fal + Send,
|
||||
Fal: RenderHtml + 'static,
|
||||
{
|
||||
type Output<SomeNewAttr: leptos::attr::Attribute> =
|
||||
@@ -256,21 +249,17 @@ where
|
||||
impl<Loc, Defs, FalFn, Fal> RenderHtml for NestedRoutesView<Loc, Defs, FalFn>
|
||||
where
|
||||
Loc: LocationProvider + Send,
|
||||
Defs: MatchNestedRoutes + Send + 'static,
|
||||
FalFn: FnOnce() -> Fal + Send + 'static,
|
||||
Defs: MatchNestedRoutes + Send,
|
||||
FalFn: FnOnce() -> Fal + Send,
|
||||
Fal: RenderHtml + 'static,
|
||||
{
|
||||
type AsyncOutput = Self;
|
||||
type Owned = Self;
|
||||
|
||||
const MIN_LENGTH: usize = 0; // TODO
|
||||
|
||||
fn dry_resolve(&mut self, _extra_attrs: ExtraAttrsMut<'_>) {}
|
||||
fn dry_resolve(&mut self) {}
|
||||
|
||||
async fn resolve(
|
||||
self,
|
||||
_extra_attrs: ExtraAttrsMut<'_>,
|
||||
) -> Self::AsyncOutput {
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self
|
||||
}
|
||||
|
||||
@@ -280,7 +269,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
// if this is being run on the server for the first time, generating all possible routes
|
||||
if RouteList::is_generating() {
|
||||
@@ -360,13 +348,7 @@ where
|
||||
outer_owner.with(|| Either::Right(Outlet().into_any()))
|
||||
}
|
||||
};
|
||||
view.to_html_with_buf(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
view.to_html_with_buf(buf, position, escape, mark_branches);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,7 +358,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -419,7 +400,6 @@ where
|
||||
position,
|
||||
escape,
|
||||
mark_branches,
|
||||
extra_attrs,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -427,7 +407,6 @@ where
|
||||
self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let NestedRoutesView {
|
||||
routes,
|
||||
@@ -467,7 +446,7 @@ where
|
||||
outer_owner.with(|| EitherOf3::C(Outlet().into_any()))
|
||||
}
|
||||
}
|
||||
.hydrate::<FROM_SERVER>(cursor, position, extra_attrs),
|
||||
.hydrate::<FROM_SERVER>(cursor, position),
|
||||
));
|
||||
|
||||
NestedRouteViewState {
|
||||
@@ -477,10 +456,6 @@ where
|
||||
view,
|
||||
}
|
||||
}
|
||||
|
||||
fn into_owned(self) -> Self::Owned {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
type OutletViewFn = Box<dyn Fn() -> Suspend<AnyView> + Send>;
|
||||
|
||||
@@ -89,7 +89,7 @@ where
|
||||
type State =
|
||||
ReactiveRouterInnerState<Rndr, Loc, Defs, FallbackFn, Fallback>;
|
||||
|
||||
fn build(self, _extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(self) -> Self::State {
|
||||
let (prev_id, inner) = self.inner.fallback_or_view();
|
||||
let owner = self.owner.with(Owner::new);
|
||||
ReactiveRouterInnerState {
|
||||
@@ -100,11 +100,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
self,
|
||||
state: &mut Self::State,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
let (new_id, view) = self.inner.fallback_or_view();
|
||||
if new_id != state.prev_id {
|
||||
state.owner = self.owner.with(Owner::new)
|
||||
@@ -134,7 +130,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
// if this is being run on the server for the first time, generating all possible routes
|
||||
if RouteList::is_generating() {
|
||||
@@ -161,7 +156,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -175,7 +169,6 @@ where
|
||||
self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let (prev_id, inner) = self.inner.fallback_or_view();
|
||||
let owner = self.owner.with(Owner::new);
|
||||
@@ -287,7 +280,7 @@ where
|
||||
{
|
||||
type State = ReactiveRouteState<View::State>;
|
||||
|
||||
fn build(self, extra_attrs: Option<Vec<AnyAttribute>>) -> Self::State {
|
||||
fn build(self) -> Self::State {
|
||||
let MatchedRoute {
|
||||
search_params,
|
||||
params,
|
||||
@@ -298,19 +291,14 @@ where
|
||||
params: ArcRwSignal::new(params),
|
||||
matched: ArcRwSignal::new(matched),
|
||||
};
|
||||
let view_state =
|
||||
untrack(|| (self.view_fn)(&matched).build(extra_attrs.clone()));
|
||||
let view_state = untrack(|| (self.view_fn)(&matched).build());
|
||||
ReactiveRouteState {
|
||||
matched,
|
||||
view_state,
|
||||
}
|
||||
}
|
||||
|
||||
fn rebuild(
|
||||
mut self,
|
||||
state: &mut Self::State,
|
||||
_extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
fn rebuild(mut self, state: &mut Self::State) {
|
||||
let ReactiveRouteState { matched, .. } = state;
|
||||
matched
|
||||
.search_params
|
||||
@@ -336,7 +324,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) {
|
||||
let MatchedRoute {
|
||||
search_params,
|
||||
@@ -349,12 +336,7 @@ where
|
||||
matched: ArcRwSignal::new(matched),
|
||||
};
|
||||
untrack(|| {
|
||||
(self.view_fn)(&matched).to_html_with_buf(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
extra_attrs.clone(),
|
||||
)
|
||||
(self.view_fn)(&matched).to_html_with_buf(buf, position, escape)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -364,7 +346,6 @@ where
|
||||
position: &mut Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -379,12 +360,8 @@ where
|
||||
matched: ArcRwSignal::new(matched),
|
||||
};
|
||||
untrack(|| {
|
||||
(self.view_fn)(&matched).to_html_async_with_buf::<OUT_OF_ORDER>(
|
||||
buf,
|
||||
position,
|
||||
escape,
|
||||
extra_attrs.clone(),
|
||||
)
|
||||
(self.view_fn)(&matched)
|
||||
.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position, escape)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -392,7 +369,6 @@ where
|
||||
self,
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
extra_attrs: Option<Vec<AnyAttribute>>,
|
||||
) -> Self::State {
|
||||
let MatchedRoute {
|
||||
search_params,
|
||||
@@ -405,11 +381,7 @@ where
|
||||
matched: ArcRwSignal::new(matched),
|
||||
};
|
||||
let view_state = untrack(|| {
|
||||
(self.view_fn)(&matched).hydrate::<FROM_SERVER>(
|
||||
cursor,
|
||||
position,
|
||||
extra_attrs.clone(),
|
||||
)
|
||||
(self.view_fn)(&matched).hydrate::<FROM_SERVER>(cursor, position)
|
||||
});
|
||||
ReactiveRouteState {
|
||||
matched,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_router_macro"
|
||||
version = "0.8.0-alpha"
|
||||
version = "0.7.7"
|
||||
authors = ["Greg Johnston", "Ben Wishovich"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -14,7 +14,6 @@ throw_error = { workspace = true }
|
||||
server_fn_macro_default = { workspace = true }
|
||||
# used for hashing paths in #[server] macro
|
||||
const_format = "0.2.33"
|
||||
const-str = "0.5.7"
|
||||
xxhash-rust = { version = "0.8.12", features = ["const_xxh64"] }
|
||||
# used across multiple features
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
@@ -31,7 +30,7 @@ once_cell = "1.20"
|
||||
actix-web = { version = "4.9", optional = true }
|
||||
|
||||
# axum
|
||||
axum = { version = "0.8.1", optional = true, default-features = false, features = [
|
||||
axum = { version = "0.7.9", optional = true, default-features = false, features = [
|
||||
"multipart",
|
||||
] }
|
||||
tower = { version = "0.5.1", optional = true }
|
||||
@@ -54,7 +53,6 @@ bytes = "1.9"
|
||||
http-body-util = { version = "0.1.2", optional = true }
|
||||
rkyv = { version = "0.8.9", optional = true }
|
||||
rmp-serde = { version = "1.3.0", optional = true }
|
||||
base64 = { version = "0.22.1" }
|
||||
|
||||
# client
|
||||
gloo-net = { version = "0.6.0", optional = true }
|
||||
@@ -233,4 +231,4 @@ skip_feature_sets = [
|
||||
]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
|
||||
@@ -74,7 +74,7 @@ pub fn server(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
|
||||
args.into(),
|
||||
s.into(),
|
||||
Some(syn::parse_quote!(server_fns)),
|
||||
option_env!("SERVER_FN_PREFIX").unwrap_or("/api"),
|
||||
"/api",
|
||||
None,
|
||||
None,
|
||||
) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{request::ClientReq, response::ClientRes};
|
||||
use crate::{error::ServerFnError, request::ClientReq, response::ClientRes};
|
||||
use std::{future::Future, sync::OnceLock};
|
||||
|
||||
static ROOT_URL: OnceLock<&'static str> = OnceLock::new();
|
||||
@@ -21,16 +21,16 @@ pub fn get_server_url() -> &'static str {
|
||||
/// This trait is implemented for things like a browser `fetch` request or for
|
||||
/// the `reqwest` trait. It should almost never be necessary to implement it
|
||||
/// yourself, unless you’re trying to use an alternative HTTP crate on the client side.
|
||||
pub trait Client<E> {
|
||||
pub trait Client<CustErr> {
|
||||
/// The type of a request sent by this client.
|
||||
type Request: ClientReq<E> + Send;
|
||||
type Request: ClientReq<CustErr> + Send;
|
||||
/// The type of a response received by this client.
|
||||
type Response: ClientRes<E> + Send;
|
||||
type Response: ClientRes<CustErr> + Send;
|
||||
|
||||
/// Sends the request and receives a response.
|
||||
fn send(
|
||||
req: Self::Request,
|
||||
) -> impl Future<Output = Result<Self::Response, E>> + Send;
|
||||
) -> impl Future<Output = Result<Self::Response, ServerFnError<CustErr>>> + Send;
|
||||
}
|
||||
|
||||
#[cfg(feature = "browser")]
|
||||
@@ -38,23 +38,24 @@ pub trait Client<E> {
|
||||
pub mod browser {
|
||||
use super::Client;
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::ServerFnError,
|
||||
request::browser::{BrowserRequest, RequestInner},
|
||||
response::browser::BrowserResponse,
|
||||
};
|
||||
use send_wrapper::SendWrapper;
|
||||
use std::future::Future;
|
||||
|
||||
/// Implements [`Client`] for a `fetch` request in the browser.
|
||||
/// Implements [`Client`] for a `fetch` request in the browser.
|
||||
pub struct BrowserClient;
|
||||
|
||||
impl<E: FromServerFnError> Client<E> for BrowserClient {
|
||||
impl<CustErr> Client<CustErr> for BrowserClient {
|
||||
type Request = BrowserRequest;
|
||||
type Response = BrowserResponse;
|
||||
|
||||
fn send(
|
||||
req: Self::Request,
|
||||
) -> impl Future<Output = Result<Self::Response, E>> + Send {
|
||||
) -> impl Future<Output = Result<Self::Response, ServerFnError<CustErr>>>
|
||||
+ Send {
|
||||
SendWrapper::new(async move {
|
||||
let req = req.0.take();
|
||||
let RequestInner {
|
||||
@@ -65,10 +66,7 @@ pub mod browser {
|
||||
.send()
|
||||
.await
|
||||
.map(|res| BrowserResponse(SendWrapper::new(res)))
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Request(e.to_string())
|
||||
.into_app_error()
|
||||
});
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()));
|
||||
|
||||
// at this point, the future has successfully resolved without being dropped, so we
|
||||
// can prevent the `AbortController` from firing
|
||||
@@ -85,10 +83,7 @@ pub mod browser {
|
||||
/// Implements [`Client`] for a request made by [`reqwest`].
|
||||
pub mod reqwest {
|
||||
use super::Client;
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
request::reqwest::CLIENT,
|
||||
};
|
||||
use crate::{error::ServerFnError, request::reqwest::CLIENT};
|
||||
use futures::TryFutureExt;
|
||||
use reqwest::{Request, Response};
|
||||
use std::future::Future;
|
||||
@@ -96,16 +91,17 @@ pub mod reqwest {
|
||||
/// Implements [`Client`] for a request made by [`reqwest`].
|
||||
pub struct ReqwestClient;
|
||||
|
||||
impl<E: FromServerFnError> Client<E> for ReqwestClient {
|
||||
impl<CustErr> Client<CustErr> for ReqwestClient {
|
||||
type Request = Request;
|
||||
type Response = Response;
|
||||
|
||||
fn send(
|
||||
req: Self::Request,
|
||||
) -> impl Future<Output = Result<Self::Response, E>> + Send {
|
||||
CLIENT.execute(req).map_err(|e| {
|
||||
ServerFnErrorErr::Request(e.to_string()).into_app_error()
|
||||
})
|
||||
) -> impl Future<Output = Result<Self::Response, ServerFnError<CustErr>>>
|
||||
+ Send {
|
||||
CLIENT
|
||||
.execute(req)
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::ServerFnError,
|
||||
request::{ClientReq, Req},
|
||||
response::{ClientRes, TryRes},
|
||||
response::{ClientRes, Res},
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use http::Method;
|
||||
@@ -16,17 +16,19 @@ impl Encoding for Cbor {
|
||||
const METHOD: Method = Method::POST;
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<Cbor, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<Cbor, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<CustErr>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let mut buffer: Vec<u8> = Vec::new();
|
||||
ciborium::ser::into_writer(&self, &mut buffer).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
ciborium::ser::into_writer(&self, &mut buffer)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Request::try_new_post_bytes(
|
||||
path,
|
||||
accepts,
|
||||
@@ -36,44 +38,40 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<Cbor, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<Cbor, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let body_bytes = req.try_into_bytes().await?;
|
||||
ciborium::de::from_reader(body_bytes.as_ref())
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> IntoRes<Cbor, Response, E> for T
|
||||
impl<CustErr, T, Response> IntoRes<Cbor, Response, CustErr> for T
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
Response: Res<CustErr>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<CustErr>> {
|
||||
let mut buffer: Vec<u8> = Vec::new();
|
||||
ciborium::ser::into_writer(&self, &mut buffer).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
ciborium::ser::into_writer(&self, &mut buffer)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Response::try_from_bytes(Cbor::CONTENT_TYPE, Bytes::from(buffer))
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> FromRes<Cbor, Response, E> for T
|
||||
impl<CustErr, T, Response> FromRes<Cbor, Response, CustErr> for T
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
Response: ClientRes<CustErr> + Send,
|
||||
T: DeserializeOwned + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let data = res.try_into_bytes().await?;
|
||||
ciborium::de::from_reader(data.as_ref())
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,20 +114,20 @@ where
|
||||
<ResponseBody as HttpBody>::Data: Send ,
|
||||
<RequestBody as HttpBody>::Data: Send ,
|
||||
{
|
||||
async fn from_req(req: http::Request<RequestBody>) -> Result<Self, ServerFnError<E>> {
|
||||
async fn from_req(req: http::Request<RequestBody>) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let (_parts, body) = req.into_parts();
|
||||
|
||||
let body_bytes = body
|
||||
.collect()
|
||||
.await
|
||||
.map(|c| c.to_bytes())
|
||||
.map_err(|e| ServerFnErrorErr::Deserialization(e.to_string()).into())?;
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))?;
|
||||
let data = ciborium::de::from_reader(body_bytes.as_ref())
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into())?;
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
async fn into_req(self) -> Result<http::Request<Body>, ServerFnError<E>> {
|
||||
async fn into_req(self) -> Result<http::Request<Body>, ServerFnError<CustErr>> {
|
||||
let mut buffer: Vec<u8> = Vec::new();
|
||||
ciborium::ser::into_writer(&self, &mut buffer)?;
|
||||
let req = http::Request::builder()
|
||||
@@ -141,17 +139,17 @@ where
|
||||
.body(Body::from(buffer))?;
|
||||
Ok(req)
|
||||
}
|
||||
async fn from_res(res: http::Response<ResponseBody>) -> Result<Self, ServerFnError<E>> {
|
||||
async fn from_res(res: http::Response<ResponseBody>) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let (_parts, body) = res.into_parts();
|
||||
|
||||
let body_bytes = body
|
||||
.collect()
|
||||
.await
|
||||
.map(|c| c.to_bytes())
|
||||
.map_err(|e| ServerFnErrorErr::Deserialization(e.to_string()).into())?;
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))?;
|
||||
|
||||
ciborium::de::from_reader(body_bytes.as_ref())
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into())
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
|
||||
async fn into_res(self) -> http::Response<Body> {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{Encoding, FromReq, FromRes, Streaming};
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::{NoCustomError, ServerFnError},
|
||||
request::{ClientReq, Req},
|
||||
response::{ClientRes, TryRes},
|
||||
response::{ClientRes, Res},
|
||||
IntoReq, IntoRes,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
@@ -18,58 +18,55 @@ impl Encoding for Json {
|
||||
const METHOD: Method = Method::POST;
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<Json, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<Json, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<CustErr>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
let data = serde_json::to_string(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let data = serde_json::to_string(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Request::try_new_post(path, accepts, Json::CONTENT_TYPE, data)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<Json, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<Json, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let string_data = req.try_into_string().await?;
|
||||
serde_json::from_str::<Self>(&string_data)
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> IntoRes<Json, Response, E> for T
|
||||
impl<CustErr, T, Response> IntoRes<Json, Response, CustErr> for T
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
Response: Res<CustErr>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
let data = serde_json::to_string(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<CustErr>> {
|
||||
let data = serde_json::to_string(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Response::try_from_string(Json::CONTENT_TYPE, data)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> FromRes<Json, Response, E> for T
|
||||
impl<CustErr, T, Response> FromRes<Json, Response, CustErr> for T
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
Response: ClientRes<CustErr> + Send,
|
||||
T: DeserializeOwned + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let data = res.try_into_string().await?;
|
||||
serde_json::from_str(&data).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
serde_json::from_str(&data)
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,31 +102,35 @@ impl Encoding for StreamingJson {
|
||||
/// end before the output will begin.
|
||||
///
|
||||
/// Streaming requests are only allowed over HTTP2 or HTTP3.
|
||||
pub struct JsonStream<T, E>(Pin<Box<dyn Stream<Item = Result<T, E>> + Send>>);
|
||||
pub struct JsonStream<T, CustErr = NoCustomError>(
|
||||
Pin<Box<dyn Stream<Item = Result<T, ServerFnError<CustErr>>> + Send>>,
|
||||
);
|
||||
|
||||
impl<T, E> std::fmt::Debug for JsonStream<T, E> {
|
||||
impl<T, CustErr> std::fmt::Debug for JsonStream<T, CustErr> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("JsonStream").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> JsonStream<T, E> {
|
||||
impl<T> JsonStream<T> {
|
||||
/// Creates a new `ByteStream` from the given stream.
|
||||
pub fn new(
|
||||
value: impl Stream<Item = Result<T, E>> + Send + 'static,
|
||||
value: impl Stream<Item = Result<T, ServerFnError>> + Send + 'static,
|
||||
) -> Self {
|
||||
Self(Box::pin(value.map(|value| value)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> JsonStream<T, E> {
|
||||
impl<T, CustErr> JsonStream<T, CustErr> {
|
||||
/// Consumes the wrapper, returning a stream of text.
|
||||
pub fn into_inner(self) -> impl Stream<Item = Result<T, E>> + Send {
|
||||
pub fn into_inner(
|
||||
self,
|
||||
) -> impl Stream<Item = Result<T, ServerFnError<CustErr>>> + Send {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T: 'static, E: 'static> From<S> for JsonStream<T, E>
|
||||
impl<S, T: 'static, CustErr: 'static> From<S> for JsonStream<T, CustErr>
|
||||
where
|
||||
S: Stream<Item = T> + Send + 'static,
|
||||
{
|
||||
@@ -138,15 +139,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, S, T, Request> IntoReq<StreamingJson, Request, E> for S
|
||||
impl<CustErr, S, T, Request> IntoReq<StreamingJson, Request, CustErr> for S
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<CustErr>,
|
||||
S: Stream<Item = T> + Send + 'static,
|
||||
T: Serialize + 'static,
|
||||
E: FromServerFnError + Serialize,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
let data: JsonStream<T, E> = self.into();
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let data: JsonStream<T> = self.into();
|
||||
Request::try_new_streaming(
|
||||
path,
|
||||
accepts,
|
||||
@@ -160,61 +164,56 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, S, Request> FromReq<StreamingJson, Request, E> for S
|
||||
impl<CustErr, T, S, Request> FromReq<StreamingJson, Request, CustErr> for S
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
// The additional `Stream<Item = T>` bound is never used, but it is required to avoid an error where `T` is unconstrained
|
||||
S: Stream<Item = T> + From<JsonStream<T, E>> + Send + 'static,
|
||||
S: Stream<Item = T> + From<JsonStream<T>> + Send + 'static,
|
||||
T: DeserializeOwned + 'static,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let data = req.try_into_stream()?;
|
||||
let s = JsonStream::new(data.map(|chunk| {
|
||||
chunk.and_then(|bytes| {
|
||||
serde_json::from_slice(bytes.as_ref()).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
serde_json::from_slice(bytes.as_ref())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
})
|
||||
}));
|
||||
Ok(s.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> IntoRes<StreamingJson, Response, E> for JsonStream<T, E>
|
||||
impl<CustErr, T, Response> IntoRes<StreamingJson, Response, CustErr>
|
||||
for JsonStream<T, CustErr>
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
Response: Res<CustErr>,
|
||||
CustErr: 'static,
|
||||
T: Serialize + 'static,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<CustErr>> {
|
||||
Response::try_from_stream(
|
||||
Streaming::CONTENT_TYPE,
|
||||
self.into_inner().map(|value| {
|
||||
serde_json::to_vec(&value?).map(Bytes::from).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
serde_json::to_vec(&value?)
|
||||
.map(Bytes::from)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> FromRes<StreamingJson, Response, E> for JsonStream<T, E>
|
||||
impl<CustErr, T, Response> FromRes<StreamingJson, Response, CustErr>
|
||||
for JsonStream<T>
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
Response: ClientRes<CustErr> + Send,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let stream = res.try_into_stream()?;
|
||||
Ok(JsonStream::new(stream.map(|chunk| {
|
||||
chunk.and_then(|bytes| {
|
||||
serde_json::from_slice(bytes.as_ref()).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
serde_json::from_slice(bytes.as_ref())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
})
|
||||
})))
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ mod postcard;
|
||||
pub use postcard::*;
|
||||
|
||||
mod stream;
|
||||
use crate::error::ServerFnError;
|
||||
use futures::Future;
|
||||
use http::Method;
|
||||
pub use stream::*;
|
||||
@@ -70,27 +71,31 @@ pub use stream::*;
|
||||
/// For example, here’s the implementation for [`Json`].
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// impl<E, T, Request> IntoReq<Json, Request, E> for T
|
||||
/// impl<CustErr, T, Request> IntoReq<Json, Request, CustErr> for T
|
||||
/// where
|
||||
/// Request: ClientReq<E>,
|
||||
/// Request: ClientReq<CustErr>,
|
||||
/// T: Serialize + Send,
|
||||
/// {
|
||||
/// fn into_req(
|
||||
/// self,
|
||||
/// path: &str,
|
||||
/// accepts: &str,
|
||||
/// ) -> Result<Request, E> {
|
||||
/// ) -> Result<Request, ServerFnError<CustErr>> {
|
||||
/// // try to serialize the data
|
||||
/// let data = serde_json::to_string(&self)
|
||||
/// .map_err(|e| ServerFnErrorErr::Serialization(e.to_string()).into_app_error())?;
|
||||
/// .map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
/// // and use it as the body of a POST request
|
||||
/// Request::try_new_post(path, accepts, Json::CONTENT_TYPE, data)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait IntoReq<Encoding, Request, E> {
|
||||
pub trait IntoReq<Encoding, Request, CustErr> {
|
||||
/// Attempts to serialize the arguments into an HTTP request.
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E>;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>>;
|
||||
}
|
||||
|
||||
/// Deserializes an HTTP request into the data type, on the server.
|
||||
@@ -104,31 +109,32 @@ pub trait IntoReq<Encoding, Request, E> {
|
||||
/// For example, here’s the implementation for [`Json`].
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// impl<E, T, Request> FromReq<Json, Request, E> for T
|
||||
/// impl<CustErr, T, Request> FromReq<Json, Request, CustErr> for T
|
||||
/// where
|
||||
/// // require the Request implement `Req`
|
||||
/// Request: Req<E> + Send + 'static,
|
||||
/// Request: Req<CustErr> + Send + 'static,
|
||||
/// // require that the type can be deserialized with `serde`
|
||||
/// T: DeserializeOwned,
|
||||
/// E: FromServerFnError,
|
||||
/// {
|
||||
/// async fn from_req(
|
||||
/// req: Request,
|
||||
/// ) -> Result<Self, E> {
|
||||
/// ) -> Result<Self, ServerFnError<CustErr>> {
|
||||
/// // try to convert the body of the request into a `String`
|
||||
/// let string_data = req.try_into_string().await?;
|
||||
/// // deserialize the data
|
||||
/// serde_json::from_str(&string_data)
|
||||
/// .map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
/// serde_json::from_str::<Self>(&string_data)
|
||||
/// .map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait FromReq<Encoding, Request, E>
|
||||
pub trait FromReq<Encoding, Request, CustErr>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
/// Attempts to deserialize the arguments from a request.
|
||||
fn from_req(req: Request) -> impl Future<Output = Result<Self, E>> + Send;
|
||||
fn from_req(
|
||||
req: Request,
|
||||
) -> impl Future<Output = Result<Self, ServerFnError<CustErr>>> + Send;
|
||||
}
|
||||
|
||||
/// Serializes the data type into an HTTP response.
|
||||
@@ -142,24 +148,25 @@ where
|
||||
/// For example, here’s the implementation for [`Json`].
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// impl<E, T, Response> IntoRes<Json, Response, E> for T
|
||||
/// impl<CustErr, T, Response> IntoRes<Json, Response, CustErr> for T
|
||||
/// where
|
||||
/// Response: Res<E>,
|
||||
/// Response: Res<CustErr>,
|
||||
/// T: Serialize + Send,
|
||||
/// E: FromServerFnError,
|
||||
/// {
|
||||
/// async fn into_res(self) -> Result<Response, E> {
|
||||
/// async fn into_res(self) -> Result<Response, ServerFnError<CustErr>> {
|
||||
/// // try to serialize the data
|
||||
/// let data = serde_json::to_string(&self)
|
||||
/// .map_err(|e| ServerFnErrorErr::Serialization(e.to_string()).into())?;
|
||||
/// .map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
/// // and use it as the body of a response
|
||||
/// Response::try_from_string(Json::CONTENT_TYPE, data)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait IntoRes<Encoding, Response, E> {
|
||||
pub trait IntoRes<Encoding, Response, CustErr> {
|
||||
/// Attempts to serialize the output into an HTTP response.
|
||||
fn into_res(self) -> impl Future<Output = Result<Response, E>> + Send;
|
||||
fn into_res(
|
||||
self,
|
||||
) -> impl Future<Output = Result<Response, ServerFnError<CustErr>>> + Send;
|
||||
}
|
||||
|
||||
/// Deserializes the data type from an HTTP response.
|
||||
@@ -174,29 +181,30 @@ pub trait IntoRes<Encoding, Response, E> {
|
||||
/// For example, here’s the implementation for [`Json`].
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// impl<E, T, Response> FromRes<Json, Response, E> for T
|
||||
/// impl<CustErr, T, Response> FromRes<Json, Response, CustErr> for T
|
||||
/// where
|
||||
/// Response: ClientRes<E> + Send,
|
||||
/// Response: ClientRes<CustErr> + Send,
|
||||
/// T: DeserializeOwned + Send,
|
||||
/// E: FromServerFnError,
|
||||
/// {
|
||||
/// async fn from_res(
|
||||
/// res: Response,
|
||||
/// ) -> Result<Self, E> {
|
||||
/// ) -> Result<Self, ServerFnError<CustErr>> {
|
||||
/// // extracts the request body
|
||||
/// let data = res.try_into_string().await?;
|
||||
/// // and tries to deserialize it as JSON
|
||||
/// serde_json::from_str(&data)
|
||||
/// .map_err(|e| ServerFnErrorErr::Deserialization(e.to_string()).into_app_error())
|
||||
/// .map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait FromRes<Encoding, Response, E>
|
||||
pub trait FromRes<Encoding, Response, CustErr>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
/// Attempts to deserialize the outputs from a response.
|
||||
fn from_res(res: Response) -> impl Future<Output = Result<Self, E>> + Send;
|
||||
fn from_res(
|
||||
res: Response,
|
||||
) -> impl Future<Output = Result<Self, ServerFnError<CustErr>>> + Send;
|
||||
}
|
||||
|
||||
/// Defines a particular encoding format, which can be used for serializing or deserializing data.
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::ServerFnError,
|
||||
request::{ClientReq, Req},
|
||||
response::{ClientRes, TryRes},
|
||||
response::{ClientRes, Res},
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use http::Method;
|
||||
@@ -16,16 +16,18 @@ impl Encoding for MsgPack {
|
||||
const METHOD: Method = Method::POST;
|
||||
}
|
||||
|
||||
impl<T, Request, E> IntoReq<MsgPack, Request, E> for T
|
||||
impl<T, Request, Err> IntoReq<MsgPack, Request, Err> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<Err>,
|
||||
T: Serialize,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
let data = rmp_serde::to_vec(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<Err>> {
|
||||
let data = rmp_serde::to_vec(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Request::try_new_post_bytes(
|
||||
path,
|
||||
MsgPack::CONTENT_TYPE,
|
||||
@@ -35,43 +37,38 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Request, E> FromReq<MsgPack, Request, E> for T
|
||||
impl<T, Request, Err> FromReq<MsgPack, Request, Err> for T
|
||||
where
|
||||
Request: Req<E> + Send,
|
||||
Request: Req<Err> + Send,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<Err>> {
|
||||
let data = req.try_into_bytes().await?;
|
||||
rmp_serde::from_slice::<T>(&data)
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Response, E> IntoRes<MsgPack, Response, E> for T
|
||||
impl<T, Response, Err> IntoRes<MsgPack, Response, Err> for T
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
Response: Res<Err>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
let data = rmp_serde::to_vec(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<Err>> {
|
||||
let data = rmp_serde::to_vec(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Response::try_from_bytes(MsgPack::CONTENT_TYPE, Bytes::from(data))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Response, E> FromRes<MsgPack, Response, E> for T
|
||||
impl<T, Response, Err> FromRes<MsgPack, Response, Err> for T
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
Response: ClientRes<Err> + Send,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<Err>> {
|
||||
let data = res.try_into_bytes().await?;
|
||||
rmp_serde::from_slice(&data).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
rmp_serde::from_slice(&data)
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{Encoding, FromReq};
|
||||
use crate::{
|
||||
error::FromServerFnError,
|
||||
error::ServerFnError,
|
||||
request::{browser::BrowserFormData, ClientReq, Req},
|
||||
IntoReq,
|
||||
};
|
||||
@@ -56,12 +56,16 @@ impl From<FormData> for MultipartData {
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<MultipartFormData, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<MultipartFormData, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E, FormData = BrowserFormData>,
|
||||
Request: ClientReq<CustErr, FormData = BrowserFormData>,
|
||||
T: Into<MultipartData>,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let multi = self.into();
|
||||
Request::try_new_multipart(
|
||||
path,
|
||||
@@ -71,20 +75,20 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<MultipartFormData, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<MultipartFormData, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: From<MultipartData>,
|
||||
E: FromServerFnError,
|
||||
CustErr: 'static,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let boundary = req
|
||||
.to_content_type()
|
||||
.and_then(|ct| multer::parse_boundary(ct).ok())
|
||||
.expect("couldn't parse boundary");
|
||||
let stream = req.try_into_stream()?;
|
||||
let data = multer::Multipart::new(
|
||||
stream.map(|data| data.map_err(|e| e.ser())),
|
||||
stream.map(|data| data.map_err(|e| e.to_string())),
|
||||
boundary,
|
||||
);
|
||||
Ok(MultipartData::Server(data).into())
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::ServerFnError,
|
||||
request::{ClientReq, Req},
|
||||
response::{ClientRes, TryRes},
|
||||
response::{ClientRes, Res},
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use http::Method;
|
||||
@@ -16,16 +16,18 @@ impl Encoding for Postcard {
|
||||
const METHOD: Method = Method::POST;
|
||||
}
|
||||
|
||||
impl<T, Request, E> IntoReq<Postcard, Request, E> for T
|
||||
impl<T, Request, Err> IntoReq<Postcard, Request, Err> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<Err>,
|
||||
T: Serialize,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
let data = postcard::to_allocvec(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<Err>> {
|
||||
let data = postcard::to_allocvec(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Request::try_new_post_bytes(
|
||||
path,
|
||||
Postcard::CONTENT_TYPE,
|
||||
@@ -35,43 +37,38 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Request, E> FromReq<Postcard, Request, E> for T
|
||||
impl<T, Request, Err> FromReq<Postcard, Request, Err> for T
|
||||
where
|
||||
Request: Req<E> + Send,
|
||||
Request: Req<Err> + Send,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<Err>> {
|
||||
let data = req.try_into_bytes().await?;
|
||||
postcard::from_bytes::<T>(&data)
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Response, E> IntoRes<Postcard, Response, E> for T
|
||||
impl<T, Response, Err> IntoRes<Postcard, Response, Err> for T
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
Response: Res<Err>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
let data = postcard::to_allocvec(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<Err>> {
|
||||
let data = postcard::to_allocvec(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Response::try_from_bytes(Postcard::CONTENT_TYPE, Bytes::from(data))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Response, E> FromRes<Postcard, Response, E> for T
|
||||
impl<T, Response, Err> FromRes<Postcard, Response, Err> for T
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
Response: ClientRes<Err> + Send,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<Err>> {
|
||||
let data = res.try_into_bytes().await?;
|
||||
postcard::from_bytes(&data).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
postcard::from_bytes(&data)
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::ServerFnError,
|
||||
request::{ClientReq, Req},
|
||||
response::{ClientRes, TryRes},
|
||||
response::{ClientRes, Res},
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures::StreamExt;
|
||||
@@ -29,38 +29,39 @@ impl Encoding for Rkyv {
|
||||
const METHOD: Method = Method::POST;
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<Rkyv, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<Rkyv, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<CustErr>,
|
||||
T: Archive + for<'a> Serialize<RkyvSerializer<'a>>,
|
||||
T::Archived: Deserialize<T, RkyvDeserializer>
|
||||
+ for<'a> CheckBytes<RkyvValidator<'a>>,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
let encoded = rkyv::to_bytes::<rancor::Error>(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let encoded = rkyv::to_bytes::<rancor::Error>(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
let bytes = Bytes::copy_from_slice(encoded.as_ref());
|
||||
Request::try_new_post_bytes(path, accepts, Rkyv::CONTENT_TYPE, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<Rkyv, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<Rkyv, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: Archive + for<'a> Serialize<RkyvSerializer<'a>>,
|
||||
T::Archived: Deserialize<T, RkyvDeserializer>
|
||||
+ for<'a> CheckBytes<RkyvValidator<'a>>,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let mut aligned = AlignedVec::<1024>::new();
|
||||
let mut body_stream = Box::pin(req.try_into_stream()?);
|
||||
while let Some(chunk) = body_stream.next().await {
|
||||
match chunk {
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
return Err(ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
Ok(bytes) => {
|
||||
for byte in bytes {
|
||||
@@ -70,40 +71,36 @@ where
|
||||
}
|
||||
}
|
||||
rkyv::from_bytes::<T, rancor::Error>(aligned.as_ref())
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> IntoRes<Rkyv, Response, E> for T
|
||||
impl<CustErr, T, Response> IntoRes<Rkyv, Response, CustErr> for T
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
Response: Res<CustErr>,
|
||||
T: Send,
|
||||
T: Archive + for<'a> Serialize<RkyvSerializer<'a>>,
|
||||
T::Archived: Deserialize<T, RkyvDeserializer>
|
||||
+ for<'a> CheckBytes<RkyvValidator<'a>>,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
let encoded = rkyv::to_bytes::<rancor::Error>(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(format!("{e:?}")).into_app_error()
|
||||
})?;
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<CustErr>> {
|
||||
let encoded = rkyv::to_bytes::<rancor::Error>(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(format!("{e:?}")))?;
|
||||
let bytes = Bytes::copy_from_slice(encoded.as_ref());
|
||||
Response::try_from_bytes(Rkyv::CONTENT_TYPE, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> FromRes<Rkyv, Response, E> for T
|
||||
impl<CustErr, T, Response> FromRes<Rkyv, Response, CustErr> for T
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
Response: ClientRes<CustErr> + Send,
|
||||
T: Archive + for<'a> Serialize<RkyvSerializer<'a>>,
|
||||
T::Archived: Deserialize<T, RkyvDeserializer>
|
||||
+ for<'a> CheckBytes<RkyvValidator<'a>>,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let data = res.try_into_bytes().await?;
|
||||
rkyv::from_bytes::<T, rancor::Error>(&data).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
rkyv::from_bytes::<T, rancor::Error>(&data)
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{Encoding, FromReq, FromRes};
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::ServerFnError,
|
||||
request::{ClientReq, Req},
|
||||
response::{ClientRes, TryRes},
|
||||
response::{ClientRes, Res},
|
||||
IntoReq, IntoRes,
|
||||
};
|
||||
use http::Method;
|
||||
@@ -15,68 +15,68 @@ impl Encoding for SerdeLite {
|
||||
const METHOD: Method = Method::POST;
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<SerdeLite, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<SerdeLite, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<CustErr>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
let data = serde_json::to_string(&self.serialize().map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let data = serde_json::to_string(
|
||||
&self
|
||||
.serialize()
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?,
|
||||
)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Request::try_new_post(path, accepts, SerdeLite::CONTENT_TYPE, data)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<SerdeLite, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<SerdeLite, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: Deserialize,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let string_data = req.try_into_string().await?;
|
||||
Self::deserialize(&serde_json::from_str(&string_data).map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
})?)
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
|
||||
Self::deserialize(
|
||||
&serde_json::from_str(&string_data)
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))?,
|
||||
)
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> IntoRes<SerdeLite, Response, E> for T
|
||||
impl<CustErr, T, Response> IntoRes<SerdeLite, Response, CustErr> for T
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
Response: Res<CustErr>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
let data = serde_json::to_string(&self.serialize().map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<CustErr>> {
|
||||
let data = serde_json::to_string(
|
||||
&self
|
||||
.serialize()
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?,
|
||||
)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Response::try_from_string(SerdeLite::CONTENT_TYPE, data)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Response> FromRes<SerdeLite, Response, E> for T
|
||||
impl<CustErr, T, Response> FromRes<SerdeLite, Response, CustErr> for T
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
Response: ClientRes<CustErr> + Send,
|
||||
T: Deserialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let data = res.try_into_string().await?;
|
||||
Self::deserialize(&serde_json::from_str(&data).map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
})?)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
Self::deserialize(
|
||||
&serde_json::from_str(&data)
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))?,
|
||||
)
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::{Encoding, FromReq, FromRes, IntoReq};
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::{NoCustomError, ServerFnError},
|
||||
request::{ClientReq, Req},
|
||||
response::{ClientRes, TryRes},
|
||||
IntoRes, ServerFnError,
|
||||
response::{ClientRes, Res},
|
||||
IntoRes,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, StreamExt};
|
||||
@@ -29,22 +29,26 @@ impl Encoding for Streaming {
|
||||
const METHOD: Method = Method::POST;
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<Streaming, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<Streaming, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<CustErr>,
|
||||
T: Stream<Item = Bytes> + Send + Sync + 'static,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
Request::try_new_streaming(path, accepts, Streaming::CONTENT_TYPE, self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<Streaming, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<Streaming, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
T: From<ByteStream<E>> + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: From<ByteStream> + 'static,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let data = req.try_into_stream()?;
|
||||
let s = ByteStream::new(data);
|
||||
Ok(s.into())
|
||||
@@ -63,25 +67,29 @@ where
|
||||
/// end before the output will begin.
|
||||
///
|
||||
/// Streaming requests are only allowed over HTTP2 or HTTP3.
|
||||
pub struct ByteStream<E>(Pin<Box<dyn Stream<Item = Result<Bytes, E>> + Send>>);
|
||||
pub struct ByteStream<CustErr = NoCustomError>(
|
||||
Pin<Box<dyn Stream<Item = Result<Bytes, ServerFnError<CustErr>>> + Send>>,
|
||||
);
|
||||
|
||||
impl<E> ByteStream<E> {
|
||||
impl<CustErr> ByteStream<CustErr> {
|
||||
/// Consumes the wrapper, returning a stream of bytes.
|
||||
pub fn into_inner(self) -> impl Stream<Item = Result<Bytes, E>> + Send {
|
||||
pub fn into_inner(
|
||||
self,
|
||||
) -> impl Stream<Item = Result<Bytes, ServerFnError<CustErr>>> + Send {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> Debug for ByteStream<E> {
|
||||
impl<CustErr> Debug for ByteStream<CustErr> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("ByteStream").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> ByteStream<E> {
|
||||
impl ByteStream {
|
||||
/// Creates a new `ByteStream` from the given stream.
|
||||
pub fn new<T>(
|
||||
value: impl Stream<Item = Result<T, E>> + Send + 'static,
|
||||
value: impl Stream<Item = Result<T, ServerFnError>> + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
T: Into<Bytes>,
|
||||
@@ -90,7 +98,7 @@ impl<E> ByteStream<E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, S, T> From<S> for ByteStream<E>
|
||||
impl<S, T> From<S> for ByteStream
|
||||
where
|
||||
S: Stream<Item = T> + Send + 'static,
|
||||
T: Into<Bytes>,
|
||||
@@ -100,21 +108,22 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, Response> IntoRes<Streaming, Response, E> for ByteStream<E>
|
||||
impl<CustErr, Response> IntoRes<Streaming, Response, CustErr>
|
||||
for ByteStream<CustErr>
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
E: 'static,
|
||||
Response: Res<CustErr>,
|
||||
CustErr: 'static,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<CustErr>> {
|
||||
Response::try_from_stream(Streaming::CONTENT_TYPE, self.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, Response> FromRes<Streaming, Response, E> for ByteStream<E>
|
||||
impl<CustErr, Response> FromRes<Streaming, Response, CustErr> for ByteStream
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
Response: ClientRes<CustErr> + Send,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let stream = res.try_into_stream()?;
|
||||
Ok(ByteStream(Box::pin(stream)))
|
||||
}
|
||||
@@ -151,33 +160,35 @@ impl Encoding for StreamingText {
|
||||
/// end before the output will begin.
|
||||
///
|
||||
/// Streaming requests are only allowed over HTTP2 or HTTP3.
|
||||
pub struct TextStream<E = ServerFnError>(
|
||||
Pin<Box<dyn Stream<Item = Result<String, E>> + Send>>,
|
||||
pub struct TextStream<CustErr = NoCustomError>(
|
||||
Pin<Box<dyn Stream<Item = Result<String, ServerFnError<CustErr>>> + Send>>,
|
||||
);
|
||||
|
||||
impl<E> Debug for TextStream<E> {
|
||||
impl<CustErr> Debug for TextStream<CustErr> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("TextStream").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> TextStream<E> {
|
||||
impl TextStream {
|
||||
/// Creates a new `ByteStream` from the given stream.
|
||||
pub fn new(
|
||||
value: impl Stream<Item = Result<String, E>> + Send + 'static,
|
||||
value: impl Stream<Item = Result<String, ServerFnError>> + Send + 'static,
|
||||
) -> Self {
|
||||
Self(Box::pin(value.map(|value| value)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> TextStream<E> {
|
||||
impl<CustErr> TextStream<CustErr> {
|
||||
/// Consumes the wrapper, returning a stream of text.
|
||||
pub fn into_inner(self) -> impl Stream<Item = Result<String, E>> + Send {
|
||||
pub fn into_inner(
|
||||
self,
|
||||
) -> impl Stream<Item = Result<String, ServerFnError<CustErr>>> + Send {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, S, T> From<S> for TextStream<E>
|
||||
impl<S, T> From<S> for TextStream
|
||||
where
|
||||
S: Stream<Item = T> + Send + 'static,
|
||||
T: Into<String>,
|
||||
@@ -187,13 +198,16 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<StreamingText, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<StreamingText, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
T: Into<TextStream<E>>,
|
||||
E: 'static,
|
||||
Request: ClientReq<CustErr>,
|
||||
T: Into<TextStream>,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let data = self.into();
|
||||
Request::try_new_streaming(
|
||||
path,
|
||||
@@ -204,32 +218,30 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<StreamingText, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<StreamingText, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
T: From<TextStream<E>> + 'static,
|
||||
E: FromServerFnError,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: From<TextStream> + 'static,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let data = req.try_into_stream()?;
|
||||
let s = TextStream::new(data.map(|chunk| {
|
||||
chunk.and_then(|bytes| {
|
||||
String::from_utf8(bytes.to_vec()).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
String::from_utf8(bytes.to_vec())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
})
|
||||
}));
|
||||
Ok(s.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, Response> IntoRes<StreamingText, Response, E> for TextStream<E>
|
||||
impl<CustErr, Response> IntoRes<StreamingText, Response, CustErr>
|
||||
for TextStream<CustErr>
|
||||
where
|
||||
Response: TryRes<E>,
|
||||
E: 'static,
|
||||
Response: Res<CustErr>,
|
||||
CustErr: 'static,
|
||||
{
|
||||
async fn into_res(self) -> Result<Response, E> {
|
||||
async fn into_res(self) -> Result<Response, ServerFnError<CustErr>> {
|
||||
Response::try_from_stream(
|
||||
Streaming::CONTENT_TYPE,
|
||||
self.into_inner().map(|stream| stream.map(Into::into)),
|
||||
@@ -237,19 +249,16 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, Response> FromRes<StreamingText, Response, E> for TextStream<E>
|
||||
impl<CustErr, Response> FromRes<StreamingText, Response, CustErr> for TextStream
|
||||
where
|
||||
Response: ClientRes<E> + Send,
|
||||
E: FromServerFnError,
|
||||
Response: ClientRes<CustErr> + Send,
|
||||
{
|
||||
async fn from_res(res: Response) -> Result<Self, E> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let stream = res.try_into_stream()?;
|
||||
Ok(TextStream(Box::pin(stream.map(|chunk| {
|
||||
chunk.and_then(|bytes| {
|
||||
String::from_utf8(bytes.into()).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
String::from_utf8(bytes.into())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
})
|
||||
}))))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{Encoding, FromReq, IntoReq};
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
error::ServerFnError,
|
||||
request::{ClientReq, Req},
|
||||
};
|
||||
use http::Method;
|
||||
@@ -17,33 +17,32 @@ impl Encoding for GetUrl {
|
||||
const METHOD: Method = Method::GET;
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<GetUrl, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<GetUrl, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<CustErr>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
let data = serde_qs::to_string(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let data = serde_qs::to_string(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Request::try_new_get(path, accepts, GetUrl::CONTENT_TYPE, &data)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<GetUrl, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<GetUrl, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let string_data = req.as_query().unwrap_or_default();
|
||||
let args = serde_qs::Config::new(5, false)
|
||||
.deserialize_str::<Self>(string_data)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
})?;
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))?;
|
||||
Ok(args)
|
||||
}
|
||||
}
|
||||
@@ -53,33 +52,32 @@ impl Encoding for PostUrl {
|
||||
const METHOD: Method = Method::POST;
|
||||
}
|
||||
|
||||
impl<E, T, Request> IntoReq<PostUrl, Request, E> for T
|
||||
impl<CustErr, T, Request> IntoReq<PostUrl, Request, CustErr> for T
|
||||
where
|
||||
Request: ClientReq<E>,
|
||||
Request: ClientReq<CustErr>,
|
||||
T: Serialize + Send,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
|
||||
let qs = serde_qs::to_string(&self).map_err(|e| {
|
||||
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
|
||||
})?;
|
||||
fn into_req(
|
||||
self,
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
) -> Result<Request, ServerFnError<CustErr>> {
|
||||
let qs = serde_qs::to_string(&self)
|
||||
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
|
||||
Request::try_new_post(path, accepts, PostUrl::CONTENT_TYPE, qs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T, Request> FromReq<PostUrl, Request, E> for T
|
||||
impl<CustErr, T, Request> FromReq<PostUrl, Request, CustErr> for T
|
||||
where
|
||||
Request: Req<E> + Send + 'static,
|
||||
Request: Req<CustErr> + Send + 'static,
|
||||
T: DeserializeOwned,
|
||||
E: FromServerFnError,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let string_data = req.try_into_string().await?;
|
||||
let args = serde_qs::Config::new(5, false)
|
||||
.deserialize_str::<Self>(&string_data)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
})?;
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))?;
|
||||
Ok(args)
|
||||
}
|
||||
}
|
||||
@@ -88,18 +86,18 @@ where
|
||||
impl<T, Request, Response> Codec<Request, Response, GetUrlJson> for T
|
||||
where
|
||||
T: DeserializeOwned + Serialize + Send,
|
||||
Request: Req<E> + Send,
|
||||
Response: Res<E> + Send,
|
||||
Request: Req<CustErr> + Send,
|
||||
Response: Res<CustErr> + Send,
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<E>> {
|
||||
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let string_data = req.try_into_string()?;
|
||||
|
||||
let args = serde_json::from_str::<Self>(&string_data)
|
||||
.map_err(|e| ServerFnErrorErr::Args(e.to_string()).into())?;
|
||||
.map_err(|e| ServerFnError::Args(e.to_string()))?;
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
async fn into_req(self) -> Result<Request, ServerFnError<E>> {
|
||||
async fn into_req(self) -> Result<Request, ServerFnError<CustErr>> {
|
||||
/* let qs = serde_qs::to_string(&self)?;
|
||||
let req = http::Request::builder()
|
||||
.method("GET")
|
||||
@@ -112,7 +110,7 @@ where
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<E>> {
|
||||
async fn from_res(res: Response) -> Result<Self, ServerFnError<CustErr>> {
|
||||
todo!()
|
||||
/* let (_parts, body) = res.into_parts();
|
||||
|
||||
@@ -120,7 +118,7 @@ where
|
||||
.collect()
|
||||
.await
|
||||
.map(|c| c.to_bytes())
|
||||
.map_err(|e| ServerFnErrorErr::Deserialization(e.to_string()).into())?;
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))?;
|
||||
let string_data = String::from_utf8(body_bytes.to_vec())?;
|
||||
serde_json::from_str(&string_data)
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string())) */
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
#![allow(deprecated)]
|
||||
|
||||
use base64::{engine::general_purpose::URL_SAFE, Engine as _};
|
||||
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fmt::{self, Display, Write},
|
||||
fmt,
|
||||
fmt::{Display, Write},
|
||||
str::FromStr,
|
||||
};
|
||||
use thiserror::Error;
|
||||
@@ -15,7 +13,7 @@ pub const SERVER_FN_ERROR_HEADER: &str = "serverfnerror";
|
||||
|
||||
impl From<ServerFnError> for Error {
|
||||
fn from(e: ServerFnError) -> Self {
|
||||
Error::from(ServerFnErrorWrapper(e))
|
||||
Error::from(ServerFnErrorErr::from(e))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,11 +35,6 @@ impl From<ServerFnError> for Error {
|
||||
feature = "rkyv",
|
||||
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
|
||||
)]
|
||||
#[deprecated(
|
||||
since = "0.8.0",
|
||||
note = "Now server_fn can return any error type other than ServerFnError, \
|
||||
so the WrappedServerError variant will be removed in 0.9.0"
|
||||
)]
|
||||
pub struct NoCustomError;
|
||||
|
||||
// Implement `Display` for `NoCustomError`
|
||||
@@ -62,21 +55,11 @@ impl FromStr for NoCustomError {
|
||||
/// Wraps some error type, which may implement any of [`Error`](trait@std::error::Error), [`Clone`], or
|
||||
/// [`Display`].
|
||||
#[derive(Debug)]
|
||||
#[deprecated(
|
||||
since = "0.8.0",
|
||||
note = "Now server_fn can return any error type other than ServerFnError, \
|
||||
so the WrappedServerError variant will be removed in 0.9.0"
|
||||
)]
|
||||
pub struct WrapError<T>(pub T);
|
||||
|
||||
/// A helper macro to convert a variety of different types into `ServerFnError`.
|
||||
/// This should mostly be used if you are implementing `From<ServerFnError>` for `YourError`.
|
||||
#[macro_export]
|
||||
#[deprecated(
|
||||
since = "0.8.0",
|
||||
note = "Now server_fn can return any error type other than ServerFnError, \
|
||||
so the WrappedServerError variant will be removed in 0.9.0"
|
||||
)]
|
||||
macro_rules! server_fn_error {
|
||||
() => {{
|
||||
use $crate::{ViaError, WrapError};
|
||||
@@ -92,12 +75,6 @@ macro_rules! server_fn_error {
|
||||
|
||||
/// This trait serves as the conversion method between a variety of types
|
||||
/// and [`ServerFnError`].
|
||||
#[deprecated(
|
||||
since = "0.8.0",
|
||||
note = "Now server_fn can return any error type other than ServerFnError, \
|
||||
so users should place their custom error type instead of \
|
||||
ServerFnError"
|
||||
)]
|
||||
pub trait ViaError<E> {
|
||||
/// Converts something into an error.
|
||||
fn to_server_error(&self) -> ServerFnError<E>;
|
||||
@@ -113,7 +90,6 @@ impl<E: ServerFnErrorKind + std::error::Error + Clone> ViaError<E>
|
||||
}
|
||||
|
||||
// A type tag for ServerFnError so we can special case it
|
||||
#[deprecated]
|
||||
pub(crate) trait ServerFnErrorKind {}
|
||||
|
||||
impl ServerFnErrorKind for ServerFnError {}
|
||||
@@ -155,8 +131,7 @@ impl<E> ViaError<E> for WrapError<E> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that can be used as the return type of the server function for easy error conversion with `?` operator.
|
||||
/// This type can be replaced with any other error type that implements `FromServerFnError`.
|
||||
/// Type for errors that can occur when using server functions.
|
||||
///
|
||||
/// Unlike [`ServerFnErrorErr`], this does not implement [`Error`](trait@std::error::Error).
|
||||
/// This means that other error types can easily be converted into it using the
|
||||
@@ -167,12 +142,6 @@ impl<E> ViaError<E> for WrapError<E> {
|
||||
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
|
||||
)]
|
||||
pub enum ServerFnError<E = NoCustomError> {
|
||||
#[deprecated(
|
||||
since = "0.8.0",
|
||||
note = "Now server_fn can return any error type other than \
|
||||
ServerFnError, so users should place their custom error type \
|
||||
instead of ServerFnError"
|
||||
)]
|
||||
/// A user-defined custom error type, which defaults to [`NoCustomError`].
|
||||
WrappedServerError(E),
|
||||
/// Error while trying to register the server function (only occurs in case of poisoned RwLock).
|
||||
@@ -183,8 +152,6 @@ pub enum ServerFnError<E = NoCustomError> {
|
||||
Response(String),
|
||||
/// Occurs when there is an error while actually running the function on the server.
|
||||
ServerError(String),
|
||||
/// Occurs when there is an error while actually running the middleware on the server.
|
||||
MiddlewareError(String),
|
||||
/// Occurs on the client if there is an error deserializing the server's response.
|
||||
Deserialization(String),
|
||||
/// Occurs on the client if there is an error serializing the server function arguments.
|
||||
@@ -231,8 +198,6 @@ where
|
||||
),
|
||||
ServerFnError::ServerError(s) =>
|
||||
format!("error running server function: {s}"),
|
||||
ServerFnError::MiddlewareError(s) =>
|
||||
format!("error running middleware: {s}"),
|
||||
ServerFnError::Deserialization(s) =>
|
||||
format!("error deserializing server function results: {s}"),
|
||||
ServerFnError::Serialization(s) =>
|
||||
@@ -249,45 +214,30 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<CustErr> FromServerFnError for ServerFnError<CustErr>
|
||||
where
|
||||
CustErr: std::fmt::Debug
|
||||
+ Display
|
||||
+ Serialize
|
||||
+ DeserializeOwned
|
||||
+ 'static
|
||||
+ FromStr
|
||||
+ Display,
|
||||
{
|
||||
fn from_server_fn_error(value: ServerFnErrorErr) -> Self {
|
||||
match value {
|
||||
ServerFnErrorErr::Registration(value) => {
|
||||
ServerFnError::Registration(value)
|
||||
}
|
||||
ServerFnErrorErr::Request(value) => ServerFnError::Request(value),
|
||||
ServerFnErrorErr::ServerError(value) => {
|
||||
ServerFnError::ServerError(value)
|
||||
}
|
||||
ServerFnErrorErr::MiddlewareError(value) => {
|
||||
ServerFnError::MiddlewareError(value)
|
||||
}
|
||||
ServerFnErrorErr::Deserialization(value) => {
|
||||
ServerFnError::Deserialization(value)
|
||||
}
|
||||
ServerFnErrorErr::Serialization(value) => {
|
||||
ServerFnError::Serialization(value)
|
||||
}
|
||||
ServerFnErrorErr::Args(value) => ServerFnError::Args(value),
|
||||
ServerFnErrorErr::MissingArg(value) => {
|
||||
ServerFnError::MissingArg(value)
|
||||
}
|
||||
ServerFnErrorErr::Response(value) => ServerFnError::Response(value),
|
||||
}
|
||||
}
|
||||
/// A serializable custom server function error type.
|
||||
///
|
||||
/// This is implemented for all types that implement [`FromStr`] + [`Display`].
|
||||
///
|
||||
/// This means you do not necessarily need the overhead of `serde` for a custom error type.
|
||||
/// Instead, you can use something like `strum` to derive `FromStr` and `Display` for your
|
||||
/// custom error type.
|
||||
///
|
||||
/// This is implemented for the default [`ServerFnError`], which uses [`NoCustomError`].
|
||||
pub trait ServerFnErrorSerde: Sized {
|
||||
/// Converts the custom error type to a [`String`].
|
||||
fn ser(&self) -> Result<String, std::fmt::Error>;
|
||||
|
||||
fn ser(&self) -> String {
|
||||
/// Deserializes the custom error type from a [`String`].
|
||||
fn de(data: &str) -> Self;
|
||||
}
|
||||
|
||||
impl<CustErr> ServerFnErrorSerde for ServerFnError<CustErr>
|
||||
where
|
||||
CustErr: FromStr + Display,
|
||||
{
|
||||
fn ser(&self) -> Result<String, std::fmt::Error> {
|
||||
let mut buf = String::new();
|
||||
let result = match self {
|
||||
match self {
|
||||
ServerFnError::WrappedServerError(e) => {
|
||||
write!(&mut buf, "WrappedServerFn|{e}")
|
||||
}
|
||||
@@ -299,9 +249,6 @@ where
|
||||
ServerFnError::ServerError(e) => {
|
||||
write!(&mut buf, "ServerError|{e}")
|
||||
}
|
||||
ServerFnError::MiddlewareError(e) => {
|
||||
write!(&mut buf, "MiddlewareError|{e}")
|
||||
}
|
||||
ServerFnError::Deserialization(e) => {
|
||||
write!(&mut buf, "Deserialization|{e}")
|
||||
}
|
||||
@@ -312,11 +259,8 @@ where
|
||||
ServerFnError::MissingArg(e) => {
|
||||
write!(&mut buf, "MissingArg|{e}")
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(()) => buf,
|
||||
Err(_) => "Serialization|".to_string(),
|
||||
}
|
||||
}?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
fn de(data: &str) -> Self {
|
||||
@@ -367,13 +311,20 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Type for errors that can occur when using server functions. If you need to return a custom error type from a server function, implement `FromServerFnError` for your custom error type.
|
||||
#[derive(Error, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[cfg_attr(
|
||||
feature = "rkyv",
|
||||
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
|
||||
)]
|
||||
pub enum ServerFnErrorErr {
|
||||
/// Type for errors that can occur when using server functions.
|
||||
///
|
||||
/// Unlike [`ServerFnError`], this implements [`std::error::Error`]. This means
|
||||
/// it can be used in situations in which the `Error` trait is required, but it’s
|
||||
/// not possible to create a blanket implementation that converts other errors into
|
||||
/// this type.
|
||||
///
|
||||
/// [`ServerFnError`] and [`ServerFnErrorErr`] mutually implement [`From`], so
|
||||
/// it is easy to convert between the two types.
|
||||
#[derive(Error, Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ServerFnErrorErr<E = NoCustomError> {
|
||||
/// A user-defined custom error type, which defaults to [`NoCustomError`].
|
||||
#[error("internal error: {0}")]
|
||||
WrappedServerError(E),
|
||||
/// Error while trying to register the server function (only occurs in case of poisoned RwLock).
|
||||
#[error("error while trying to register the server function: {0}")]
|
||||
Registration(String),
|
||||
@@ -383,9 +334,6 @@ pub enum ServerFnErrorErr {
|
||||
/// Occurs when there is an error while actually running the function on the server.
|
||||
#[error("error running server function: {0}")]
|
||||
ServerError(String),
|
||||
/// Occurs when there is an error while actually running the middleware on the server.
|
||||
#[error("error running middleware: {0}")]
|
||||
MiddlewareError(String),
|
||||
/// Occurs on the client if there is an error deserializing the server's response.
|
||||
#[error("error deserializing server function results: {0}")]
|
||||
Deserialization(String),
|
||||
@@ -403,6 +351,34 @@ pub enum ServerFnErrorErr {
|
||||
Response(String),
|
||||
}
|
||||
|
||||
impl<CustErr> From<ServerFnError<CustErr>> for ServerFnErrorErr<CustErr> {
|
||||
fn from(value: ServerFnError<CustErr>) -> Self {
|
||||
match value {
|
||||
ServerFnError::Registration(value) => {
|
||||
ServerFnErrorErr::Registration(value)
|
||||
}
|
||||
ServerFnError::Request(value) => ServerFnErrorErr::Request(value),
|
||||
ServerFnError::ServerError(value) => {
|
||||
ServerFnErrorErr::ServerError(value)
|
||||
}
|
||||
ServerFnError::Deserialization(value) => {
|
||||
ServerFnErrorErr::Deserialization(value)
|
||||
}
|
||||
ServerFnError::Serialization(value) => {
|
||||
ServerFnErrorErr::Serialization(value)
|
||||
}
|
||||
ServerFnError::Args(value) => ServerFnErrorErr::Args(value),
|
||||
ServerFnError::MissingArg(value) => {
|
||||
ServerFnErrorErr::MissingArg(value)
|
||||
}
|
||||
ServerFnError::WrappedServerError(value) => {
|
||||
ServerFnErrorErr::WrappedServerError(value)
|
||||
}
|
||||
ServerFnError::Response(value) => ServerFnErrorErr::Response(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Associates a particular server function error with the server function
|
||||
/// found at a particular path.
|
||||
///
|
||||
@@ -410,15 +386,15 @@ pub enum ServerFnErrorErr {
|
||||
/// without JavaScript/WASM supported, by encoding it in the URL as a query string.
|
||||
/// This is useful for progressive enhancement.
|
||||
#[derive(Debug)]
|
||||
pub struct ServerFnUrlError<E> {
|
||||
pub struct ServerFnUrlError<CustErr> {
|
||||
path: String,
|
||||
error: E,
|
||||
error: ServerFnError<CustErr>,
|
||||
}
|
||||
|
||||
impl<E: FromServerFnError> ServerFnUrlError<E> {
|
||||
impl<CustErr> ServerFnUrlError<CustErr> {
|
||||
/// Creates a new structure associating the server function at some path
|
||||
/// with a particular error.
|
||||
pub fn new(path: impl Display, error: E) -> Self {
|
||||
pub fn new(path: impl Display, error: ServerFnError<CustErr>) -> Self {
|
||||
Self {
|
||||
path: path.to_string(),
|
||||
error,
|
||||
@@ -426,7 +402,7 @@ impl<E: FromServerFnError> ServerFnUrlError<E> {
|
||||
}
|
||||
|
||||
/// The error itself.
|
||||
pub fn error(&self) -> &E {
|
||||
pub fn error(&self) -> &ServerFnError<CustErr> {
|
||||
&self.error
|
||||
}
|
||||
|
||||
@@ -436,11 +412,17 @@ impl<E: FromServerFnError> ServerFnUrlError<E> {
|
||||
}
|
||||
|
||||
/// Adds an encoded form of this server function error to the given base URL.
|
||||
pub fn to_url(&self, base: &str) -> Result<Url, url::ParseError> {
|
||||
pub fn to_url(&self, base: &str) -> Result<Url, url::ParseError>
|
||||
where
|
||||
CustErr: FromStr + Display,
|
||||
{
|
||||
let mut url = Url::parse(base)?;
|
||||
url.query_pairs_mut()
|
||||
.append_pair("__path", &self.path)
|
||||
.append_pair("__err", &URL_SAFE.encode(self.error.ser()));
|
||||
.append_pair(
|
||||
"__err",
|
||||
&ServerFnErrorSerde::ser(&self.error).unwrap_or_default(),
|
||||
);
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
@@ -466,102 +448,16 @@ impl<E: FromServerFnError> ServerFnUrlError<E> {
|
||||
*path = url.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes an error from a URL.
|
||||
pub fn decode_err(err: &str) -> E {
|
||||
let decoded = match URL_SAFE.decode(err) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(err) => {
|
||||
return ServerFnErrorErr::Deserialization(err.to_string())
|
||||
.into_app_error();
|
||||
}
|
||||
};
|
||||
let s = match String::from_utf8(decoded) {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
return ServerFnErrorErr::Deserialization(err.to_string())
|
||||
.into_app_error();
|
||||
}
|
||||
};
|
||||
E::de(&s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> From<ServerFnUrlError<E>> for ServerFnError<E> {
|
||||
fn from(error: ServerFnUrlError<E>) -> Self {
|
||||
error.error.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> From<ServerFnUrlError<ServerFnError<E>>> for ServerFnError<E> {
|
||||
fn from(error: ServerFnUrlError<ServerFnError<E>>) -> Self {
|
||||
impl<CustErr> From<ServerFnUrlError<CustErr>> for ServerFnError<CustErr> {
|
||||
fn from(error: ServerFnUrlError<CustErr>) -> Self {
|
||||
error.error
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[doc(hidden)]
|
||||
/// Only used instantly only when a framework needs E: Error.
|
||||
pub struct ServerFnErrorWrapper<E: FromServerFnError>(pub E);
|
||||
|
||||
impl<E: FromServerFnError> Display for ServerFnErrorWrapper<E> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0.ser())
|
||||
impl<CustErr> From<ServerFnUrlError<CustErr>> for ServerFnErrorErr<CustErr> {
|
||||
fn from(error: ServerFnUrlError<CustErr>) -> Self {
|
||||
error.error.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: FromServerFnError> std::error::Error for ServerFnErrorWrapper<E> {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for types that can be returned from a server function.
|
||||
pub trait FromServerFnError:
|
||||
std::fmt::Debug + Serialize + DeserializeOwned + 'static
|
||||
{
|
||||
/// Converts a [`ServerFnErrorErr`] into the application-specific custom error type.
|
||||
fn from_server_fn_error(value: ServerFnErrorErr) -> Self;
|
||||
|
||||
/// Converts the custom error type to a [`String`]. Defaults to serializing to JSON.
|
||||
fn ser(&self) -> String {
|
||||
serde_json::to_string(self).unwrap_or_else(|e| {
|
||||
serde_json::to_string(&Self::from_server_fn_error(
|
||||
ServerFnErrorErr::Serialization(e.to_string()),
|
||||
))
|
||||
.expect(
|
||||
"error serializing should success at least with the \
|
||||
Serialization error",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Deserializes the custom error type from a [`&str`]. Defaults to deserializing from JSON.
|
||||
fn de(data: &str) -> Self {
|
||||
serde_json::from_str(data).unwrap_or_else(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A helper trait for converting a [`ServerFnErrorErr`] into an application-specific custom error type that implements [`FromServerFnError`].
|
||||
pub trait IntoAppError<E> {
|
||||
/// Converts a [`ServerFnErrorErr`] into the application-specific custom error type.
|
||||
fn into_app_error(self) -> E;
|
||||
}
|
||||
|
||||
impl<E> IntoAppError<E> for ServerFnErrorErr
|
||||
where
|
||||
E: FromServerFnError,
|
||||
{
|
||||
fn into_app_error(self) -> E {
|
||||
E::from_server_fn_error(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assert_from_server_fn_error_impl() {
|
||||
fn assert_impl<T: FromServerFnError>() {}
|
||||
|
||||
assert_impl::<ServerFnError>();
|
||||
}
|
||||
|
||||
@@ -130,19 +130,17 @@ use client::Client;
|
||||
use codec::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
|
||||
#[doc(hidden)]
|
||||
pub use const_format;
|
||||
#[doc(hidden)]
|
||||
pub use const_str;
|
||||
use dashmap::DashMap;
|
||||
pub use error::ServerFnError;
|
||||
use error::ServerFnErrorSerde;
|
||||
#[cfg(feature = "form-redirects")]
|
||||
use error::ServerFnUrlError;
|
||||
use error::{FromServerFnError, ServerFnErrorErr};
|
||||
use http::Method;
|
||||
use middleware::{BoxedService, Layer, Service};
|
||||
use middleware::{Layer, Service};
|
||||
use once_cell::sync::Lazy;
|
||||
use redirect::RedirectHook;
|
||||
use request::Req;
|
||||
use response::{ClientRes, Res, TryRes};
|
||||
use response::{ClientRes, Res};
|
||||
#[cfg(feature = "rkyv")]
|
||||
pub use rkyv;
|
||||
#[doc(hidden)]
|
||||
@@ -150,7 +148,7 @@ pub use serde;
|
||||
#[doc(hidden)]
|
||||
#[cfg(feature = "serde-lite")]
|
||||
pub use serde_lite;
|
||||
use std::{future::Future, pin::Pin, sync::Arc};
|
||||
use std::{fmt::Display, future::Future, pin::Pin, str::FromStr, sync::Arc};
|
||||
#[doc(hidden)]
|
||||
pub use xxhash_rust;
|
||||
|
||||
@@ -205,7 +203,7 @@ where
|
||||
type ServerRequest: Req<Self::Error> + Send;
|
||||
|
||||
/// The type of the HTTP response returned by the server function on the server side.
|
||||
type ServerResponse: Res + TryRes<Self::Error> + Send;
|
||||
type ServerResponse: Res<Self::Error> + Send;
|
||||
|
||||
/// The return type of the server function.
|
||||
///
|
||||
@@ -224,8 +222,9 @@ where
|
||||
/// The [`Encoding`] used in the response for the result of the server function.
|
||||
type OutputEncoding: Encoding;
|
||||
|
||||
/// The type of the error on the server function. Typically [`ServerFnError`], but allowed to be any type that implements [`FromServerFnError`].
|
||||
type Error: FromServerFnError;
|
||||
/// The type of the custom error on [`ServerFnError`], if any. (If there is no
|
||||
/// custom error type, this can be `NoCustomError` by default.)
|
||||
type Error: FromStr + Display;
|
||||
|
||||
/// Returns [`Self::PATH`].
|
||||
fn url() -> &'static str {
|
||||
@@ -241,7 +240,7 @@ where
|
||||
/// The body of the server function. This will only run on the server.
|
||||
fn run_body(
|
||||
self,
|
||||
) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send;
|
||||
) -> impl Future<Output = Result<Self::Output, ServerFnError<Self::Error>>> + Send;
|
||||
|
||||
#[doc(hidden)]
|
||||
fn run_on_server(
|
||||
@@ -266,10 +265,7 @@ where
|
||||
.map(|res| (res, None))
|
||||
.unwrap_or_else(|e| {
|
||||
(
|
||||
Self::ServerResponse::error_response(
|
||||
Self::PATH,
|
||||
e.ser(),
|
||||
),
|
||||
Self::ServerResponse::error_response(Self::PATH, &e),
|
||||
Some(e),
|
||||
)
|
||||
});
|
||||
@@ -302,7 +298,8 @@ where
|
||||
#[doc(hidden)]
|
||||
fn run_on_client(
|
||||
self,
|
||||
) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send {
|
||||
) -> impl Future<Output = Result<Self::Output, ServerFnError<Self::Error>>> + Send
|
||||
{
|
||||
async move {
|
||||
// create and send request on client
|
||||
let req =
|
||||
@@ -316,7 +313,8 @@ where
|
||||
fn run_on_client_with_req(
|
||||
req: <Self::Client as Client<Self::Error>>::Request,
|
||||
redirect_hook: Option<&RedirectHook>,
|
||||
) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send {
|
||||
) -> impl Future<Output = Result<Self::Output, ServerFnError<Self::Error>>> + Send
|
||||
{
|
||||
async move {
|
||||
let res = Self::Client::send(req).await?;
|
||||
|
||||
@@ -327,7 +325,7 @@ where
|
||||
// if it returns an error status, deserialize the error using FromStr
|
||||
let res = if (400..=599).contains(&status) {
|
||||
let text = res.try_into_string().await?;
|
||||
Err(Self::Error::de(&text))
|
||||
Err(ServerFnError::<Self::Error>::de(&text))
|
||||
} else {
|
||||
// otherwise, deserialize the body as is
|
||||
Ok(Self::Output::from_res(res).await)
|
||||
@@ -347,8 +345,9 @@ where
|
||||
#[doc(hidden)]
|
||||
fn execute_on_server(
|
||||
req: Self::ServerRequest,
|
||||
) -> impl Future<Output = Result<Self::ServerResponse, Self::Error>> + Send
|
||||
{
|
||||
) -> impl Future<
|
||||
Output = Result<Self::ServerResponse, ServerFnError<Self::Error>>,
|
||||
> + Send {
|
||||
async {
|
||||
let this = Self::from_req(req).await?;
|
||||
let output = this.run_body().await?;
|
||||
@@ -388,20 +387,21 @@ pub struct ServerFnTraitObj<Req, Res> {
|
||||
method: Method,
|
||||
handler: fn(Req) -> Pin<Box<dyn Future<Output = Res> + Send>>,
|
||||
middleware: fn() -> MiddlewareSet<Req, Res>,
|
||||
ser: fn(ServerFnErrorErr) -> String,
|
||||
}
|
||||
|
||||
impl<Req, Res> ServerFnTraitObj<Req, Res> {
|
||||
/// Converts the relevant parts of a server function into a trait object.
|
||||
pub const fn new<S: ServerFn<ServerRequest = Req, ServerResponse = Res>>(
|
||||
pub const fn new(
|
||||
path: &'static str,
|
||||
method: Method,
|
||||
handler: fn(Req) -> Pin<Box<dyn Future<Output = Res> + Send>>,
|
||||
middleware: fn() -> MiddlewareSet<Req, Res>,
|
||||
) -> Self {
|
||||
Self {
|
||||
path: S::PATH,
|
||||
method: S::InputEncoding::METHOD,
|
||||
path,
|
||||
method,
|
||||
handler,
|
||||
middleware: S::middlewares,
|
||||
ser: |e| S::Error::from_server_fn_error(e).ser(),
|
||||
middleware,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,16 +424,6 @@ impl<Req, Res> ServerFnTraitObj<Req, Res> {
|
||||
pub fn middleware(&self) -> MiddlewareSet<Req, Res> {
|
||||
(self.middleware)()
|
||||
}
|
||||
|
||||
/// Converts the server function into a boxed service.
|
||||
pub fn boxed(self) -> BoxedService<Req, Res>
|
||||
where
|
||||
Self: Service<Req, Res>,
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
{
|
||||
BoxedService::new(self.ser, self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Req, Res> Service<Req, Res> for ServerFnTraitObj<Req, Res>
|
||||
@@ -441,11 +431,7 @@ where
|
||||
Req: Send + 'static,
|
||||
Res: 'static,
|
||||
{
|
||||
fn run(
|
||||
&mut self,
|
||||
req: Req,
|
||||
_ser: fn(ServerFnErrorErr) -> String,
|
||||
) -> Pin<Box<dyn Future<Output = Res> + Send>> {
|
||||
fn run(&mut self, req: Req) -> Pin<Box<dyn Future<Output = Res> + Send>> {
|
||||
let handler = self.handler;
|
||||
Box::pin(async move { handler(req).await })
|
||||
}
|
||||
@@ -458,7 +444,6 @@ impl<Req, Res> Clone for ServerFnTraitObj<Req, Res> {
|
||||
method: self.method.clone(),
|
||||
handler: self.handler,
|
||||
middleware: self.middleware,
|
||||
ser: self.ser,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -482,8 +467,8 @@ impl<Req: 'static, Res: 'static> inventory::Collect
|
||||
#[cfg(feature = "axum-no-default")]
|
||||
pub mod axum {
|
||||
use crate::{
|
||||
middleware::BoxedService, Encoding, LazyServerFnMap, ServerFn,
|
||||
ServerFnTraitObj,
|
||||
middleware::{BoxedService, Service},
|
||||
Encoding, LazyServerFnMap, ServerFn, ServerFnTraitObj,
|
||||
};
|
||||
use axum::body::Body;
|
||||
use http::{Method, Request, Response, StatusCode};
|
||||
@@ -505,7 +490,12 @@ pub mod axum {
|
||||
{
|
||||
REGISTERED_SERVER_FUNCTIONS.insert(
|
||||
(T::PATH.into(), T::InputEncoding::METHOD),
|
||||
ServerFnTraitObj::new::<T>(|req| Box::pin(T::run_on_server(req))),
|
||||
ServerFnTraitObj::new(
|
||||
T::PATH,
|
||||
T::InputEncoding::METHOD,
|
||||
|req| Box::pin(T::run_on_server(req)),
|
||||
T::middlewares,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -549,7 +539,7 @@ pub mod axum {
|
||||
let key = (path.into(), method);
|
||||
REGISTERED_SERVER_FUNCTIONS.get(&key).map(|server_fn| {
|
||||
let middleware = (server_fn.middleware)();
|
||||
let mut service = server_fn.clone().boxed();
|
||||
let mut service = BoxedService::new(server_fn.clone());
|
||||
for middleware in middleware {
|
||||
service = middleware.layer(service);
|
||||
}
|
||||
@@ -588,7 +578,12 @@ pub mod actix {
|
||||
{
|
||||
REGISTERED_SERVER_FUNCTIONS.insert(
|
||||
(T::PATH.into(), T::InputEncoding::METHOD),
|
||||
ServerFnTraitObj::new::<T>(|req| Box::pin(T::run_on_server(req))),
|
||||
ServerFnTraitObj::new(
|
||||
T::PATH,
|
||||
T::InputEncoding::METHOD,
|
||||
|req| Box::pin(T::run_on_server(req)),
|
||||
T::middlewares,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -608,6 +603,7 @@ pub mod actix {
|
||||
let method = req.method();
|
||||
if let Some(mut service) = get_server_fn_service(path, method) {
|
||||
service
|
||||
.0
|
||||
.run(ActixRequest::from((req, payload)))
|
||||
.await
|
||||
.0
|
||||
@@ -648,7 +644,7 @@ pub mod actix {
|
||||
REGISTERED_SERVER_FUNCTIONS.get(&(path.into(), method)).map(
|
||||
|server_fn| {
|
||||
let middleware = (server_fn.middleware)();
|
||||
let mut service = server_fn.clone().boxed();
|
||||
let mut service = BoxedService::new(server_fn.clone());
|
||||
for middleware in middleware {
|
||||
service = middleware.layer(service);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::error::ServerFnErrorErr;
|
||||
use std::{future::Future, pin::Pin};
|
||||
|
||||
/// An abstraction over a middleware layer, which can be used to add additional
|
||||
@@ -9,31 +8,12 @@ pub trait Layer<Req, Res>: Send + Sync + 'static {
|
||||
}
|
||||
|
||||
/// A type-erased service, which takes an HTTP request and returns a response.
|
||||
pub struct BoxedService<Req, Res> {
|
||||
/// A function that converts a [`ServerFnErrorErr`] into a string.
|
||||
pub ser: fn(ServerFnErrorErr) -> String,
|
||||
/// The inner service.
|
||||
pub service: Box<dyn Service<Req, Res> + Send>,
|
||||
}
|
||||
pub struct BoxedService<Req, Res>(pub Box<dyn Service<Req, Res> + Send>);
|
||||
|
||||
impl<Req, Res> BoxedService<Req, Res> {
|
||||
/// Constructs a type-erased service from this service.
|
||||
pub fn new(
|
||||
ser: fn(ServerFnErrorErr) -> String,
|
||||
service: impl Service<Req, Res> + Send + 'static,
|
||||
) -> Self {
|
||||
Self {
|
||||
ser,
|
||||
service: Box::new(service),
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a request into a response by running the inner service.
|
||||
pub fn run(
|
||||
&mut self,
|
||||
req: Req,
|
||||
) -> Pin<Box<dyn Future<Output = Res> + Send>> {
|
||||
self.service.run(req, self.ser)
|
||||
pub fn new(service: impl Service<Req, Res> + Send + 'static) -> Self {
|
||||
Self(Box::new(service))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,36 +23,37 @@ pub trait Service<Request, Response> {
|
||||
fn run(
|
||||
&mut self,
|
||||
req: Request,
|
||||
ser: fn(ServerFnErrorErr) -> String,
|
||||
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
|
||||
}
|
||||
|
||||
#[cfg(feature = "axum-no-default")]
|
||||
mod axum {
|
||||
use super::{BoxedService, Service};
|
||||
use crate::{error::ServerFnErrorErr, response::Res, ServerFnError};
|
||||
use crate::{response::Res, ServerFnError};
|
||||
use axum::body::Body;
|
||||
use http::{Request, Response};
|
||||
use std::{future::Future, pin::Pin};
|
||||
use std::{
|
||||
fmt::{Debug, Display},
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
};
|
||||
|
||||
impl<S> super::Service<Request<Body>, Response<Body>> for S
|
||||
where
|
||||
S: tower::Service<Request<Body>, Response = Response<Body>>,
|
||||
S::Future: Send + 'static,
|
||||
S::Error: std::fmt::Display + Send + 'static,
|
||||
S::Error: Into<ServerFnError> + Send + Debug + Display + Sync + 'static,
|
||||
{
|
||||
fn run(
|
||||
&mut self,
|
||||
req: Request<Body>,
|
||||
ser: fn(ServerFnErrorErr) -> String,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> {
|
||||
let path = req.uri().path().to_string();
|
||||
let inner = self.call(req);
|
||||
Box::pin(async move {
|
||||
inner.await.unwrap_or_else(|e| {
|
||||
let err =
|
||||
ser(ServerFnErrorErr::MiddlewareError(e.to_string()));
|
||||
Response::<Body>::error_response(&path, err)
|
||||
let err = ServerFnError::new(e);
|
||||
Response::<Body>::error_response(&path, &err)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -99,7 +80,7 @@ mod axum {
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request<Body>) -> Self::Future {
|
||||
let inner = self.service.run(req, self.ser);
|
||||
let inner = self.0.run(req);
|
||||
Box::pin(async move { Ok(inner.await) })
|
||||
}
|
||||
}
|
||||
@@ -116,7 +97,7 @@ mod axum {
|
||||
&self,
|
||||
inner: BoxedService<Request<Body>, Response<Body>>,
|
||||
) -> BoxedService<Request<Body>, Response<Body>> {
|
||||
BoxedService::new(inner.ser, self.layer(inner))
|
||||
BoxedService(Box::new(self.layer(inner)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -124,31 +105,33 @@ mod axum {
|
||||
#[cfg(feature = "actix")]
|
||||
mod actix {
|
||||
use crate::{
|
||||
error::ServerFnErrorErr,
|
||||
request::actix::ActixRequest,
|
||||
response::{actix::ActixResponse, Res},
|
||||
ServerFnError,
|
||||
};
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use std::{future::Future, pin::Pin};
|
||||
use std::{
|
||||
fmt::{Debug, Display},
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
};
|
||||
|
||||
impl<S> super::Service<HttpRequest, HttpResponse> for S
|
||||
where
|
||||
S: actix_web::dev::Service<HttpRequest, Response = HttpResponse>,
|
||||
S::Future: Send + 'static,
|
||||
S::Error: std::fmt::Display + Send + 'static,
|
||||
S::Error: Into<ServerFnError> + Debug + Display + 'static,
|
||||
{
|
||||
fn run(
|
||||
&mut self,
|
||||
req: HttpRequest,
|
||||
ser: fn(ServerFnErrorErr) -> String,
|
||||
) -> Pin<Box<dyn Future<Output = HttpResponse> + Send>> {
|
||||
let path = req.uri().path().to_string();
|
||||
let inner = self.call(req);
|
||||
Box::pin(async move {
|
||||
inner.await.unwrap_or_else(|e| {
|
||||
let err =
|
||||
ser(ServerFnErrorErr::MiddlewareError(e.to_string()));
|
||||
ActixResponse::error_response(&path, err).take()
|
||||
let err = ServerFnError::new(e);
|
||||
ActixResponse::error_response(&path, &err).take()
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -158,20 +141,18 @@ mod actix {
|
||||
where
|
||||
S: actix_web::dev::Service<HttpRequest, Response = HttpResponse>,
|
||||
S::Future: Send + 'static,
|
||||
S::Error: std::fmt::Display + Send + 'static,
|
||||
S::Error: Into<ServerFnError> + Debug + Display + 'static,
|
||||
{
|
||||
fn run(
|
||||
&mut self,
|
||||
req: ActixRequest,
|
||||
ser: fn(ServerFnErrorErr) -> String,
|
||||
) -> Pin<Box<dyn Future<Output = ActixResponse> + Send>> {
|
||||
let path = req.0 .0.uri().path().to_string();
|
||||
let inner = self.call(req.0.take().0);
|
||||
Box::pin(async move {
|
||||
ActixResponse::from(inner.await.unwrap_or_else(|e| {
|
||||
let err =
|
||||
ser(ServerFnErrorErr::MiddlewareError(e.to_string()));
|
||||
ActixResponse::error_response(&path, err).take()
|
||||
let err = ServerFnError::new(e);
|
||||
ActixResponse::error_response(&path, &err).take()
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
request::Req,
|
||||
ServerFnError,
|
||||
};
|
||||
use crate::{error::ServerFnError, request::Req};
|
||||
use actix_web::{web::Payload, HttpRequest};
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, StreamExt};
|
||||
@@ -37,9 +33,9 @@ impl From<(HttpRequest, Payload)> for ActixRequest {
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> Req<E> for ActixRequest
|
||||
impl<CustErr> Req<CustErr> for ActixRequest
|
||||
where
|
||||
E: FromServerFnError,
|
||||
CustErr: 'static,
|
||||
{
|
||||
fn as_query(&self) -> Option<&str> {
|
||||
self.0 .0.uri().query()
|
||||
@@ -57,39 +53,44 @@ where
|
||||
self.header("Referer")
|
||||
}
|
||||
|
||||
fn try_into_bytes(self) -> impl Future<Output = Result<Bytes, E>> + Send {
|
||||
fn try_into_bytes(
|
||||
self,
|
||||
) -> impl Future<Output = Result<Bytes, ServerFnError<CustErr>>> + Send
|
||||
{
|
||||
// Actix is going to keep this on a single thread anyway so it's fine to wrap it
|
||||
// with SendWrapper, which makes it `Send` but will panic if it moves to another thread
|
||||
SendWrapper::new(async move {
|
||||
let payload = self.0.take().1;
|
||||
payload.to_bytes().await.map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
payload
|
||||
.to_bytes()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
fn try_into_string(self) -> impl Future<Output = Result<String, E>> + Send {
|
||||
fn try_into_string(
|
||||
self,
|
||||
) -> impl Future<Output = Result<String, ServerFnError<CustErr>>> + Send
|
||||
{
|
||||
// Actix is going to keep this on a single thread anyway so it's fine to wrap it
|
||||
// with SendWrapper, which makes it `Send` but will panic if it moves to another thread
|
||||
SendWrapper::new(async move {
|
||||
let payload = self.0.take().1;
|
||||
let bytes = payload.to_bytes().await.map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Deserialization(
|
||||
e.to_string(),
|
||||
))
|
||||
})?;
|
||||
String::from_utf8(bytes.into()).map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Deserialization(
|
||||
e.to_string(),
|
||||
))
|
||||
})
|
||||
let bytes = payload
|
||||
.to_bytes()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))?;
|
||||
String::from_utf8(bytes.into())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<impl Stream<Item = Result<Bytes, E>> + Send, E> {
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, ServerFnError>> + Send,
|
||||
ServerFnError<CustErr>,
|
||||
> {
|
||||
let payload = self.0.take().1;
|
||||
let stream = payload.map(|res| {
|
||||
res.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
request::Req,
|
||||
};
|
||||
use crate::{error::ServerFnError, request::Req};
|
||||
use axum::body::{Body, Bytes};
|
||||
use futures::{Stream, StreamExt};
|
||||
use http::{
|
||||
@@ -11,9 +8,9 @@ use http::{
|
||||
use http_body_util::BodyExt;
|
||||
use std::borrow::Cow;
|
||||
|
||||
impl<E> Req<E> for Request<Body>
|
||||
impl<CustErr> Req<CustErr> for Request<Body>
|
||||
where
|
||||
E: FromServerFnError,
|
||||
CustErr: 'static,
|
||||
{
|
||||
fn as_query(&self) -> Option<&str> {
|
||||
self.uri().query()
|
||||
@@ -37,29 +34,29 @@ where
|
||||
.map(|h| String::from_utf8_lossy(h.as_bytes()))
|
||||
}
|
||||
|
||||
async fn try_into_bytes(self) -> Result<Bytes, E> {
|
||||
async fn try_into_bytes(self) -> Result<Bytes, ServerFnError<CustErr>> {
|
||||
let (_parts, body) = self.into_parts();
|
||||
|
||||
body.collect().await.map(|c| c.to_bytes()).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
body.collect()
|
||||
.await
|
||||
.map(|c| c.to_bytes())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
|
||||
async fn try_into_string(self) -> Result<String, E> {
|
||||
async fn try_into_string(self) -> Result<String, ServerFnError<CustErr>> {
|
||||
let bytes = self.try_into_bytes().await?;
|
||||
String::from_utf8(bytes.to_vec()).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
String::from_utf8(bytes.to_vec())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<impl Stream<Item = Result<Bytes, E>> + Send + 'static, E> {
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, ServerFnError>> + Send + 'static,
|
||||
ServerFnError<CustErr>,
|
||||
> {
|
||||
Ok(self.into_body().into_data_stream().map(|chunk| {
|
||||
chunk.map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
chunk.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use super::ClientReq;
|
||||
use crate::{
|
||||
client::get_server_url,
|
||||
error::{FromServerFnError, ServerFnErrorErr},
|
||||
};
|
||||
use crate::{client::get_server_url, error::ServerFnError};
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, StreamExt};
|
||||
pub use gloo_net::http::Request;
|
||||
@@ -86,10 +83,7 @@ fn abort_signal() -> (Option<AbortOnDrop>, Option<AbortSignal>) {
|
||||
(ctrl.map(|ctrl| AbortOnDrop(Some(ctrl))), signal)
|
||||
}
|
||||
|
||||
impl<E> ClientReq<E> for BrowserRequest
|
||||
where
|
||||
E: FromServerFnError,
|
||||
{
|
||||
impl<CustErr> ClientReq<CustErr> for BrowserRequest {
|
||||
type FormData = BrowserFormData;
|
||||
|
||||
fn try_new_get(
|
||||
@@ -97,7 +91,7 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
query: &str,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let (abort_ctrl, abort_signal) = abort_signal();
|
||||
let server_url = get_server_url();
|
||||
let mut url = String::with_capacity(
|
||||
@@ -113,11 +107,7 @@ where
|
||||
.header("Accept", accepts)
|
||||
.abort_signal(abort_signal.as_ref())
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Request(
|
||||
e.to_string(),
|
||||
))
|
||||
})?,
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))?,
|
||||
abort_ctrl,
|
||||
})))
|
||||
}
|
||||
@@ -127,7 +117,7 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: String,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let (abort_ctrl, abort_signal) = abort_signal();
|
||||
let server_url = get_server_url();
|
||||
let mut url = String::with_capacity(server_url.len() + path.len());
|
||||
@@ -139,11 +129,7 @@ where
|
||||
.header("Accept", accepts)
|
||||
.abort_signal(abort_signal.as_ref())
|
||||
.body(body)
|
||||
.map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Request(
|
||||
e.to_string(),
|
||||
))
|
||||
})?,
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))?,
|
||||
abort_ctrl,
|
||||
})))
|
||||
}
|
||||
@@ -153,7 +139,7 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: Bytes,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let (abort_ctrl, abort_signal) = abort_signal();
|
||||
let server_url = get_server_url();
|
||||
let mut url = String::with_capacity(server_url.len() + path.len());
|
||||
@@ -167,11 +153,7 @@ where
|
||||
.header("Accept", accepts)
|
||||
.abort_signal(abort_signal.as_ref())
|
||||
.body(body)
|
||||
.map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Request(
|
||||
e.to_string(),
|
||||
))
|
||||
})?,
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))?,
|
||||
abort_ctrl,
|
||||
})))
|
||||
}
|
||||
@@ -180,7 +162,7 @@ where
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
body: Self::FormData,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let (abort_ctrl, abort_signal) = abort_signal();
|
||||
let server_url = get_server_url();
|
||||
let mut url = String::with_capacity(server_url.len() + path.len());
|
||||
@@ -191,11 +173,7 @@ where
|
||||
.header("Accept", accepts)
|
||||
.abort_signal(abort_signal.as_ref())
|
||||
.body(body.0.take())
|
||||
.map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Request(
|
||||
e.to_string(),
|
||||
))
|
||||
})?,
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))?,
|
||||
abort_ctrl,
|
||||
})))
|
||||
}
|
||||
@@ -205,17 +183,17 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: Self::FormData,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let (abort_ctrl, abort_signal) = abort_signal();
|
||||
let form_data = body.0.take();
|
||||
let url_params =
|
||||
UrlSearchParams::new_with_str_sequence_sequence(&form_data)
|
||||
.map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Serialization(
|
||||
e.as_string().unwrap_or_else(|| {
|
||||
ServerFnError::Serialization(e.as_string().unwrap_or_else(
|
||||
|| {
|
||||
"Could not serialize FormData to URLSearchParams"
|
||||
.to_string()
|
||||
}),
|
||||
},
|
||||
))
|
||||
})?;
|
||||
Ok(Self(SendWrapper::new(RequestInner {
|
||||
@@ -224,11 +202,7 @@ where
|
||||
.header("Accept", accepts)
|
||||
.abort_signal(abort_signal.as_ref())
|
||||
.body(url_params)
|
||||
.map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Request(
|
||||
e.to_string(),
|
||||
))
|
||||
})?,
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))?,
|
||||
abort_ctrl,
|
||||
})))
|
||||
}
|
||||
@@ -238,16 +212,11 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: impl Stream<Item = Bytes> + 'static,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
// TODO abort signal
|
||||
let (request, abort_ctrl) =
|
||||
streaming_request(path, accepts, content_type, body).map_err(
|
||||
|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Request(format!(
|
||||
"{e:?}"
|
||||
)))
|
||||
},
|
||||
)?;
|
||||
streaming_request(path, accepts, content_type, body)
|
||||
.map_err(|e| ServerFnError::Request(format!("{e:?}")))?;
|
||||
Ok(Self(SendWrapper::new(RequestInner {
|
||||
request,
|
||||
abort_ctrl,
|
||||
|
||||
@@ -12,10 +12,7 @@
|
||||
//! * `wasm32-wasip*` integration crate `leptos_wasi` is using this
|
||||
//! crate under the hood.
|
||||
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
request::Req,
|
||||
};
|
||||
use crate::request::Req;
|
||||
use bytes::Bytes;
|
||||
use futures::{
|
||||
stream::{self, Stream},
|
||||
@@ -24,23 +21,30 @@ use futures::{
|
||||
use http::Request;
|
||||
use std::borrow::Cow;
|
||||
|
||||
impl<E> Req<E> for Request<Bytes>
|
||||
impl<CustErr> Req<CustErr> for Request<Bytes>
|
||||
where
|
||||
E: FromServerFnError,
|
||||
CustErr: 'static,
|
||||
{
|
||||
async fn try_into_bytes(self) -> Result<Bytes, E> {
|
||||
async fn try_into_bytes(
|
||||
self,
|
||||
) -> Result<Bytes, crate::ServerFnError<CustErr>> {
|
||||
Ok(self.into_body())
|
||||
}
|
||||
|
||||
async fn try_into_string(self) -> Result<String, E> {
|
||||
async fn try_into_string(
|
||||
self,
|
||||
) -> Result<String, crate::ServerFnError<CustErr>> {
|
||||
String::from_utf8(self.into_body().into()).map_err(|err| {
|
||||
ServerFnErrorErr::Deserialization(err.to_string()).into_app_error()
|
||||
crate::ServerFnError::Deserialization(err.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<impl Stream<Item = Result<Bytes, E>> + Send + 'static, E> {
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, crate::ServerFnError>> + Send + 'static,
|
||||
crate::ServerFnError<CustErr>,
|
||||
> {
|
||||
Ok(stream::iter(self.into_body())
|
||||
.ready_chunks(16)
|
||||
.map(|chunk| Ok(Bytes::from(chunk))))
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::error::ServerFnError;
|
||||
use bytes::Bytes;
|
||||
use futures::Stream;
|
||||
use std::{borrow::Cow, future::Future};
|
||||
@@ -18,7 +19,7 @@ pub mod generic;
|
||||
pub mod reqwest;
|
||||
|
||||
/// Represents a request as made by the client.
|
||||
pub trait ClientReq<E>
|
||||
pub trait ClientReq<CustErr>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -31,7 +32,7 @@ where
|
||||
content_type: &str,
|
||||
accepts: &str,
|
||||
query: &str,
|
||||
) -> Result<Self, E>;
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
|
||||
/// Attempts to construct a new `POST` request with a text body.
|
||||
fn try_new_post(
|
||||
@@ -39,7 +40,7 @@ where
|
||||
content_type: &str,
|
||||
accepts: &str,
|
||||
body: String,
|
||||
) -> Result<Self, E>;
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
|
||||
/// Attempts to construct a new `POST` request with a binary body.
|
||||
fn try_new_post_bytes(
|
||||
@@ -47,7 +48,7 @@ where
|
||||
content_type: &str,
|
||||
accepts: &str,
|
||||
body: Bytes,
|
||||
) -> Result<Self, E>;
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
|
||||
/// Attempts to construct a new `POST` request with form data as the body.
|
||||
fn try_new_post_form_data(
|
||||
@@ -55,14 +56,14 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: Self::FormData,
|
||||
) -> Result<Self, E>;
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
|
||||
/// Attempts to construct a new `POST` request with a multipart body.
|
||||
fn try_new_multipart(
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
body: Self::FormData,
|
||||
) -> Result<Self, E>;
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
|
||||
/// Attempts to construct a new `POST` request with a streaming body.
|
||||
fn try_new_streaming(
|
||||
@@ -70,11 +71,11 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: impl Stream<Item = Bytes> + Send + 'static,
|
||||
) -> Result<Self, E>;
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
}
|
||||
|
||||
/// Represents the request as received by the server.
|
||||
pub trait Req<E>
|
||||
pub trait Req<CustErr>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
@@ -91,22 +92,32 @@ where
|
||||
fn referer(&self) -> Option<Cow<'_, str>>;
|
||||
|
||||
/// Attempts to extract the body of the request into [`Bytes`].
|
||||
fn try_into_bytes(self) -> impl Future<Output = Result<Bytes, E>> + Send;
|
||||
fn try_into_bytes(
|
||||
self,
|
||||
) -> impl Future<Output = Result<Bytes, ServerFnError<CustErr>>> + Send;
|
||||
|
||||
/// Attempts to convert the body of the request into a string.
|
||||
fn try_into_string(self) -> impl Future<Output = Result<String, E>> + Send;
|
||||
fn try_into_string(
|
||||
self,
|
||||
) -> impl Future<Output = Result<String, ServerFnError<CustErr>>> + Send;
|
||||
|
||||
/// Attempts to convert the body of the request into a stream of bytes.
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<impl Stream<Item = Result<Bytes, E>> + Send + 'static, E>;
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, ServerFnError>> + Send + 'static,
|
||||
ServerFnError<CustErr>,
|
||||
>;
|
||||
}
|
||||
|
||||
/// A mocked request type that can be used in place of the actual server request,
|
||||
/// when compiling for the browser.
|
||||
pub struct BrowserMockReq;
|
||||
|
||||
impl<E: 'static> Req<E> for BrowserMockReq {
|
||||
impl<CustErr> Req<CustErr> for BrowserMockReq
|
||||
where
|
||||
CustErr: 'static,
|
||||
{
|
||||
fn as_query(&self) -> Option<&str> {
|
||||
unreachable!()
|
||||
}
|
||||
@@ -122,17 +133,20 @@ impl<E: 'static> Req<E> for BrowserMockReq {
|
||||
fn referer(&self) -> Option<Cow<'_, str>> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn try_into_bytes(self) -> Result<Bytes, E> {
|
||||
async fn try_into_bytes(self) -> Result<Bytes, ServerFnError<CustErr>> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn try_into_string(self) -> Result<String, E> {
|
||||
async fn try_into_string(self) -> Result<String, ServerFnError<CustErr>> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<impl Stream<Item = Result<Bytes, E>> + Send, E> {
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, ServerFnError>> + Send,
|
||||
ServerFnError<CustErr>,
|
||||
> {
|
||||
Ok(futures::stream::once(async { unreachable!() }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use super::ClientReq;
|
||||
use crate::{
|
||||
client::get_server_url,
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
};
|
||||
use crate::{client::get_server_url, error::ServerFnError};
|
||||
use bytes::Bytes;
|
||||
use futures::Stream;
|
||||
use once_cell::sync::Lazy;
|
||||
@@ -11,10 +8,7 @@ pub use reqwest::{multipart::Form, Client, Method, Request, Url};
|
||||
|
||||
pub(crate) static CLIENT: Lazy<Client> = Lazy::new(Client::new);
|
||||
|
||||
impl<E> ClientReq<E> for Request
|
||||
where
|
||||
E: FromServerFnError,
|
||||
{
|
||||
impl<CustErr> ClientReq<CustErr> for Request {
|
||||
type FormData = Form;
|
||||
|
||||
fn try_new_get(
|
||||
@@ -22,22 +16,17 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
query: &str,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let url = format!("{}{}", get_server_url(), path);
|
||||
let mut url = Url::try_from(url.as_str()).map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Request(e.to_string()))
|
||||
})?;
|
||||
let mut url = Url::try_from(url.as_str())
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))?;
|
||||
url.set_query(Some(query));
|
||||
let req = CLIENT
|
||||
.get(url)
|
||||
.header(CONTENT_TYPE, content_type)
|
||||
.header(ACCEPT, accepts)
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
E::from_server_fn_error(ServerFnErrorErr::Request(
|
||||
e.to_string(),
|
||||
))
|
||||
})?;
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))?;
|
||||
Ok(req)
|
||||
}
|
||||
|
||||
@@ -46,7 +35,7 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: String,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let url = format!("{}{}", get_server_url(), path);
|
||||
CLIENT
|
||||
.post(url)
|
||||
@@ -54,9 +43,7 @@ where
|
||||
.header(ACCEPT, accepts)
|
||||
.body(body)
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Request(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_new_post_bytes(
|
||||
@@ -64,7 +51,7 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: Bytes,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let url = format!("{}{}", get_server_url(), path);
|
||||
CLIENT
|
||||
.post(url)
|
||||
@@ -72,24 +59,20 @@ where
|
||||
.header(ACCEPT, accepts)
|
||||
.body(body)
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Request(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_new_multipart(
|
||||
path: &str,
|
||||
accepts: &str,
|
||||
body: Self::FormData,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
CLIENT
|
||||
.post(path)
|
||||
.header(ACCEPT, accepts)
|
||||
.multipart(body)
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Request(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_new_post_form_data(
|
||||
@@ -97,16 +80,14 @@ where
|
||||
accepts: &str,
|
||||
content_type: &str,
|
||||
body: Self::FormData,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
CLIENT
|
||||
.post(path)
|
||||
.header(CONTENT_TYPE, content_type)
|
||||
.header(ACCEPT, accepts)
|
||||
.multipart(body)
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Request(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_new_streaming(
|
||||
@@ -114,7 +95,7 @@ where
|
||||
_accepts: &str,
|
||||
_content_type: &str,
|
||||
_body: impl Stream<Item = Bytes> + 'static,
|
||||
) -> Result<Self, E> {
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
todo!("Streaming requests are not yet implemented for reqwest.")
|
||||
// We run into a fundamental issue here.
|
||||
// To be a reqwest body, the type must be Sync
|
||||
@@ -131,7 +112,7 @@ where
|
||||
.header(ACCEPT, accepts)
|
||||
.body(body)
|
||||
.build()
|
||||
.map_err(|e| ServerFnErrorErr::Request(e.to_string()).into())
|
||||
.map_err(|e| ServerFnError::Request(e.to_string()))
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use http::{
|
||||
use http_body_util::BodyExt;
|
||||
use std::borrow::Cow;
|
||||
|
||||
impl<E> Req<E> for IncomingRequest
|
||||
impl<CustErr> Req<CustErr> for IncomingRequest
|
||||
where
|
||||
CustErr: 'static,
|
||||
{
|
||||
@@ -34,31 +34,29 @@ where
|
||||
.map(|h| String::from_utf8_lossy(h.as_bytes()))
|
||||
}
|
||||
|
||||
async fn try_into_bytes(self) -> Result<Bytes, E> {
|
||||
async fn try_into_bytes(self) -> Result<Bytes, ServerFnError<CustErr>> {
|
||||
let (_parts, body) = self.into_parts();
|
||||
|
||||
body.collect().await.map(|c| c.to_bytes()).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into()
|
||||
})
|
||||
body.collect()
|
||||
.await
|
||||
.map(|c| c.to_bytes())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
|
||||
async fn try_into_string(self) -> Result<String, E> {
|
||||
async fn try_into_string(self) -> Result<String, ServerFnError<CustErr>> {
|
||||
let bytes = self.try_into_bytes().await?;
|
||||
String::from_utf8(bytes.to_vec()).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into()
|
||||
})
|
||||
String::from_utf8(bytes.to_vec())
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, ServerFnError>> + Send + 'static,
|
||||
E,
|
||||
ServerFnError<CustErr>,
|
||||
> {
|
||||
Ok(self.into_body().into_data_stream().map(|chunk| {
|
||||
chunk.map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into()
|
||||
})
|
||||
chunk.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{Res, TryRes};
|
||||
use super::Res;
|
||||
use crate::error::{
|
||||
FromServerFnError, ServerFnErrorWrapper, SERVER_FN_ERROR_HEADER,
|
||||
ServerFnError, ServerFnErrorErr, ServerFnErrorSerde, SERVER_FN_ERROR_HEADER,
|
||||
};
|
||||
use actix_web::{
|
||||
http::{
|
||||
@@ -13,6 +13,10 @@ use actix_web::{
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, StreamExt};
|
||||
use send_wrapper::SendWrapper;
|
||||
use std::{
|
||||
fmt::{Debug, Display},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
/// A wrapped Actix response.
|
||||
///
|
||||
@@ -34,11 +38,14 @@ impl From<HttpResponse> for ActixResponse {
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> TryRes<E> for ActixResponse
|
||||
impl<CustErr> Res<CustErr> for ActixResponse
|
||||
where
|
||||
E: FromServerFnError,
|
||||
CustErr: FromStr + Display + Debug + 'static,
|
||||
{
|
||||
fn try_from_string(content_type: &str, data: String) -> Result<Self, E> {
|
||||
fn try_from_string(
|
||||
content_type: &str,
|
||||
data: String,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let mut builder = HttpResponse::build(StatusCode::OK);
|
||||
Ok(ActixResponse(SendWrapper::new(
|
||||
builder
|
||||
@@ -47,7 +54,10 @@ where
|
||||
)))
|
||||
}
|
||||
|
||||
fn try_from_bytes(content_type: &str, data: Bytes) -> Result<Self, E> {
|
||||
fn try_from_bytes(
|
||||
content_type: &str,
|
||||
data: Bytes,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let mut builder = HttpResponse::build(StatusCode::OK);
|
||||
Ok(ActixResponse(SendWrapper::new(
|
||||
builder
|
||||
@@ -58,23 +68,23 @@ where
|
||||
|
||||
fn try_from_stream(
|
||||
content_type: &str,
|
||||
data: impl Stream<Item = Result<Bytes, E>> + 'static,
|
||||
) -> Result<Self, E> {
|
||||
data: impl Stream<Item = Result<Bytes, ServerFnError<CustErr>>> + 'static,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let mut builder = HttpResponse::build(StatusCode::OK);
|
||||
Ok(ActixResponse(SendWrapper::new(
|
||||
builder
|
||||
.insert_header((header::CONTENT_TYPE, content_type))
|
||||
.streaming(data.map(|data| data.map_err(ServerFnErrorWrapper))),
|
||||
.streaming(
|
||||
data.map(|data| data.map_err(ServerFnErrorErr::from)),
|
||||
),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Res for ActixResponse {
|
||||
fn error_response(path: &str, err: String) -> Self {
|
||||
fn error_response(path: &str, err: &ServerFnError<CustErr>) -> Self {
|
||||
ActixResponse(SendWrapper::new(
|
||||
HttpResponse::build(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.append_header((SERVER_FN_ERROR_HEADER, path))
|
||||
.body(err),
|
||||
.body(err.ser().unwrap_or_else(|_| err.to_string())),
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use super::ClientRes;
|
||||
use crate::{
|
||||
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
|
||||
redirect::REDIRECT_HEADER,
|
||||
};
|
||||
use crate::{error::ServerFnError, redirect::REDIRECT_HEADER};
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, StreamExt};
|
||||
pub use gloo_net::http::Response;
|
||||
@@ -15,39 +12,48 @@ use wasm_streams::ReadableStream;
|
||||
/// The response to a `fetch` request made in the browser.
|
||||
pub struct BrowserResponse(pub(crate) SendWrapper<Response>);
|
||||
|
||||
impl<E: FromServerFnError> ClientRes<E> for BrowserResponse {
|
||||
fn try_into_string(self) -> impl Future<Output = Result<String, E>> + Send {
|
||||
impl<CustErr> ClientRes<CustErr> for BrowserResponse {
|
||||
fn try_into_string(
|
||||
self,
|
||||
) -> impl Future<Output = Result<String, ServerFnError<CustErr>>> + Send
|
||||
{
|
||||
// the browser won't send this async work between threads (because it's single-threaded)
|
||||
// so we can safely wrap this
|
||||
SendWrapper::new(async move {
|
||||
self.0.text().await.map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
self.0
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
fn try_into_bytes(self) -> impl Future<Output = Result<Bytes, E>> + Send {
|
||||
fn try_into_bytes(
|
||||
self,
|
||||
) -> impl Future<Output = Result<Bytes, ServerFnError<CustErr>>> + Send
|
||||
{
|
||||
// the browser won't send this async work between threads (because it's single-threaded)
|
||||
// so we can safely wrap this
|
||||
SendWrapper::new(async move {
|
||||
self.0.binary().await.map(Bytes::from).map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string())
|
||||
.into_app_error()
|
||||
})
|
||||
self.0
|
||||
.binary()
|
||||
.await
|
||||
.map(Bytes::from)
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<impl Stream<Item = Result<Bytes, E>> + Send + 'static, E> {
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, ServerFnError>> + Send + 'static,
|
||||
ServerFnError<CustErr>,
|
||||
> {
|
||||
let stream = ReadableStream::from_raw(self.0.body().unwrap())
|
||||
.into_stream()
|
||||
.map(|data| match data {
|
||||
Err(e) => {
|
||||
web_sys::console::error_1(&e);
|
||||
Err(ServerFnErrorErr::Request(format!("{e:?}"))
|
||||
.into_app_error())
|
||||
Err(ServerFnError::Request(format!("{e:?}")))
|
||||
}
|
||||
Ok(data) => {
|
||||
let data = data.unchecked_into::<Uint8Array>();
|
||||
|
||||
@@ -12,15 +12,18 @@
|
||||
//! * `wasm32-wasip*` integration crate `leptos_wasi` is using this
|
||||
//! crate under the hood.
|
||||
|
||||
use super::{Res, TryRes};
|
||||
use super::Res;
|
||||
use crate::error::{
|
||||
FromServerFnError, IntoAppError, ServerFnErrorErr, ServerFnErrorWrapper,
|
||||
SERVER_FN_ERROR_HEADER,
|
||||
ServerFnError, ServerFnErrorErr, ServerFnErrorSerde, SERVER_FN_ERROR_HEADER,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, TryStreamExt};
|
||||
use http::{header, HeaderValue, Response, StatusCode};
|
||||
use std::pin::Pin;
|
||||
use std::{
|
||||
fmt::{Debug, Display},
|
||||
pin::Pin,
|
||||
str::FromStr,
|
||||
};
|
||||
use throw_error::Error;
|
||||
|
||||
/// The Body of a Response whose *execution model* can be
|
||||
@@ -41,55 +44,55 @@ impl From<String> for Body {
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> TryRes<E> for Response<Body>
|
||||
impl<CustErr> Res<CustErr> for Response<Body>
|
||||
where
|
||||
E: Send + Sync + FromServerFnError,
|
||||
CustErr: Send + Sync + Debug + FromStr + Display + 'static,
|
||||
{
|
||||
fn try_from_string(content_type: &str, data: String) -> Result<Self, E> {
|
||||
fn try_from_string(
|
||||
content_type: &str,
|
||||
data: String,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let builder = http::Response::builder();
|
||||
builder
|
||||
.status(200)
|
||||
.header(http::header::CONTENT_TYPE, content_type)
|
||||
.body(data.into())
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Response(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Response(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_from_bytes(content_type: &str, data: Bytes) -> Result<Self, E> {
|
||||
fn try_from_bytes(
|
||||
content_type: &str,
|
||||
data: Bytes,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let builder = http::Response::builder();
|
||||
builder
|
||||
.status(200)
|
||||
.header(http::header::CONTENT_TYPE, content_type)
|
||||
.body(Body::Sync(data))
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Response(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Response(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_from_stream(
|
||||
content_type: &str,
|
||||
data: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
|
||||
) -> Result<Self, E> {
|
||||
data: impl Stream<Item = Result<Bytes, ServerFnError<CustErr>>>
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let builder = http::Response::builder();
|
||||
builder
|
||||
.status(200)
|
||||
.header(http::header::CONTENT_TYPE, content_type)
|
||||
.body(Body::Async(Box::pin(
|
||||
data.map_err(ServerFnErrorWrapper).map_err(Error::from),
|
||||
data.map_err(ServerFnErrorErr::from).map_err(Error::from),
|
||||
)))
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Response(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Response(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Res for Response<Body> {
|
||||
fn error_response(path: &str, err: String) -> Self {
|
||||
fn error_response(path: &str, err: &ServerFnError<CustErr>) -> Self {
|
||||
Response::builder()
|
||||
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.header(SERVER_FN_ERROR_HEADER, path)
|
||||
.body(err.into())
|
||||
.body(err.ser().unwrap_or_else(|_| err.to_string()).into())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,61 +1,65 @@
|
||||
use super::{Res, TryRes};
|
||||
use super::Res;
|
||||
use crate::error::{
|
||||
FromServerFnError, IntoAppError, ServerFnErrorErr, ServerFnErrorWrapper,
|
||||
SERVER_FN_ERROR_HEADER,
|
||||
ServerFnError, ServerFnErrorErr, ServerFnErrorSerde, SERVER_FN_ERROR_HEADER,
|
||||
};
|
||||
use axum::body::Body;
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, TryStreamExt};
|
||||
use futures::{Stream, StreamExt};
|
||||
use http::{header, HeaderValue, Response, StatusCode};
|
||||
use std::{
|
||||
fmt::{Debug, Display},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
impl<E> TryRes<E> for Response<Body>
|
||||
impl<CustErr> Res<CustErr> for Response<Body>
|
||||
where
|
||||
E: Send + Sync + FromServerFnError,
|
||||
CustErr: Send + Sync + Debug + FromStr + Display + 'static,
|
||||
{
|
||||
fn try_from_string(content_type: &str, data: String) -> Result<Self, E> {
|
||||
fn try_from_string(
|
||||
content_type: &str,
|
||||
data: String,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let builder = http::Response::builder();
|
||||
builder
|
||||
.status(200)
|
||||
.header(http::header::CONTENT_TYPE, content_type)
|
||||
.body(Body::from(data))
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Response(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Response(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_from_bytes(content_type: &str, data: Bytes) -> Result<Self, E> {
|
||||
fn try_from_bytes(
|
||||
content_type: &str,
|
||||
data: Bytes,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let builder = http::Response::builder();
|
||||
builder
|
||||
.status(200)
|
||||
.header(http::header::CONTENT_TYPE, content_type)
|
||||
.body(Body::from(data))
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Response(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Response(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_from_stream(
|
||||
content_type: &str,
|
||||
data: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
|
||||
) -> Result<Self, E> {
|
||||
let body = Body::from_stream(data.map_err(|e| ServerFnErrorWrapper(e)));
|
||||
data: impl Stream<Item = Result<Bytes, ServerFnError<CustErr>>>
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
let body =
|
||||
Body::from_stream(data.map(|n| n.map_err(ServerFnErrorErr::from)));
|
||||
let builder = http::Response::builder();
|
||||
builder
|
||||
.status(200)
|
||||
.header(http::header::CONTENT_TYPE, content_type)
|
||||
.body(body)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Response(e.to_string()).into_app_error()
|
||||
})
|
||||
.map_err(|e| ServerFnError::Response(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Res for Response<Body> {
|
||||
fn error_response(path: &str, err: String) -> Self {
|
||||
fn error_response(path: &str, err: &ServerFnError<CustErr>) -> Self {
|
||||
Response::builder()
|
||||
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.header(SERVER_FN_ERROR_HEADER, path)
|
||||
.body(err.into())
|
||||
.body(err.ser().unwrap_or_else(|_| err.to_string()).into())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
|
||||
@@ -13,49 +13,62 @@ pub mod http;
|
||||
#[cfg(feature = "reqwest")]
|
||||
pub mod reqwest;
|
||||
|
||||
use crate::error::ServerFnError;
|
||||
use bytes::Bytes;
|
||||
use futures::Stream;
|
||||
use std::future::Future;
|
||||
|
||||
/// Represents the response as created by the server;
|
||||
pub trait TryRes<E>
|
||||
pub trait Res<CustErr>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
/// Attempts to convert a UTF-8 string into an HTTP response.
|
||||
fn try_from_string(content_type: &str, data: String) -> Result<Self, E>;
|
||||
fn try_from_string(
|
||||
content_type: &str,
|
||||
data: String,
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
|
||||
/// Attempts to convert a binary blob represented as bytes into an HTTP response.
|
||||
fn try_from_bytes(content_type: &str, data: Bytes) -> Result<Self, E>;
|
||||
fn try_from_bytes(
|
||||
content_type: &str,
|
||||
data: Bytes,
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
|
||||
/// Attempts to convert a stream of bytes into an HTTP response.
|
||||
fn try_from_stream(
|
||||
content_type: &str,
|
||||
data: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
|
||||
) -> Result<Self, E>;
|
||||
}
|
||||
data: impl Stream<Item = Result<Bytes, ServerFnError<CustErr>>>
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> Result<Self, ServerFnError<CustErr>>;
|
||||
|
||||
/// Represents the response as created by the server;
|
||||
pub trait Res {
|
||||
/// Converts an error into a response, with a `500` status code and the error text as its body.
|
||||
fn error_response(path: &str, err: String) -> Self;
|
||||
fn error_response(path: &str, err: &ServerFnError<CustErr>) -> Self;
|
||||
|
||||
/// Redirect the response by setting a 302 code and Location header.
|
||||
fn redirect(&mut self, path: &str);
|
||||
}
|
||||
|
||||
/// Represents the response as received by the client.
|
||||
pub trait ClientRes<E> {
|
||||
pub trait ClientRes<CustErr> {
|
||||
/// Attempts to extract a UTF-8 string from an HTTP response.
|
||||
fn try_into_string(self) -> impl Future<Output = Result<String, E>> + Send;
|
||||
fn try_into_string(
|
||||
self,
|
||||
) -> impl Future<Output = Result<String, ServerFnError<CustErr>>> + Send;
|
||||
|
||||
/// Attempts to extract a binary blob from an HTTP response.
|
||||
fn try_into_bytes(self) -> impl Future<Output = Result<Bytes, E>> + Send;
|
||||
fn try_into_bytes(
|
||||
self,
|
||||
) -> impl Future<Output = Result<Bytes, ServerFnError<CustErr>>> + Send;
|
||||
|
||||
/// Attempts to extract a binary stream from an HTTP response.
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<impl Stream<Item = Result<Bytes, E>> + Send + Sync + 'static, E>;
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, ServerFnError>> + Send + Sync + 'static,
|
||||
ServerFnError<CustErr>,
|
||||
>;
|
||||
|
||||
/// HTTP status code of the response.
|
||||
fn status(&self) -> u16;
|
||||
@@ -78,25 +91,29 @@ pub trait ClientRes<E> {
|
||||
/// server response type when compiling for the client.
|
||||
pub struct BrowserMockRes;
|
||||
|
||||
impl<E> TryRes<E> for BrowserMockRes {
|
||||
fn try_from_string(_content_type: &str, _data: String) -> Result<Self, E> {
|
||||
impl<CustErr> Res<CustErr> for BrowserMockRes {
|
||||
fn try_from_string(
|
||||
_content_type: &str,
|
||||
_data: String,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn try_from_bytes(_content_type: &str, _data: Bytes) -> Result<Self, E> {
|
||||
fn try_from_bytes(
|
||||
_content_type: &str,
|
||||
_data: Bytes,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn error_response(_path: &str, _err: &ServerFnError<CustErr>) -> Self {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn try_from_stream(
|
||||
_content_type: &str,
|
||||
_data: impl Stream<Item = Result<Bytes, E>>,
|
||||
) -> Result<Self, E> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Res for BrowserMockRes {
|
||||
fn error_response(_path: &str, _err: String) -> Self {
|
||||
_data: impl Stream<Item = Result<Bytes, ServerFnError<CustErr>>>,
|
||||
) -> Result<Self, ServerFnError<CustErr>> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,28 +1,31 @@
|
||||
use super::ClientRes;
|
||||
use crate::error::{FromServerFnError, IntoAppError, ServerFnErrorErr};
|
||||
use crate::error::ServerFnError;
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, TryStreamExt};
|
||||
use reqwest::Response;
|
||||
|
||||
impl<E: FromServerFnError> ClientRes<E> for Response {
|
||||
async fn try_into_string(self) -> Result<String, E> {
|
||||
self.text().await.map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
impl<CustErr> ClientRes<CustErr> for Response {
|
||||
async fn try_into_string(self) -> Result<String, ServerFnError<CustErr>> {
|
||||
self.text()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
|
||||
async fn try_into_bytes(self) -> Result<Bytes, E> {
|
||||
self.bytes().await.map_err(|e| {
|
||||
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
|
||||
})
|
||||
async fn try_into_bytes(self) -> Result<Bytes, ServerFnError<CustErr>> {
|
||||
self.bytes()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
|
||||
}
|
||||
|
||||
fn try_into_stream(
|
||||
self,
|
||||
) -> Result<impl Stream<Item = Result<Bytes, E>> + Send + 'static, E> {
|
||||
Ok(self.bytes_stream().map_err(|e| {
|
||||
ServerFnErrorErr::Response(e.to_string()).into_app_error()
|
||||
}))
|
||||
) -> Result<
|
||||
impl Stream<Item = Result<Bytes, ServerFnError>> + Send + 'static,
|
||||
ServerFnError<CustErr>,
|
||||
> {
|
||||
Ok(self
|
||||
.bytes_stream()
|
||||
.map_err(|e| ServerFnError::Response(e.to_string())))
|
||||
}
|
||||
|
||||
fn status(&self) -> u16 {
|
||||
|
||||
@@ -230,7 +230,6 @@ pub fn server_macro_impl(
|
||||
None => Some("PostUrl".to_string()),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let input = input
|
||||
.map(|n| {
|
||||
if builtin_encoding {
|
||||
@@ -383,8 +382,13 @@ pub fn server_macro_impl(
|
||||
quote! {
|
||||
#server_fn_path::inventory::submit! {{
|
||||
use #server_fn_path::{ServerFn, codec::Encoding};
|
||||
#server_fn_path::ServerFnTraitObj::new::<#wrapped_struct_name>(
|
||||
|req| Box::pin(#wrapped_struct_name_turbofish::run_on_server(req)),
|
||||
#server_fn_path::ServerFnTraitObj::new(
|
||||
#wrapped_struct_name_turbofish::PATH,
|
||||
<#wrapped_struct_name as ServerFn>::InputEncoding::METHOD,
|
||||
|req| {
|
||||
Box::pin(#wrapped_struct_name_turbofish::run_on_server(req))
|
||||
},
|
||||
#wrapped_struct_name_turbofish::middlewares
|
||||
)
|
||||
}}
|
||||
}
|
||||
@@ -605,44 +609,20 @@ pub fn server_macro_impl(
|
||||
} else {
|
||||
quote! { concat!("/", #fn_path) }
|
||||
};
|
||||
|
||||
let enable_server_fn_mod_path = option_env!("SERVER_FN_MOD_PATH").is_some();
|
||||
let mod_path = if enable_server_fn_mod_path {
|
||||
quote! {
|
||||
#server_fn_path::const_format::concatcp!(
|
||||
#server_fn_path::const_str::replace!(module_path!(), "::", "/"),
|
||||
"/"
|
||||
)
|
||||
}
|
||||
} else {
|
||||
quote! { "" }
|
||||
};
|
||||
|
||||
let enable_hash = option_env!("DISABLE_SERVER_FN_HASH").is_none();
|
||||
let hash = if enable_hash {
|
||||
quote! {
|
||||
#server_fn_path::xxhash_rust::const_xxh64::xxh64(
|
||||
concat!(env!(#key_env_var), ":", file!(), ":", line!(), ":", column!()).as_bytes(),
|
||||
0
|
||||
)
|
||||
}
|
||||
} else {
|
||||
quote! { "" }
|
||||
};
|
||||
|
||||
let path = quote! {
|
||||
if #fn_path.is_empty() {
|
||||
#server_fn_path::const_format::concatcp!(
|
||||
#prefix,
|
||||
"/",
|
||||
#mod_path,
|
||||
#fn_name_as_str,
|
||||
#hash
|
||||
#server_fn_path::xxhash_rust::const_xxh64::xxh64(
|
||||
concat!(env!(#key_env_var), ":", file!(), ":", line!(), ":", column!()).as_bytes(),
|
||||
0
|
||||
)
|
||||
)
|
||||
} else {
|
||||
#server_fn_path::const_format::concatcp!(
|
||||
#prefix,
|
||||
#mod_path,
|
||||
#fn_path
|
||||
)
|
||||
}
|
||||
@@ -750,12 +730,12 @@ fn output_type(return_ty: &Type) -> Result<&GenericArgument> {
|
||||
|
||||
Err(syn::Error::new(
|
||||
return_ty.span(),
|
||||
"server functions should return Result<T, E> where E: \
|
||||
FromServerFnError",
|
||||
"server functions should return Result<T, ServerFnError> or Result<T, \
|
||||
ServerFnError<E>>",
|
||||
))
|
||||
}
|
||||
|
||||
fn err_type(return_ty: &Type) -> Result<Option<&Type>> {
|
||||
fn err_type(return_ty: &Type) -> Result<Option<&GenericArgument>> {
|
||||
if let syn::Type::Path(pat) = &return_ty {
|
||||
if pat.path.segments[0].ident == "Result" {
|
||||
if let PathArguments::AngleBracketed(args) =
|
||||
@@ -766,8 +746,25 @@ fn err_type(return_ty: &Type) -> Result<Option<&Type>> {
|
||||
return Ok(None);
|
||||
}
|
||||
// Result<T, _>
|
||||
else if let GenericArgument::Type(ty) = &args.args[1] {
|
||||
return Ok(Some(ty));
|
||||
else if let GenericArgument::Type(Type::Path(pat)) =
|
||||
&args.args[1]
|
||||
{
|
||||
if let Some(segment) = pat.path.segments.last() {
|
||||
if segment.ident == "ServerFnError" {
|
||||
let args = &segment.arguments;
|
||||
match args {
|
||||
// Result<T, ServerFnError>
|
||||
PathArguments::None => return Ok(None),
|
||||
// Result<T, ServerFnError<E>>
|
||||
PathArguments::AngleBracketed(args) => {
|
||||
if args.args.len() == 1 {
|
||||
return Ok(Some(&args.args[0]));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -775,8 +772,8 @@ fn err_type(return_ty: &Type) -> Result<Option<&Type>> {
|
||||
|
||||
Err(syn::Error::new(
|
||||
return_ty.span(),
|
||||
"server functions should return Result<T, E> where E: \
|
||||
FromServerFnError",
|
||||
"server functions should return Result<T, ServerFnError> or Result<T, \
|
||||
ServerFnError<E>>",
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user