rs_query/
query.rs

1//! Query definition
2
3use crate::{QueryError, QueryKey, QueryOptions, RetryConfig};
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7
8/// Type alias for boxed async query function
9pub type QueryFn<T> =
10    Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<T, QueryError>> + Send>> + Send + Sync>;
11
12/// A query definition.
13///
14/// # Example
15///
16/// ```rust,ignore
17/// let query = Query::new(QueryKey::new("users"), || async {
18///     api::fetch_users().await
19/// })
20/// .stale_time(Duration::from_secs(60));
21/// ```
22pub struct Query<T: Clone + Send + Sync + 'static> {
23    pub key: QueryKey,
24    pub fetch_fn: QueryFn<T>,
25    pub options: QueryOptions,
26}
27
28impl<T: Clone + Send + Sync + 'static> Query<T> {
29    /// Create a new query
30    pub fn new<F, Fut>(key: QueryKey, fetch_fn: F) -> Self
31    where
32        F: Fn() -> Fut + Send + Sync + 'static,
33        Fut: Future<Output = Result<T, QueryError>> + Send + 'static,
34    {
35        Self {
36            key,
37            fetch_fn: Arc::new(move || Box::pin(fetch_fn())),
38            options: QueryOptions::default(),
39        }
40    }
41
42    /// Set stale time
43    pub fn stale_time(mut self, duration: std::time::Duration) -> Self {
44        self.options.stale_time = duration;
45        self
46    }
47
48    /// Set garbage collection time
49    pub fn gc_time(mut self, duration: std::time::Duration) -> Self {
50        self.options.gc_time = duration;
51        self
52    }
53
54    /// Set retry configuration
55    pub fn retry(mut self, config: RetryConfig) -> Self {
56        self.options.retry = config;
57        self
58    }
59
60    /// Enable or disable the query
61    pub fn enabled(mut self, enabled: bool) -> Self {
62        self.options.enabled = enabled;
63        self
64    }
65}