use crate::{
error::IIIError,
iii::III,
types::{StreamUpdateInput, UpdateOp, UpdateResult},
};
#[derive(Clone)]
pub struct Streams {
iii: III,
}
impl Streams {
pub fn new(iii: III) -> Self {
Self { iii }
}
pub async fn update(
&self,
key: impl Into<String>,
ops: Vec<UpdateOp>,
) -> Result<UpdateResult, IIIError> {
let input = StreamUpdateInput {
key: key.into(),
ops,
};
let result = self.iii.call("stream.update", input).await?;
serde_json::from_value(result).map_err(|e| IIIError::Serde(e.to_string()))
}
pub async fn increment(
&self,
key: impl Into<String>,
field: impl Into<String>,
by: i64,
) -> Result<UpdateResult, IIIError> {
self.update(key, vec![UpdateOp::increment(field.into(), by)])
.await
}
pub async fn decrement(
&self,
key: impl Into<String>,
field: impl Into<String>,
by: i64,
) -> Result<UpdateResult, IIIError> {
self.update(key, vec![UpdateOp::decrement(field.into(), by)])
.await
}
pub async fn set_field(
&self,
key: impl Into<String>,
field: impl Into<String>,
value: impl Into<serde_json::Value>,
) -> Result<UpdateResult, IIIError> {
self.update(key, vec![UpdateOp::set(field.into(), value.into())])
.await
}
pub async fn remove_field(
&self,
key: impl Into<String>,
field: impl Into<String>,
) -> Result<UpdateResult, IIIError> {
self.update(key, vec![UpdateOp::remove(field.into())]).await
}
pub async fn merge(
&self,
key: impl Into<String>,
value: impl Into<serde_json::Value>,
) -> Result<UpdateResult, IIIError> {
self.update(key, vec![UpdateOp::merge(value.into())]).await
}
}
#[derive(Debug, Clone, Default)]
pub struct UpdateBuilder {
ops: Vec<UpdateOp>,
}
impl UpdateBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn set(mut self, path: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
self.ops.push(UpdateOp::set(path.into(), value.into()));
self
}
pub fn increment(mut self, path: impl Into<String>, by: i64) -> Self {
self.ops.push(UpdateOp::increment(path.into(), by));
self
}
pub fn decrement(mut self, path: impl Into<String>, by: i64) -> Self {
self.ops.push(UpdateOp::decrement(path.into(), by));
self
}
pub fn remove(mut self, path: impl Into<String>) -> Self {
self.ops.push(UpdateOp::remove(path.into()));
self
}
pub fn merge(mut self, value: impl Into<serde_json::Value>) -> Self {
self.ops.push(UpdateOp::merge(value.into()));
self
}
pub fn build(self) -> Vec<UpdateOp> {
self.ops
}
}