use super::*;
impl<T> ServiceResponse<T>
where
T: Serialize,
{
pub fn success(data: T) -> Self {
Self {
success: true,
data: Some(data),
error: None,
status_code: None,
#[cfg(feature = "timestamp")]
timestamp: Some(chrono::Utc::now().timestamp()),
}
}
pub fn success_with_status(data: T, code: u16) -> Self {
debug_assert!(
(100..=999).contains(&code),
"success_with_status code must be in 100..=999, got {}",
code
);
Self {
success: true,
data: Some(data),
error: None,
status_code: Some(code),
#[cfg(feature = "timestamp")]
timestamp: Some(chrono::Utc::now().timestamp()),
}
}
pub fn error(error: ServiceError) -> Self {
Self {
success: false,
data: None,
error: Some(error),
status_code: None,
#[cfg(feature = "timestamp")]
timestamp: Some(chrono::Utc::now().timestamp()),
}
}
pub fn status_code(&self) -> Option<u16> {
self.status_code
}
pub fn with_status_code_opt(mut self, code: Option<u16>) -> Self {
if self.status_code.is_none() {
self.status_code = code;
}
self
}
pub fn is_success(&self) -> bool {
self.success
}
pub fn data(&self) -> Option<&T> {
self.data.as_ref()
}
pub fn error_ref(&self) -> Option<&ServiceError> {
self.error.as_ref()
}
#[cfg(feature = "timestamp")]
pub fn timestamp(&self) -> Option<i64> {
self.timestamp
}
}
impl ServiceError {
pub fn new(code: impl Into<String>, message: impl Into<String>, http_status: u16) -> Self {
Self {
code: code.into(),
message: message.into(),
details: None,
http_status,
}
}
pub fn with_details(
code: impl Into<String>,
message: impl Into<String>,
details: serde_json::Value,
http_status: u16,
) -> Self {
Self {
code: code.into(),
message: message.into(),
details: Some(details),
http_status,
}
}
pub fn code(&self) -> &str {
&self.code
}
pub fn message(&self) -> &str {
&self.message
}
pub fn details(&self) -> Option<&serde_json::Value> {
self.details.as_ref()
}
pub fn http_status(&self) -> u16 {
self.http_status
}
}