1use crate::{QueryError, QueryKey, QueryOptions, RetryConfig};
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7
8pub type QueryFn<T> =
10 Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<T, QueryError>> + Send>> + Send + Sync>;
11
12pub 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 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 pub fn stale_time(mut self, duration: std::time::Duration) -> Self {
44 self.options.stale_time = duration;
45 self
46 }
47
48 pub fn gc_time(mut self, duration: std::time::Duration) -> Self {
50 self.options.gc_time = duration;
51 self
52 }
53
54 pub fn retry(mut self, config: RetryConfig) -> Self {
56 self.options.retry = config;
57 self
58 }
59
60 pub fn enabled(mut self, enabled: bool) -> Self {
62 self.options.enabled = enabled;
63 self
64 }
65}