1
0
Fork 0
mirror of https://gitlab.com/msrd0/gotham-restful.git synced 2025-04-20 06:54:46 +00:00

response can have a different mime type than json

This commit is contained in:
Dominic 2019-10-19 20:23:25 +02:00
parent bb5f58e97d
commit 656595711c
Signed by: msrd0
GPG key ID: DCC8C247452E98F9
2 changed files with 90 additions and 39 deletions

View file

@ -6,12 +6,40 @@ use serde::Serialize;
use serde_json::error::Error as SerdeJsonError;
use std::error::Error;
pub struct Response
{
pub status : StatusCode,
pub body : String,
pub mime : Option<Mime>
}
impl Response
{
pub fn json(status : StatusCode, body : String) -> Self
{
Self {
status,
body,
mime: Some(APPLICATION_JSON)
}
}
pub fn no_content() -> Self
{
Self {
status: StatusCode::NO_CONTENT,
body: String::new(),
mime: None
}
}
}
/// A trait provided to convert a resource's result to json.
pub trait ResourceResult
{
/// Turn this into a response that can be returned to the browser. This api will likely
/// change in the future.
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError>;
fn to_response(&self) -> Result<Response, SerdeJsonError>;
/// Return a list of supported mime types.
fn accepted_types() -> Option<Vec<Mime>>
@ -59,13 +87,13 @@ impl<T : ToString> From<T> for ResourceError
impl<R : ResourceType, E : Error> ResourceResult for Result<R, E>
{
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError>
fn to_response(&self) -> Result<Response, SerdeJsonError>
{
Ok(match self {
Ok(r) => (StatusCode::OK, serde_json::to_string(r)?),
Ok(r) => Response::json(StatusCode::OK, serde_json::to_string(r)?),
Err(e) => {
let err : ResourceError = e.into();
(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?)
Response::json(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?)
}
})
}
@ -119,9 +147,9 @@ impl<T> From<T> for Success<T>
impl<T : ResourceType> ResourceResult for Success<T>
{
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError>
fn to_response(&self) -> Result<Response, SerdeJsonError>
{
Ok((StatusCode::OK, serde_json::to_string(&self.0)?))
Ok(Response::json(StatusCode::OK, serde_json::to_string(&self.0)?))
}
fn accepted_types() -> Option<Vec<Mime>>
@ -169,9 +197,9 @@ impl From<()> for NoContent
impl ResourceResult for NoContent
{
/// This will always be a _204 No Content_ together with an empty string.
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError>
fn to_response(&self) -> Result<Response, SerdeJsonError>
{
Ok((Self::default_status(), "".to_string()))
Ok(Response::no_content())
}
/// Returns the schema of the `()` type.
@ -191,15 +219,15 @@ impl ResourceResult for NoContent
impl<E : Error> ResourceResult for Result<NoContent, E>
{
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError>
fn to_response(&self) -> Result<Response, SerdeJsonError>
{
Ok(match self {
Ok(_) => (Self::default_status(), "".to_string()),
match self {
Ok(nc) => nc.to_response(),
Err(e) => {
let err : ResourceError = e.into();
(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?)
Ok(Response::json(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?))
}
})
}
}
#[cfg(feature = "openapi")]
@ -236,44 +264,49 @@ mod test
fn resource_result_ok()
{
let ok : Result<Msg, MsgError> = Ok(Msg::default());
let (status, json) = ok.to_response().expect("didn't expect error response");
assert_eq!(status, StatusCode::OK);
assert_eq!(json, r#"{"msg":""}"#);
let res = ok.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
assert_eq!(res.body, r#"{"msg":""}"#);
assert_eq!(res.mime, Some(APPLICATION_JSON));
}
#[test]
fn resource_result_err()
{
let err : Result<Msg, MsgError> = Err(MsgError::default());
let (status, json) = err.to_response().expect("didn't expect error response");
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(json, format!(r#"{{"error":true,"message":"{}"}}"#, err.unwrap_err()));
let res = err.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(res.body, format!(r#"{{"error":true,"message":"{}"}}"#, err.unwrap_err()));
assert_eq!(res.mime, Some(APPLICATION_JSON));
}
#[test]
fn success_always_successfull()
{
let success : Success<Msg> = Msg::default().into();
let (status, json) = success.to_response().expect("didn't expect error response");
assert_eq!(status, StatusCode::OK);
assert_eq!(json, r#"{"msg":""}"#);
let res = success.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
assert_eq!(res.body, r#"{"msg":""}"#);
assert_eq!(res.mime, Some(APPLICATION_JSON));
}
#[test]
fn no_content_has_empty_json()
fn no_content_has_empty_response()
{
let no_content = NoContent::default();
let (status, json) = no_content.to_response().expect("didn't expect error response");
assert_eq!(status, StatusCode::NO_CONTENT);
assert_eq!(json, "");
let res = no_content.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::NO_CONTENT);
assert_eq!(res.body, "");
assert_eq!(res.mime, None);
}
#[test]
fn no_content_result()
{
let no_content = NoContent::default();
let res_def = no_content.to_response().expect("didn't expect error response");
let res_err = Result::<NoContent, MsgError>::Ok(no_content).to_response().expect("didn't expect error response");
assert_eq!(res_def, res_err);
let no_content : Result<NoContent, MsgError> = Ok(NoContent::default());
let res = no_content.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::NO_CONTENT);
assert_eq!(res.body, "");
assert_eq!(res.mime, None);
}
}