Skip to content

Commit

Permalink
Sessions: add generic setters to client, add generic remove to client…
Browse files Browse the repository at this point in the history
… and server (#358)
  • Loading branch information
bosukas authored Oct 30, 2024
1 parent 1339081 commit d8f552f
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions libs/pavex_session/src/session_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,19 @@ impl<'session> ClientSessionState<'session> {
pub struct ClientSessionStateMut<'session>(&'session mut ClientState);

impl<'session> ClientSessionStateMut<'session> {
/// Set a value in the client-side state for the given key.
///
/// If the key already exists, the value is updated and the old raw value is returned.
/// If the value cannot be serialized, an error is returned.
pub fn set<T: Serialize>(
&mut self,
key: String,
value: T
) -> Result<Option<Value>, serde_json::Error> {
let value = serde_json::to_value(value)?;
Ok(self.set_value(key, value))
}

/// Set a value in the client-side state for the given key.
///
/// If the key already exists, the value is updated and the old value is returned.
Expand All @@ -292,6 +305,16 @@ impl<'session> ClientSessionStateMut<'session> {
}
}

/// Remove the value associated with `key` from the client-side state.
///
/// If the key exists, the removed value is returned.
/// If the removed value cannot be serialized, an error is returned.
pub fn remove<T: DeserializeOwned>(&mut self, key: &str) -> Result<Option<T>, serde_json::Error> {
self.remove_value(key)
.map(|value| serde_json::from_value(value))
.transpose()
}

/// Remove the value associated with `key` from the client-side state.
///
/// If the key exists, the removed value is returned.
Expand Down Expand Up @@ -419,6 +442,17 @@ impl<'session, 'store> ServerSessionState<'session, 'store> {
Ok(old_value)
}

/// Remove the value associated with `key` from the server-side state.
///
/// If the key exists, the removed value is returned.
/// If the removed value cannot be serialized, an error is returned.
pub async fn remove<T: DeserializeOwned>(&mut self, key: &str) -> Result<Option<T>, LoadError> {
self.remove_value(key).await?
.map(serde_json::from_value)
.transpose()
.map_err(LoadError::DeserializationError)
}

/// Remove the value associated with `key` from the server-side state.
///
/// If the key exists, the removed value is returned.
Expand Down

0 comments on commit d8f552f

Please sign in to comment.