2024-10-03 15:55:38 -04:00
|
|
|
use std::borrow::Cow;
|
|
|
|
|
2024-08-06 11:08:15 -04:00
|
|
|
use axum::Json;
|
|
|
|
use serde::Serialize;
|
|
|
|
|
2024-10-03 15:55:38 -04:00
|
|
|
use super::AppError;
|
|
|
|
|
2024-08-06 11:08:15 -04:00
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
pub struct ApiResponse<T> {
|
|
|
|
#[serde(rename = "_meta")]
|
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
|
|
pub meta: Option<ApiResponseMetadata>,
|
|
|
|
|
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
|
|
pub data: Option<T>,
|
|
|
|
|
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
2024-10-03 15:55:38 -04:00
|
|
|
pub error: Option<Cow<'static, str>>,
|
2024-08-06 11:08:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> ApiResponse<T> {
|
|
|
|
pub fn new(data: T) -> ApiResponse<T> {
|
|
|
|
Self {
|
|
|
|
meta: None,
|
|
|
|
data: Some(data),
|
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn _new_with_metadata(data: T, meta: ApiResponseMetadata) -> ApiResponse<T> {
|
|
|
|
Self {
|
|
|
|
meta: Some(meta),
|
|
|
|
data: Some(data),
|
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn into_json_response(self) -> Json<ApiResponse<T>> {
|
|
|
|
Json(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ApiResponse<()> {
|
2024-10-03 15:55:38 -04:00
|
|
|
pub fn _new_empty() -> Self {
|
|
|
|
Self {
|
|
|
|
meta: None,
|
|
|
|
data: None,
|
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-06 11:08:15 -04:00
|
|
|
pub fn error(error: &'static str) -> Self {
|
|
|
|
Self {
|
|
|
|
meta: None,
|
|
|
|
data: None,
|
2024-10-03 15:55:38 -04:00
|
|
|
error: Some(error.into()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn new_with_error(error: AppError) -> Self {
|
|
|
|
Self {
|
|
|
|
meta: None,
|
|
|
|
data: None,
|
|
|
|
error: Some(error.to_string().into()),
|
2024-08-06 11:08:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
|
|
pub struct ApiResponseMetadata {}
|