use serde::Serialize; use crate::error::{AppError, AppResult}; use super::NatsQueue; pub struct PublishResult { pub stream: String, pub sequence: u64, } impl NatsQueue { pub async fn publish(&self, subject: &str, payload: &[u8]) -> AppResult { let subject = subject.to_string(); let ack = self .inner .js .publish(subject.clone(), payload.to_vec().into()) .await .map_err(|e| AppError::Config(format!("publish to {subject} failed: {e}")))? .await .map_err(|e| AppError::Config(format!("publish ack for {subject} failed: {e}")))?; Ok(PublishResult { stream: ack.stream, sequence: ack.sequence, }) } pub async fn publish_json( &self, subject: &str, payload: &T, ) -> AppResult { let data = serde_json::to_vec(payload)?; self.publish(subject, &data).await } pub async fn publish_with_headers( &self, subject: &str, payload: &[u8], headers: Vec<(String, String)>, ) -> AppResult { let subject = subject.to_string(); let mut nats_headers = async_nats::HeaderMap::new(); for (k, v) in headers { nats_headers.insert(k, v); } let ack = self .inner .js .publish_with_headers(subject.clone(), nats_headers, payload.to_vec().into()) .await .map_err(|e| AppError::Config(format!("publish to {subject} failed: {e}")))? .await .map_err(|e| AppError::Config(format!("publish ack for {subject} failed: {e}")))?; Ok(PublishResult { stream: ack.stream, sequence: ack.sequence, }) } }