#[cfg(test)]
mod tests;
use serde::{de::DeserializeOwned, Serialize};
use crate::core::New;
use crate::error::{AppError, IntoResponse};
use crate::extract::FromRequest;
use crate::mime_type::MimeType;
use crate::range::Range;
use crate::request::Request;
use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
#[derive(Debug)]
pub struct Json<T>(pub T);
impl<T> std::ops::Deref for Json<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> std::ops::DerefMut for Json<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T: DeserializeOwned> Json<T> {
pub fn from_request(request: &Request) -> Result<Json<T>, Response> {
serde_json::from_slice(&request.body)
.map(Json)
.map_err(|e| AppError::BadRequest(e.to_string()).into_response())
}
}
impl<T: DeserializeOwned> FromRequest for Json<T> {
fn from_request(request: &Request) -> Result<Self, Response> {
Json::from_request(request)
}
}
impl<T: Serialize> Json<T> {
pub fn into_response(self) -> Response {
match serde_json::to_vec(&self.0) {
Ok(body) => {
let mut response = Response::new();
response.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
response.reason_phrase =
STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
response.content_range_list = vec![Range::get_content_range(
body,
MimeType::APPLICATION_JSON.to_string(),
)];
response
}
Err(e) => AppError::Internal(e.to_string()).into_response(),
}
}
}