rust-lib/src/axum/response.rs

56 lines
1.3 KiB
Rust
Raw Normal View History

2024-06-22 17:19:55 +02:00
use {
crate::serde::response::BaseResponse,
axum::{
response::{IntoResponse, Response},
Json,
},
serde::Serialize,
};
impl<T: Serialize> IntoResponse for BaseResponse<T> {
fn into_response(self) -> Response {
Json(self).into_response()
}
}
#[cfg(test)]
2024-06-22 17:19:55 +02:00
mod tests {
use axum::http::header::CONTENT_TYPE;
use axum::http::{HeaderValue, StatusCode};
use axum::response::IntoResponse;
2024-08-27 00:21:25 +02:00
use mime::APPLICATION_JSON;
2024-06-22 17:19:55 +02:00
use serde::Serialize;
use crate::serde::response::BaseResponse;
#[derive(Serialize)]
struct Response {
message: String,
}
#[test]
fn test_into_response() {
let response = BaseResponse::new(
"",
Response {
message: "Hi".to_string(),
},
);
let json_response = response.into_response();
assert_eq!(json_response.status(), StatusCode::OK);
assert_eq!(
json_response.headers().get(CONTENT_TYPE),
2024-08-27 00:21:25 +02:00
Some(&HeaderValue::from_static(APPLICATION_JSON.as_ref()))
2024-06-22 17:19:55 +02:00
);
}
#[test]
fn test_into_response_with_primitive() {
let response = BaseResponse::new("", 42);
assert_eq!(
response.into_response().status(),
StatusCode::INTERNAL_SERVER_ERROR
);
}
}