Skip to content

Commit

Permalink
Added LazyCache::<T>::new_resource() helper
Browse files Browse the repository at this point in the history
  • Loading branch information
sfisol committed Nov 8, 2024
1 parent 8b988fb commit 750c622
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* `Driver::utc_now` (Gets current UTC timestamp)
* `Driver::timezone_offset` (Gets browsers time zone offset in seconds)
* `chrono::NaiveDate` support in `AutoJsJson`
* `LazyCache::<T>::new_resource()` helper

### Changed

Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM rustlang/rust:nightly-slim as build
FROM rustlang/rust:nightly-slim AS build

RUN apt-get update && apt-get install -y cmake pkg-config libssl-dev

Expand Down
32 changes: 31 additions & 1 deletion crates/vertigo/src/fetch/lazy_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
computed::{context::Context, Value},
get_driver,
struct_mut::ValueMut,
transaction, Computed, DomNode, Instant, Resource, ToComputed,
transaction, Computed, DomNode, Instant, JsJsonDeserialize, Resource, ToComputed,
};

use super::request_builder::{RequestBody, RequestBuilder};
Expand Down Expand Up @@ -262,3 +262,33 @@ impl<T: PartialEq + Clone> LazyCache<T> {
})
}
}

impl<T: JsJsonDeserialize> LazyCache<T> {
/// Helper to easily create a lazy cache of Vec<T> deserialized from provided URL base and route
///
/// ```rust
/// use vertigo::{Computed, LazyCache, RequestBuilder, AutoJsJson, Resource};
///
/// #[derive(AutoJsJson, PartialEq, Clone)]
/// pub struct Model {
/// id: i32,
/// name: String,
/// }
///
/// let posts = LazyCache::<Vec<Model>>::new_resource("https://some.api", "/posts", 60);
/// ```
pub fn new_resource(api: &str, path: &str, ttl: u64) -> Self {
let url = [api, path].concat();

LazyCache::new(
get_driver().request_get(url).ttl_seconds(ttl),
|status, body| {
if status == 200 {
Some(body.into::<T>())
} else {
None
}
},
)
}
}
8 changes: 7 additions & 1 deletion crates/vertigo/src/router.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{computed::Value, get_driver, Computed, DomNode, EmbedDom, Reactive, ToComputed};

/// Router based on hash part of current location.
/// Router based on path or hash part of current location.
///
/// ```rust
/// use vertigo::{dom, Computed, Reactive, Value, DomNode};
Expand Down Expand Up @@ -150,3 +150,9 @@ impl<T: Clone + PartialEq + ToString + From<String>> EmbedDom for Router<T> {
self.route.embed()
}
}

impl<T: Clone + PartialEq + ToString + From<String>> Default for Router<T> {
fn default() -> Self {
Router::new(true)
}
}

0 comments on commit 750c622

Please sign in to comment.