bitwarden_json/
response.rsuse std::error::Error;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Response<T: Serialize + JsonSchema> {
pub success: bool,
pub error_message: Option<String>,
pub data: Option<T>,
}
impl<T: Serialize + JsonSchema> Response<T> {
pub fn new<TErr: Error>(response: Result<T, TErr>) -> Self {
match response {
Ok(data) => Self {
success: true,
error_message: None,
data: Some(data),
},
Err(err) => Self {
success: false,
error_message: Some(err.to_string()),
data: None,
},
}
}
}
impl Response<()> {
pub fn error(message: String) -> Self {
Self {
success: false,
error_message: Some(message),
data: None,
}
}
}
pub(crate) trait ResponseIntoString {
fn into_string(self) -> String;
}
impl<T: Serialize + JsonSchema, E: Error> ResponseIntoString for Result<T, E> {
fn into_string(self) -> String {
Response::new(self).into_string()
}
}
impl<T: Serialize + JsonSchema> ResponseIntoString for Response<T> {
fn into_string(self) -> String {
match serde_json::to_string(&self) {
Ok(ser) => ser,
Err(e) => {
let error = Response::error(format!("Failed to serialize Response: {}", e));
serde_json::to_string(&error).expect("Serialize should be infallible")
}
}
}
}