fix (backend-rs): Redis streaming

This commit is contained in:
naskya 2024-04-20 09:54:02 +09:00
parent f13df7e202
commit 2b0668dacd
No known key found for this signature in database
GPG Key ID: 712D413B3A9FED5C
2 changed files with 19 additions and 18 deletions

View File

@ -16,5 +16,5 @@ pub fn add_note_to_antenna(antenna_id: &str, note: &note::Model) -> Result<(), E
let stream = Stream::Antenna {
id: antenna_id.to_string(),
};
publish(&stream, Some("note"), Some(serde_json::to_value(note)?))
publish(&stream, Some("note"), Some(serde_json::to_string(note)?))
}

View File

@ -1,3 +1,4 @@
use crate::config::server::CONFIG;
use crate::database::redis_conn;
use redis::{Commands, RedisError};
@ -35,33 +36,33 @@ pub enum Stream {
pub enum Error {
#[error("Redis error: {0}")]
RedisError(#[from] RedisError),
#[error("Json serialization error: {0}")]
#[error("Json (de)serialization error: {0}")]
JsonError(#[from] serde_json::Error),
#[error("Value error: {0}")]
ValueError(String),
}
pub fn publish(
channel: &Stream,
kind: Option<&str>,
value: Option<serde_json::Value>,
) -> Result<(), Error> {
#[derive(serde::Serialize)]
struct Message {
r#type: String,
body: Option<serde_json::Value>,
}
pub fn publish(channel: &Stream, kind: Option<&str>, value: Option<String>) -> Result<(), Error> {
let message = if let Some(kind) = kind {
serde_json::to_value(Message {
r#type: kind.to_string(),
body: value,
})?
format!(
"{{ \"type\": \"{}\", \"body\": {} }}",
kind,
match value {
Some(v) => v,
None => "null".to_string(),
}
)
} else {
value.ok_or(Error::ValueError("Invalid streaming message".to_string()))?
};
redis_conn()?.publish(channel.to_string(), message.to_string())?;
redis_conn()?.publish(
&CONFIG.host,
format!(
"{{ \"channel\": \"{}\", \"message\": {} }}",
channel, message,
),
)?;
Ok(())
}