1
0
Fork 0
mirror of https://gitlab.com/msrd0/gotham-restful.git synced 2025-04-19 22:44:38 +00:00

delegate request body parsing to trait

This commit is contained in:
Dominic 2019-10-20 01:59:28 +02:00
parent 57e4f36852
commit f737ac4332
Signed by: msrd0
GPG key ID: DCC8C247452E98F9
3 changed files with 40 additions and 5 deletions

View file

@ -76,7 +76,10 @@ extern crate self as gotham_restful;
#[macro_use] extern crate gotham_derive;
#[macro_use] extern crate serde;
pub use hyper::StatusCode;
#[doc(no_inline)]
pub use hyper::{Chunk, StatusCode};
#[doc(no_inline)]
pub use mime::Mime;
pub use gotham_restful_derive::*;

View file

@ -27,6 +27,7 @@ use gotham::{
use hyper::{
header::CONTENT_TYPE,
Body,
HeaderMap,
Method
};
use mime::{Mime, APPLICATION_JSON};
@ -144,7 +145,7 @@ where
fn handle_with_body<Body, F, R>(mut state : State, get_result : F) -> Box<HandlerFuture>
where
Body : DeserializeOwned,
Body : RequestBody,
F : FnOnce(&mut State, Body) -> R + Send + 'static,
R : ResourceResult
{
@ -157,7 +158,15 @@ where
Err(e) => return err((state, e.into_handler_error()))
};
let body = match serde_json::from_slice(&body) {
let content_type : Mime = match HeaderMap::borrow_from(&state).get(CONTENT_TYPE) {
Some(content_type) => content_type.to_str().unwrap().parse().unwrap(),
None => {
let res = create_empty_response(&state, StatusCode::UNSUPPORTED_MEDIA_TYPE);
return ok((state, res))
}
};
let body = match Body::from_body(body, content_type) {
Ok(body) => body,
Err(e) => return {
let error : ResourceError = e.into();

View file

@ -1,6 +1,8 @@
#[cfg(feature = "openapi")]
use crate::OpenapiType;
use crate::{OpenapiType, result::ResourceError};
use hyper::Chunk;
use mime::{Mime, APPLICATION_JSON};
use serde::{de::DeserializeOwned, Serialize};
#[cfg(not(feature = "openapi"))]
@ -39,10 +41,31 @@ impl<T : ResourceType + Serialize> ResponseBody for T
/// A type that can be used inside a request body. Implemented for every type that is
/// deserializable with serde. If the `openapi` feature is used, it must also be of type
/// `OpenapiType`.
pub trait RequestBody : ResourceType + DeserializeOwned
pub trait RequestBody : ResourceType + Sized
{
type Err : Into<ResourceError>;
/// Return all types that are supported as content types
fn supported_types() -> Option<Vec<Mime>>
{
None
}
/// Create the request body from a raw body and the content type.
fn from_body(body : Chunk, content_type : Mime) -> Result<Self, Self::Err>;
}
impl<T : ResourceType + DeserializeOwned> RequestBody for T
{
type Err = serde_json::Error;
fn supported_types() -> Option<Vec<Mime>>
{
Some(vec![APPLICATION_JSON])
}
fn from_body(body : Chunk, _content_type : Mime) -> Result<Self, Self::Err>
{
serde_json::from_slice(&body)
}
}