Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Integrate Retries and Error Handling #11

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ cfg-if = "1"
js-sys = {version = "0.3.64", optional = true}
gloo-timers = { version = "0.2.6", optional = true, features = ["futures"] }
tokio = { version = "1.29.1", optional = true, features = ["time"]}
dyn-clone = "1.0.13"

[features]
hydrate = ["dep:js-sys", "dep:gloo-timers"]
ssr = ["dep:tokio"]

[package.metadata.docs.rs]
all-features = true
all-features = true
32 changes: 16 additions & 16 deletions example/start-axum/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@ pub fn App(cx: Scope) -> impl IntoView {
#[component]
fn HomePage(cx: Scope) -> impl IntoView {
let invalidate_one = move |_| {
use_query_client(cx).invalidate_query::<u32, String>(&1);
// use_query_client(cx).invalidate_query::<u32, String>(&1);
};

let prefetch_two = move |_| {
use_query_client(cx).prefetch_query(cx, || 2, get_post_unwrapped, true);
// use_query_client(cx).prefetch_query(cx, || 2, get_post_unwrapped, true);
};

view! { cx,
Expand Down Expand Up @@ -136,17 +136,18 @@ fn HomePage(cx: Scope) -> impl IntoView {
fn use_post_query(
cx: Scope,
key: impl Fn() -> u32 + 'static,
) -> QueryResult<Option<String>, impl RefetchFn> {
use_query(
) -> QueryResult<String, ServerFnError, impl RefetchFn> {
use_query_with_retry(
cx,
key,
get_post_unwrapped,
get_post,
QueryOptions {
default_value: None,
refetch_interval: None,
resource_option: ResourceOption::NonBlocking,
stale_time: Some(Duration::from_secs(5)),
cache_time: Some(Duration::from_secs(60)),
retry: Schedules::recur(3).build(),
},
)
}
Expand All @@ -159,11 +160,15 @@ async fn get_post_unwrapped(id: u32) -> Option<String> {
#[server(GetPost, "/api")]
pub async fn get_post(id: u32) -> Result<String, ServerFnError> {
use leptos_query::Instant;

log!("Fetching post: {}", id);
tokio::time::sleep(Duration::from_millis(2000)).await;
let instant = Instant::now();
Ok(format!("Post {}: Timestamp {}", id, instant))
// random number, if it's 0, we'll return an error.
// if random == 0 {
return Err(ServerFnError::ServerError("Random error".into()));
// } else {
// log!("Fetching post: {}", id);
// let instant = Instant::now();
// Ok(format!("Post {}: Timestamp {}", id, instant))
// }
}

#[component]
Expand Down Expand Up @@ -222,16 +227,11 @@ fn Post(cx: Scope, #[prop(into)] post_id: MaybeSignal<u32>) -> impl IntoView {
view! { cx, <h2>"Loading..."</h2> }
}>
<h2>
{
{move || {
data
.get()
.map(|post| {
match post {
Some(post) => post,
None => "Not Found".into(),
}
})
}
}
</h2>
</Transition>
</div>
Expand Down
10 changes: 5 additions & 5 deletions example/start-axum/src/todo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ fn AllTodos(cx: Scope) -> impl IntoView {
async move {
let _ = delete_todo(id).await;
refetch();
use_query_client(cx).invalidate_query::<u32, TodoResponse>(&id);
// use_query_client(cx).invalidate_query::<u32, TodoResponse>(&id);
}
});

Expand Down Expand Up @@ -203,14 +203,14 @@ fn AddTodoComponent(cx: Scope) -> impl IntoView {
if let Some(Ok(todo)) = response.get() {
let id = todo.id;
// Invalidate individual TodoResponse.
client.clone().invalidate_query::<u32, TodoResponse>(id);
// client.clone().invalidate_query::<u32, TodoResponse>(id);

// Invalidate AllTodos.
client.clone().invalidate_query::<(), Vec<Todo>>(());
// client.clone().invalidate_query::<(), Vec<Todo>>(());

// Optimistic update.
let as_response = Ok(Some(todo));
client.set_query_data::<u32, TodoResponse>(id, |_| Some(as_response));
// let as_response = Ok(Some(todo));
// client.set_query_data::<u32, TodoResponse>(id, |_| Some(as_response));
}
});

Expand Down
18 changes: 10 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,16 @@ mod query_executor;
mod query_options;
mod query_result;
mod query_state;
mod schedule;
mod use_query;
mod util;

pub use instant::*;
use query::*;
pub use query_client::*;
pub use query_executor::*;
pub use query_options::*;
pub use query_result::*;
pub use query_state::*;
pub use use_query::*;
pub use crate::instant::*;
use crate::query::*;
pub use crate::query_client::*;
pub use crate::query_executor::*;
pub use crate::query_options::*;
pub use crate::query_result::*;
pub use crate::query_state::*;
pub use crate::schedule::*;
pub use crate::use_query::*;
21 changes: 12 additions & 9 deletions src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,35 @@ use std::{cell::Cell, rc::Rc, time::Duration};
use crate::{ensure_valid_stale_time, QueryOptions, QueryState};

#[derive(Clone)]
pub(crate) struct Query<K, V>
pub(crate) struct Query<K, V, E>
where
K: 'static,
V: 'static,
E: 'static,
{
pub(crate) key: K,
// State.
pub(crate) observers: Rc<Cell<usize>>,
pub(crate) state: RwSignal<QueryState<V>>,
pub(crate) state: RwSignal<QueryState<V, E>>,
// Config.
pub(crate) stale_time: RwSignal<Option<Duration>>,
pub(crate) cache_time: RwSignal<Option<Duration>>,
pub(crate) refetch_interval: RwSignal<Option<Duration>>,
}

impl<K: PartialEq, V> PartialEq for Query<K, V> {
impl<K: PartialEq, V, E> PartialEq for Query<K, V, E> {
fn eq(&self, other: &Self) -> bool {
self.key == other.key
}
}

impl<K: PartialEq, V> Eq for Query<K, V> {}
impl<K: PartialEq, V, E> Eq for Query<K, V, E> {}

impl<K, V> Query<K, V>
impl<K, V, E> Query<K, V, E>
where
K: Clone + 'static,
V: Clone + 'static,
E: Clone + 'static,
{
pub(crate) fn new(cx: Scope, key: K) -> Self {
let stale_time = create_rw_signal(cx, None);
Expand All @@ -50,10 +52,11 @@ where
}
}

impl<K, V> Query<K, V>
impl<K, V, E> Query<K, V, E>
where
K: Clone + 'static,
V: Clone + 'static,
E: Clone + 'static,
{
/// Marks the resource as invalid, which will cause it to be refetched on next read.
pub(crate) fn mark_invalid(&self) -> bool {
Expand All @@ -65,7 +68,7 @@ where
}
}

pub(crate) fn overwrite_options(&self, options: QueryOptions<V>) {
pub(crate) fn overwrite_options(&self, options: QueryOptions<V, E>) {
let stale_time = ensure_valid_stale_time(&options.stale_time, &options.cache_time);

self.stale_time.set(stale_time);
Expand All @@ -77,7 +80,7 @@ where
// The lowest stale time & refetch interval will be used.
// When the scope is dropped, the stale time & refetch interval will be reset to the previous value (if they existed).
// Cache time behaves differently. It will only use the minimum cache time found.
pub(crate) fn update_options(&self, cx: Scope, options: QueryOptions<V>) {
pub(crate) fn update_options(&self, cx: Scope, options: QueryOptions<V, E>) {
// Use the minimum cache time.
match (self.cache_time.get_untracked(), options.cache_time) {
(Some(current), Some(new)) if new < current => self.cache_time.set(Some(new)),
Expand Down Expand Up @@ -123,7 +126,7 @@ where
}
}

impl<K, V> Query<K, V> {
impl<K, V, E> Query<K, V, E> {
pub(crate) fn dispose(&self) {
self.state.dispose();
self.stale_time.dispose();
Expand Down
Loading