pub struct CookieStore<T, J> { /* private fields */ }Expand description
A typed value backed by a single cookie.
Holds a value of type T in memory. commit serializes it
as JSON and writes it through the configured Cookies jar.
Reads and mutations affect only the in-memory value until you commit.
Dropping the store or calling rollback discards those
changes. Call remove to delete the cookie instead.
Obtain one by reading the incoming cookie through cookie_store:
// src/app/api/cart.rs
use serde::{Deserialize, Serialize};
use topcoat::{
Result,
context::Cx,
cookie::{cookie_store, private_cookies},
router::route,
};
#[derive(Default, Serialize, Deserialize)]
struct Cart {
items: Vec<String>,
}
#[route(POST)]
async fn add_item(cx: &Cx) -> Result<String> {
// `commit` writes the cookie and hands the value back; without it the
// change is discarded.
let cart = cookie_store::<Cart, _>(private_cookies(cx), "cart")
.parse_or_default()
.update(|cart| cart.items.push("widget".to_owned()))
.commit()?;
Ok(format!("{} items in cart", cart.items.len()))
}Implementations§
Source§impl<T, J> CookieStore<T, J>
impl<T, J> CookieStore<T, J>
Sourcepub fn new(jar: J, key: impl Into<Cow<'static, str>>, value: T) -> Self
pub fn new(jar: J, key: impl Into<Cow<'static, str>>, value: T) -> Self
Builds a store around an already-known value.
Most code instead goes through cookie_store and one of the parse*
methods, which read the existing cookie first.
Sourcepub fn set(self, value: T) -> Self
pub fn set(self, value: T) -> Self
Replaces the in-memory value, returning the store so calls can be chained.
Like every mutation, this is not persisted until commit.
Sourcepub fn update<F>(self, f: F) -> Self
pub fn update<F>(self, f: F) -> Self
Mutates the in-memory value in place, returning the store so calls can be chained.
Like every mutation, this is not persisted until commit.
let cart = cookie_store::<Cart, _>(private_cookies(cx), "cart")
.parse_or_default()
.update(|cart| cart.items.push("widget".to_owned()))
.commit()?;Sourcepub fn commit(self) -> Result<T, Error>
pub fn commit(self) -> Result<T, Error>
Serializes the current value, queues it on the backing jar as a
Set-Cookie, and returns the value.
Call this after any work that must succeed before saving the value.
§Errors
Returns Err if serializing T to JSON fails.