use http::{Response, StatusCode, header::CONTENT_TYPE};
use serde::Serialize;
pub trait IntoResponse {
fn into_response(self) -> Result<Response<Vec<u8>>, serde_json::Error>
where
Self: Serialize + Sized,
{
let status = self.http_status();
let body = serde_json::to_vec(&self)?;
Ok(http::Response::builder()
.status(status)
.header(CONTENT_TYPE, "application/json")
.body(body)
.expect("status code and header value are always valid"))
}
fn http_status(&self) -> StatusCode;
}
#[derive(Serialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Status {
Success,
Fail,
Error,
}
#[cfg(test)]
mod tests {
use super::*;
use http::header::CONTENT_TYPE;
use serde_json::{Value, from_slice, json};
use crate::success::Success;
struct AlwaysFailsToSerialise;
impl Serialize for AlwaysFailsToSerialise {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Err(serde::ser::Error::custom("forced serialisation failure"))
}
}
fn to_json<R: IntoResponse + Serialize>(response: R) -> Value {
let http_response = response
.into_response()
.expect("serialisation should succeed");
from_slice(http_response.body()).expect("body should be valid JSON")
}
#[test]
fn http_status_field_is_not_serialised() {
let response = Success::new(
Some(json!({"title": "End of the World Sun"})),
StatusCode::IM_A_TEAPOT,
);
assert!(to_json(response).get("http_status").is_none());
}
#[test]
fn into_response_reflects_provided_status_code() {
let response = Success::new(
Some(json!({"title": "Outlier/EOTWS_Variation1"})),
StatusCode::NOT_FOUND,
);
let http_response = response
.into_response()
.expect("serialisation should succeed");
assert_eq!(http_response.status(), StatusCode::NOT_FOUND);
}
#[test]
fn into_response_sets_json_content_type() {
let response = Success::new(
Some(json!({"writers": ["65daysofstatic"]})),
StatusCode::OK,
);
let http_response = response
.into_response()
.expect("serialisation should succeed");
assert_eq!(
http_response.headers().get(CONTENT_TYPE).unwrap(),
"application/json"
);
}
#[test]
fn into_response_propagates_serialisation_errors() {
let response =
Success::new(Some(AlwaysFailsToSerialise), StatusCode::OK);
assert!(response.into_response().is_err());
}
}