use serde::{Deserialize, Serialize};
use crate::response::BaseResponse;
use crate::{field_access, impl_response};
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Response {
#[serde(flatten)]
base: BaseResponse,
rendered: Option<String>,
}
impl Response {
pub const fn new() -> Self {
Self {
base: BaseResponse::new(),
rendered: None,
}
}
}
impl Default for Response {
fn default() -> Self {
Self::new()
}
}
impl_response!(Response, base);
field_access! {
Response {
rendered: option_cow_deref { str, String },
}
}
impl std::fmt::Display for Response {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
serde_json::to_string(self)
.map_err(|_| std::fmt::Error)
.and_then(|s| write!(f, "{s}"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_response() {
let response = Response::new().with_rendered("<p>test message</p>");
let response_json = response.to_string();
assert_eq!(serde_json::to_string(&response).unwrap(), response_json);
assert_eq!(
serde_json::from_str::<Response>(&response_json).unwrap(),
response
);
}
}