2024-06-22 17:19:55 +02:00
|
|
|
use serde::Serialize;
|
|
|
|
|
|
|
|
#[derive(Serialize)]
|
|
|
|
pub struct BaseResponse<T: Serialize> {
|
|
|
|
pub version: String,
|
|
|
|
#[serde(flatten)]
|
2024-08-19 14:15:29 +02:00
|
|
|
pub body: T, // T must be a struct (or enum?) TODO from! macro that validates T on compile time
|
2024-06-22 17:19:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Serialize> BaseResponse<T> {
|
|
|
|
pub fn new(version: impl Into<String>, body: T) -> Self {
|
|
|
|
Self {
|
|
|
|
version: version.into(),
|
|
|
|
body,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-19 14:15:29 +02:00
|
|
|
#[macro_export]
|
|
|
|
macro_rules! from {
|
|
|
|
($body:expr) => {
|
|
|
|
BaseResponse::new(env!("CARGO_PKG_VERSION"), $body)
|
|
|
|
};
|
2024-08-14 20:37:10 +02:00
|
|
|
}
|
|
|
|
|
2024-06-30 20:16:17 +02:00
|
|
|
#[cfg(test)]
|
2024-06-22 17:19:55 +02:00
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[derive(Serialize)]
|
|
|
|
struct Response {
|
|
|
|
message: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_base_response_new() {
|
|
|
|
let response = BaseResponse::new(
|
|
|
|
"",
|
|
|
|
Response {
|
|
|
|
message: "Hi".to_string(),
|
|
|
|
},
|
|
|
|
);
|
|
|
|
assert_eq!(response.body.message, "Hi".to_string());
|
|
|
|
}
|
2024-08-19 14:15:29 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_from_macro() {
|
|
|
|
let response = from!(Response {
|
|
|
|
message: "Hi".to_string(),
|
|
|
|
});
|
|
|
|
from!(1); // Should not be allowed
|
|
|
|
assert_eq!(response.version, env!("CARGO_PKG_VERSION"));
|
|
|
|
assert_eq!(response.body.message, "Hi".to_string());
|
|
|
|
}
|
2024-06-22 17:19:55 +02:00
|
|
|
}
|