mirror of
https://gitlab.com/msrd0/gotham-restful.git
synced 2025-02-23 04:52:28 +00:00
expose async to handlers
This commit is contained in:
parent
d7282786b1
commit
427c836f52
5 changed files with 71 additions and 41 deletions
|
@ -115,6 +115,7 @@ pub use gotham_restful_derive::*;
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub mod export
|
pub mod export
|
||||||
{
|
{
|
||||||
|
pub use futures_util::future::FutureExt;
|
||||||
pub use gotham::{
|
pub use gotham::{
|
||||||
hyper::body::Bytes,
|
hyper::body::Bytes,
|
||||||
state::{FromState, State}
|
state::{FromState, State}
|
||||||
|
|
|
@ -5,7 +5,11 @@ use gotham::{
|
||||||
};
|
};
|
||||||
use hyper::Body;
|
use hyper::Body;
|
||||||
use serde::de::DeserializeOwned;
|
use serde::de::DeserializeOwned;
|
||||||
use std::panic::RefUnwindSafe;
|
use std::{
|
||||||
|
future::Future,
|
||||||
|
panic::RefUnwindSafe,
|
||||||
|
pin::Pin
|
||||||
|
};
|
||||||
|
|
||||||
/// This trait must be implemented by every RESTful Resource. It will
|
/// This trait must be implemented by every RESTful Resource. It will
|
||||||
/// allow you to register the different methods for this Resource.
|
/// allow you to register the different methods for this Resource.
|
||||||
|
@ -21,7 +25,7 @@ pub trait Resource
|
||||||
|
|
||||||
pub trait ResourceMethod
|
pub trait ResourceMethod
|
||||||
{
|
{
|
||||||
type Res : ResourceResult;
|
type Res : ResourceResult + Send + 'static;
|
||||||
|
|
||||||
#[cfg(feature = "openapi")]
|
#[cfg(feature = "openapi")]
|
||||||
fn operation_id() -> Option<String>
|
fn operation_id() -> Option<String>
|
||||||
|
@ -38,7 +42,7 @@ pub trait ResourceMethod
|
||||||
/// Handle a GET request on the Resource root.
|
/// Handle a GET request on the Resource root.
|
||||||
pub trait ResourceReadAll : ResourceMethod
|
pub trait ResourceReadAll : ResourceMethod
|
||||||
{
|
{
|
||||||
fn read_all(state : &mut State) -> Self::Res;
|
fn read_all(state : &mut State) -> Pin<Box<dyn Future<Output = Self::Res> + Send>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle a GET request on the Resource with an id.
|
/// Handle a GET request on the Resource with an id.
|
||||||
|
@ -46,7 +50,7 @@ pub trait ResourceRead : ResourceMethod
|
||||||
{
|
{
|
||||||
type ID : DeserializeOwned + Clone + RefUnwindSafe + Send + Sync + 'static;
|
type ID : DeserializeOwned + Clone + RefUnwindSafe + Send + Sync + 'static;
|
||||||
|
|
||||||
fn read(state : &mut State, id : Self::ID) -> Self::Res;
|
fn read(state : &mut State, id : Self::ID) -> Pin<Box<dyn Future<Output = Self::Res> + Send>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle a GET request on the Resource with additional search parameters.
|
/// Handle a GET request on the Resource with additional search parameters.
|
||||||
|
@ -54,7 +58,7 @@ pub trait ResourceSearch : ResourceMethod
|
||||||
{
|
{
|
||||||
type Query : ResourceType + QueryStringExtractor<Body> + Sync;
|
type Query : ResourceType + QueryStringExtractor<Body> + Sync;
|
||||||
|
|
||||||
fn search(state : &mut State, query : Self::Query) -> Self::Res;
|
fn search(state : &mut State, query : Self::Query) -> Pin<Box<dyn Future<Output = Self::Res> + Send>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle a POST request on the Resource root.
|
/// Handle a POST request on the Resource root.
|
||||||
|
@ -62,7 +66,7 @@ pub trait ResourceCreate : ResourceMethod
|
||||||
{
|
{
|
||||||
type Body : RequestBody;
|
type Body : RequestBody;
|
||||||
|
|
||||||
fn create(state : &mut State, body : Self::Body) -> Self::Res;
|
fn create(state : &mut State, body : Self::Body) -> Pin<Box<dyn Future<Output = Self::Res> + Send>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle a PUT request on the Resource root.
|
/// Handle a PUT request on the Resource root.
|
||||||
|
@ -70,7 +74,7 @@ pub trait ResourceUpdateAll : ResourceMethod
|
||||||
{
|
{
|
||||||
type Body : RequestBody;
|
type Body : RequestBody;
|
||||||
|
|
||||||
fn update_all(state : &mut State, body : Self::Body) -> Self::Res;
|
fn update_all(state : &mut State, body : Self::Body) -> Pin<Box<dyn Future<Output = Self::Res> + Send>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle a PUT request on the Resource with an id.
|
/// Handle a PUT request on the Resource with an id.
|
||||||
|
@ -79,13 +83,13 @@ pub trait ResourceUpdate : ResourceMethod
|
||||||
type Body : RequestBody;
|
type Body : RequestBody;
|
||||||
type ID : DeserializeOwned + Clone + RefUnwindSafe + Send + Sync + 'static;
|
type ID : DeserializeOwned + Clone + RefUnwindSafe + Send + Sync + 'static;
|
||||||
|
|
||||||
fn update(state : &mut State, id : Self::ID, body : Self::Body) -> Self::Res;
|
fn update(state : &mut State, id : Self::ID, body : Self::Body) -> Pin<Box<dyn Future<Output = Self::Res> + Send>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle a DELETE request on the Resource root.
|
/// Handle a DELETE request on the Resource root.
|
||||||
pub trait ResourceDeleteAll : ResourceMethod
|
pub trait ResourceDeleteAll : ResourceMethod
|
||||||
{
|
{
|
||||||
fn delete_all(state : &mut State) -> Self::Res;
|
fn delete_all(state : &mut State) -> Pin<Box<dyn Future<Output = Self::Res> + Send>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle a DELETE request on the Resource with an id.
|
/// Handle a DELETE request on the Resource with an id.
|
||||||
|
@ -93,5 +97,5 @@ pub trait ResourceDelete : ResourceMethod
|
||||||
{
|
{
|
||||||
type ID : DeserializeOwned + Clone + RefUnwindSafe + Send + Sync + 'static;
|
type ID : DeserializeOwned + Clone + RefUnwindSafe + Send + Sync + 'static;
|
||||||
|
|
||||||
fn delete(state : &mut State, id : Self::ID) -> Self::Res;
|
fn delete(state : &mut State, id : Self::ID) -> Pin<Box<dyn Future<Output = Self::Res> + Send>>;
|
||||||
}
|
}
|
||||||
|
|
|
@ -80,7 +80,7 @@ impl Response
|
||||||
|
|
||||||
|
|
||||||
/// A trait provided to convert a resource's result to json.
|
/// A trait provided to convert a resource's result to json.
|
||||||
pub trait ResourceResult : Send
|
pub trait ResourceResult
|
||||||
{
|
{
|
||||||
type Err : Error + Send + 'static;
|
type Err : Error + Send + 'static;
|
||||||
|
|
||||||
|
|
|
@ -9,7 +9,7 @@ use crate::OpenapiRouter;
|
||||||
|
|
||||||
use futures_util::{future, future::FutureExt};
|
use futures_util::{future, future::FutureExt};
|
||||||
use gotham::{
|
use gotham::{
|
||||||
handler::{HandlerError, HandlerFuture, IntoHandlerError, IntoHandlerFuture},
|
handler::{HandlerError, HandlerFuture, IntoHandlerError},
|
||||||
helpers::http::response::{create_empty_response, create_response},
|
helpers::http::response::{create_empty_response, create_response},
|
||||||
pipeline::chain::PipelineHandleChain,
|
pipeline::chain::PipelineHandleChain,
|
||||||
router::{
|
router::{
|
||||||
|
@ -32,6 +32,7 @@ use gotham::hyper::{
|
||||||
};
|
};
|
||||||
use mime::{Mime, APPLICATION_JSON};
|
use mime::{Mime, APPLICATION_JSON};
|
||||||
use std::{
|
use std::{
|
||||||
|
future::Future,
|
||||||
panic::RefUnwindSafe,
|
panic::RefUnwindSafe,
|
||||||
pin::Pin
|
pin::Pin
|
||||||
};
|
};
|
||||||
|
@ -105,27 +106,26 @@ fn response_from(res : Response, state : &State) -> hyper::Response<Body>
|
||||||
r
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
fn to_handler_future<F, R>(mut state : State, get_result : F) -> Pin<Box<HandlerFuture>>
|
async fn to_handler_future<F, R>(mut state : State, get_result : F) -> Result<(State, gotham::hyper::Response<Body>), (State, HandlerError)>
|
||||||
where
|
where
|
||||||
F : FnOnce(&mut State) -> R,
|
F : FnOnce(&mut State) -> Pin<Box<dyn Future<Output = R> + Send>>,
|
||||||
R : ResourceResult
|
R : ResourceResult
|
||||||
{
|
{
|
||||||
get_result(&mut state).into_response()
|
let res = get_result(&mut state).await;
|
||||||
.then(|res|
|
let res = res.into_response().await;
|
||||||
match res {
|
match res {
|
||||||
Ok(res) => {
|
Ok(res) => {
|
||||||
let r = response_from(res, &state);
|
let r = response_from(res, &state);
|
||||||
(state, r).into_handler_future()
|
Ok((state, r))
|
||||||
},
|
},
|
||||||
Err(e) => future::err((state, e.into_handler_error())).boxed()
|
Err(e) => Err((state, e.into_handler_error()))
|
||||||
}
|
}
|
||||||
).boxed()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn body_to_res<B, F, R>(mut state : State, get_result : F) -> (State, Result<gotham::hyper::Response<Body>, HandlerError>)
|
async fn body_to_res<B, F, R>(mut state : State, get_result : F) -> (State, Result<gotham::hyper::Response<Body>, HandlerError>)
|
||||||
where
|
where
|
||||||
B : RequestBody,
|
B : RequestBody,
|
||||||
F : FnOnce(&mut State, B) -> R,
|
F : FnOnce(&mut State, B) -> Pin<Box<dyn Future<Output = R> + Send>>,
|
||||||
R : ResourceResult
|
R : ResourceResult
|
||||||
{
|
{
|
||||||
let body = to_bytes(Body::take_from(&mut state)).await;
|
let body = to_bytes(Body::take_from(&mut state)).await;
|
||||||
|
@ -160,8 +160,11 @@ where
|
||||||
};
|
};
|
||||||
get_result(&mut state, body)
|
get_result(&mut state, body)
|
||||||
};
|
};
|
||||||
|
|
||||||
let res = match res.into_response().await {
|
let res = res.await;
|
||||||
|
let res = res.into_response().await;
|
||||||
|
|
||||||
|
let res = match res {
|
||||||
Ok(res) => {
|
Ok(res) => {
|
||||||
let r = response_from(res, &state);
|
let r = response_from(res, &state);
|
||||||
Ok(r)
|
Ok(r)
|
||||||
|
@ -174,8 +177,8 @@ where
|
||||||
fn handle_with_body<B, F, R>(state : State, get_result : F) -> Pin<Box<HandlerFuture>>
|
fn handle_with_body<B, F, R>(state : State, get_result : F) -> Pin<Box<HandlerFuture>>
|
||||||
where
|
where
|
||||||
B : RequestBody + 'static,
|
B : RequestBody + 'static,
|
||||||
F : FnOnce(&mut State, B) -> R + Send + 'static,
|
F : FnOnce(&mut State, B) -> Pin<Box<dyn Future<Output = R> + Send>> + Send + 'static,
|
||||||
R : ResourceResult + 'static
|
R : ResourceResult + Send + 'static
|
||||||
{
|
{
|
||||||
body_to_res(state, get_result)
|
body_to_res(state, get_result)
|
||||||
.then(|(state, res)| match res {
|
.then(|(state, res)| match res {
|
||||||
|
@ -187,7 +190,7 @@ where
|
||||||
|
|
||||||
fn read_all_handler<Handler : ResourceReadAll>(state : State) -> Pin<Box<HandlerFuture>>
|
fn read_all_handler<Handler : ResourceReadAll>(state : State) -> Pin<Box<HandlerFuture>>
|
||||||
{
|
{
|
||||||
to_handler_future(state, |state| Handler::read_all(state))
|
to_handler_future(state, |state| Handler::read_all(state)).boxed()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_handler<Handler : ResourceRead>(state : State) -> Pin<Box<HandlerFuture>>
|
fn read_handler<Handler : ResourceRead>(state : State) -> Pin<Box<HandlerFuture>>
|
||||||
|
@ -196,13 +199,13 @@ fn read_handler<Handler : ResourceRead>(state : State) -> Pin<Box<HandlerFuture>
|
||||||
let path : &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);
|
let path : &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);
|
||||||
path.id.clone()
|
path.id.clone()
|
||||||
};
|
};
|
||||||
to_handler_future(state, |state| Handler::read(state, id))
|
to_handler_future(state, |state| Handler::read(state, id)).boxed()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn search_handler<Handler : ResourceSearch>(mut state : State) -> Pin<Box<HandlerFuture>>
|
fn search_handler<Handler : ResourceSearch>(mut state : State) -> Pin<Box<HandlerFuture>>
|
||||||
{
|
{
|
||||||
let query = Handler::Query::take_from(&mut state);
|
let query = Handler::Query::take_from(&mut state);
|
||||||
to_handler_future(state, |state| Handler::search(state, query))
|
to_handler_future(state, |state| Handler::search(state, query)).boxed()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_handler<Handler : ResourceCreate>(state : State) -> Pin<Box<HandlerFuture>>
|
fn create_handler<Handler : ResourceCreate>(state : State) -> Pin<Box<HandlerFuture>>
|
||||||
|
@ -235,7 +238,7 @@ where
|
||||||
|
|
||||||
fn delete_all_handler<Handler : ResourceDeleteAll>(state : State) -> Pin<Box<HandlerFuture>>
|
fn delete_all_handler<Handler : ResourceDeleteAll>(state : State) -> Pin<Box<HandlerFuture>>
|
||||||
{
|
{
|
||||||
to_handler_future(state, |state| Handler::delete_all(state))
|
to_handler_future(state, |state| Handler::delete_all(state)).boxed()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn delete_handler<Handler : ResourceDelete>(state : State) -> Pin<Box<HandlerFuture>>
|
fn delete_handler<Handler : ResourceDelete>(state : State) -> Pin<Box<HandlerFuture>>
|
||||||
|
@ -244,7 +247,7 @@ fn delete_handler<Handler : ResourceDelete>(state : State) -> Pin<Box<HandlerFut
|
||||||
let path : &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);
|
let path : &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);
|
||||||
path.id.clone()
|
path.id.clone()
|
||||||
};
|
};
|
||||||
to_handler_future(state, |state| Handler::delete(state, id))
|
to_handler_future(state, |state| Handler::delete(state, id)).boxed()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
|
|
@ -302,6 +302,12 @@ fn expand(method : Method, attrs : TokenStream, item : TokenStream) -> Result<To
|
||||||
let fun = parse_macro_input::parse::<ItemFn>(item)?;
|
let fun = parse_macro_input::parse::<ItemFn>(item)?;
|
||||||
let fun_ident = &fun.sig.ident;
|
let fun_ident = &fun.sig.ident;
|
||||||
let fun_vis = &fun.vis;
|
let fun_vis = &fun.vis;
|
||||||
|
let fun_is_async = fun.sig.asyncness.is_some();
|
||||||
|
|
||||||
|
if let Some(unsafety) = fun.sig.unsafety
|
||||||
|
{
|
||||||
|
return Err(Error::new(unsafety.span(), "Resource methods must not be unsafe"));
|
||||||
|
}
|
||||||
|
|
||||||
let trait_ident = method.trait_ident();
|
let trait_ident = method.trait_ident();
|
||||||
let method_ident = method.fn_ident();
|
let method_ident = method.fn_ident();
|
||||||
|
@ -374,6 +380,11 @@ fn expand(method : Method, attrs : TokenStream, item : TokenStream) -> Result<To
|
||||||
|
|
||||||
// prepare the method block
|
// prepare the method block
|
||||||
let mut block = quote!(#fun_ident(#(#args_pass),*));
|
let mut block = quote!(#fun_ident(#(#args_pass),*));
|
||||||
|
let mut state_block = quote!();
|
||||||
|
if fun_is_async
|
||||||
|
{
|
||||||
|
block = quote!(#block.await);
|
||||||
|
}
|
||||||
if is_no_content
|
if is_no_content
|
||||||
{
|
{
|
||||||
block = quote!(#block; Default::default())
|
block = quote!(#block; Default::default())
|
||||||
|
@ -381,19 +392,22 @@ fn expand(method : Method, attrs : TokenStream, item : TokenStream) -> Result<To
|
||||||
if let Some(arg) = args.iter().filter(|arg| (*arg).ty.is_database_conn()).nth(0)
|
if let Some(arg) = args.iter().filter(|arg| (*arg).ty.is_database_conn()).nth(0)
|
||||||
{
|
{
|
||||||
let conn_ty = arg.ty.quote_ty();
|
let conn_ty = arg.ty.quote_ty();
|
||||||
block = quote! {
|
state_block = quote! {
|
||||||
|
#state_block
|
||||||
let #repo_ident = <#krate::export::Repo<#conn_ty>>::borrow_from(&#state_ident).clone();
|
let #repo_ident = <#krate::export::Repo<#conn_ty>>::borrow_from(&#state_ident).clone();
|
||||||
|
};
|
||||||
|
block = quote! {
|
||||||
#repo_ident.run::<_, #ret, ()>(move |#conn_ident| {
|
#repo_ident.run::<_, #ret, ()>(move |#conn_ident| {
|
||||||
Ok({#block})
|
Ok({#block})
|
||||||
}).wait().unwrap()
|
}).await.unwrap()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if let Some(arg) = args.iter().filter(|arg| (*arg).ty.is_auth_status()).nth(0)
|
if let Some(arg) = args.iter().filter(|arg| (*arg).ty.is_auth_status()).nth(0)
|
||||||
{
|
{
|
||||||
let auth_ty = arg.ty.quote_ty();
|
let auth_ty = arg.ty.quote_ty();
|
||||||
block = quote! {
|
state_block = quote! {
|
||||||
|
#state_block
|
||||||
let #auth_ident : #auth_ty = <#auth_ty>::borrow_from(#state_ident).clone();
|
let #auth_ident : #auth_ty = <#auth_ty>::borrow_from(#state_ident).clone();
|
||||||
#block
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -416,6 +430,10 @@ fn expand(method : Method, attrs : TokenStream, item : TokenStream) -> Result<To
|
||||||
#fun_vis mod #mod_ident
|
#fun_vis mod #mod_ident
|
||||||
{
|
{
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use std::{
|
||||||
|
future::Future,
|
||||||
|
pin::Pin
|
||||||
|
};
|
||||||
|
|
||||||
struct #handler_ident;
|
struct #handler_ident;
|
||||||
|
|
||||||
|
@ -432,12 +450,16 @@ fn expand(method : Method, attrs : TokenStream, item : TokenStream) -> Result<To
|
||||||
{
|
{
|
||||||
#(#generics)*
|
#(#generics)*
|
||||||
|
|
||||||
fn #method_ident(#(#args_def),*) -> #ret
|
fn #method_ident(#(#args_def),*) -> Pin<Box<dyn Future<Output = #ret> + Send>>
|
||||||
{
|
{
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
use #krate::export::FromState;
|
use #krate::export::{FromState, FutureExt};
|
||||||
|
|
||||||
#block
|
#state_block
|
||||||
|
|
||||||
|
async move {
|
||||||
|
#block
|
||||||
|
}.boxed()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue