Object Transfer Library for Rust
CI/CD Status
| Service |
Status |
| Crates.io |
 |
| Code Test |
 |
Description
This library provides a simple and efficient way to transfer objects between
different parts of an application or between different applications through
message brokers like NATS.
It supports serialization and/or deserialization of various data formats, making
it easy to send and/or receive complex data structures.
Installation
If you have cargo-edit installed, you can add this library to your project
by running:
cargo add object_transfer
Alternatively, you can manually add the following line to your Cargo.toml file:
[dependencies]
object_transfer = "x.x.x"
where x.x.x is the desired version of the library. For the latst version,
please check Crates.io.
Example of Use
use ::std::sync::Arc;
use ::object_transfer::traits::{PubTrait, SubTrait};
use ::object_transfer::error::{PubError, SubError};
use ::serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct MyData {
pub id: u32,
pub name: String,
}
async fn publish_example(
publisher: Arc<dyn PubTrait + Send + Sync>,
) -> Result<MyData, PubError> {
let data = MyData { id: 1, name: "Example".to_string() };
publisher.publish(&data).await.unwrap();
}
async fn subscribe_example(
subscriber: Arc<dyn SubTrait<Item = MyData> + Send + Sync>,
) -> Result<MyData, SubError> {
let mut stream = subscriber.subscribe().await.unwrap();
while let Some(data) = stream.next().await {
match data {
Ok(my_data) => println!("Received data: {:?}", my_data),
Err(e) => eprintln!("Error receiving data: {}", e),
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = async_nats::connect("demo.nats.io").await?;
let js = Arc::new(async_nats::jetstream::new(client));
let options = Arc::new(
AckSubOptions::new(Format::JSON, Arc::from("events"))
.subjects(vec!["mydata.created"])
.durable_name("user-created")
.auto_ack(false), );
let fetcher = Arc::new(SubFetcher::new(js, options.clone()).await?);
let unsub = Some(fetcher.clone() as Arc<dyn UnSubTrait + Send + Sync>);
let subscriber: Sub<MyData> = Sub::new(fetcher, unsub, options);
let publisher: Pub<MyData> = Pub::new(
Arc::new(js),
"mydata.created",
Format::JSON,
);
let event = MyData {
id: 42,
name: "Jane Doe".to_string(),
};
publisher.publish(&event).await?;
let mut stream = subscriber.subscribe().await?;
if let Some(Ok((event, ack))) = stream.next().await {
println!("received {:?}", event);
ack.ack().await?;
} else {
println!("no event received");
}
}