use serde::{Deserialize, Serialize};
use crate::response::BaseResponse;
use crate::{field_access, impl_default, impl_display, impl_response, VisibilityPolicy};
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Response {
#[serde(flatten)]
base: BaseResponse,
#[serde(skip_serializing_if = "Option::is_none")]
id: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
automatic_new_visibility_policy: Option<VisibilityPolicy>,
}
impl_response!(Response, base);
field_access! {
Response {
id: option { u64 },
automatic_new_visibility_policy: option { VisibilityPolicy },
}
}
impl Response {
pub const fn new() -> Self {
Self {
base: BaseResponse::new(),
id: None,
automatic_new_visibility_policy: None,
}
}
}
impl_default!(Response);
impl_display!(Response);
#[cfg(test)]
mod tests {
use super::*;
use crate::response::{ApiResult, ErrorCode, Response as _};
#[test]
fn test_success_message_response() {
let msg = "test response";
let msg_json = serde_json::to_string(&msg).unwrap();
let result = ApiResult::Success;
let result_json = serde_json::to_string(&result).unwrap();
let id = 42;
let id_json = serde_json::to_string(&id).unwrap();
let response = Response::new()
.with_msg(msg)
.with_result(result)
.with_id(id);
let response_json =
format!(r#"{{"msg":{msg_json},"result":{result_json},"id":{id_json}}}"#);
assert_eq!(serde_json::to_string(&response).unwrap(), response_json);
assert_eq!(
serde_json::from_str::<Response>(&response_json).unwrap(),
response
);
assert_eq!(response.msg(), msg);
assert_eq!(response.result(), result);
assert_eq!(response.code(), None);
assert_eq!(response.id(), Some(id));
}
#[test]
fn test_error_message_response() {
let msg = "test response";
let msg_json = serde_json::to_string(&msg).unwrap();
let result = ApiResult::Error;
let result_json = serde_json::to_string(&result).unwrap();
let code = ErrorCode::BadRequest;
let code_json = serde_json::to_string(&code).unwrap();
let id = 42;
let id_json = serde_json::to_string(&id).unwrap();
let response = Response::new()
.with_msg(msg)
.with_result(result)
.with_code(code)
.with_id(id);
let response_json = format!(
r#"{{"msg":{msg_json},"result":{result_json},"code":{code_json},"id":{id_json}}}"#
);
assert_eq!(serde_json::to_string(&response).unwrap(), response_json);
assert_eq!(
serde_json::from_str::<Response>(&response_json).unwrap(),
response
);
assert_eq!(response.msg(), msg);
assert_eq!(response.result(), result);
assert_eq!(response.code(), Some(code));
assert_eq!(response.id(), Some(id));
}
}