use bytes::BufMut;
use crate::Schema;
#[cfg(feature = "schemars")]
mod schemars;
pub trait Encode {
type Error: std::error::Error;
fn get_schema() -> Option<Schema>;
fn get_message_encoding() -> String;
fn encode(&self, buf: &mut impl BufMut) -> Result<(), Self::Error>;
fn encoded_len(&self) -> Option<usize> {
None
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::channel_builder::ChannelBuilder;
use crate::{Context, Schema};
use serde::Serialize;
use tracing_test::traced_test;
#[derive(Debug, Serialize)]
struct TestMessage {
msg: String,
count: u32,
}
impl Encode for TestMessage {
type Error = serde_json::Error;
fn get_schema() -> Option<Schema> {
Some(Schema::new(
"TextMessage",
"jsonschema",
br#"{
"type": "object",
"properties": {
"msg": {"type": "string"},
"count": {"type": "number"},
},
}"#,
))
}
fn get_message_encoding() -> String {
"json".to_string()
}
fn encode(&self, buf: &mut impl BufMut) -> Result<(), Self::Error> {
serde_json::to_writer(buf.writer(), self)
}
}
#[traced_test]
#[test]
fn test_json_typed_channel() {
let ctx = Context::new();
let channel = ChannelBuilder::new("topic2")
.context(&ctx)
.build::<TestMessage>();
let message = TestMessage {
msg: "Hello, world!".to_string(),
count: 42,
};
channel.log(&message);
assert!(!logs_contain("error logging message"));
}
}