1
0
Fork 0
mirror of https://gitlab.com/msrd0/gotham-restful.git synced 2025-02-23 04:52:28 +00:00

update to gotham 0.5 and start using rustfmt

This commit is contained in:
Dominic 2020-09-15 15:10:41 +02:00
parent 5317e50961
commit d55b0897e9
Signed by: msrd0
GPG key ID: DCC8C247452E98F9
39 changed files with 1798 additions and 2095 deletions

View file

@ -20,12 +20,12 @@ gitlab = { repository = "msrd0/gotham-restful", branch = "master" }
[dependencies]
base64 = { version = "0.12.1", optional = true }
chrono = { version = "0.4.11", features = ["serde"], optional = true }
cookie = { version = "0.13.3", optional = true }
cookie = { version = "0.14", optional = true }
futures-core = "0.3.5"
futures-util = "0.3.5"
gotham = { version = "0.5.0-rc.1", default-features = false }
gotham_derive = "0.5.0-rc.1"
gotham_middleware_diesel = { version = "0.1.2", optional = true }
gotham = { version = "0.5.0", default-features = false }
gotham_derive = "0.5.0"
gotham_middleware_diesel = { version = "0.2.0", optional = true }
gotham_restful_derive = { version = "0.1.0-rc0" }
indexmap = { version = "1.3.2", optional = true }
itertools = "0.9.0"
@ -40,7 +40,7 @@ uuid = { version = "0.8.1", optional = true }
[dev-dependencies]
diesel = { version = "1.4.4", features = ["postgres"] }
futures-executor = "0.3.5"
paste = "0.1.12"
paste = "1.0"
thiserror = "1.0.18"
trybuild = "1.0.27"
@ -56,5 +56,6 @@ openapi = ["gotham_restful_derive/openapi", "indexmap", "openapiv3"]
all-features = true
[patch.crates-io]
gotham = { path = "../gotham/gotham" }
gotham_restful = { path = "." }
gotham_restful_derive = { path = "./derive" }

View file

@ -1,26 +1,14 @@
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::cmp::min;
use syn::{
spanned::Spanned,
Data,
DeriveInput,
Error,
Field,
Fields,
Ident,
Result,
Type
};
use syn::{spanned::Spanned, Data, DeriveInput, Error, Field, Fields, Ident, Result, Type};
struct ParsedFields
{
struct ParsedFields {
fields: Vec<(Ident, Type)>,
named: bool
}
impl ParsedFields
{
impl ParsedFields {
fn from_named<I>(fields: I) -> Self
where
I: Iterator<Item = Field>
@ -33,18 +21,22 @@ impl ParsedFields
where
I: Iterator<Item = Field>
{
let fields = fields.enumerate().map(|(i, field)| (format_ident!("arg{}", i), field.ty)).collect();
let fields = fields
.enumerate()
.map(|(i, field)| (format_ident!("arg{}", i), field.ty))
.collect();
Self { fields, named: false }
}
fn from_unit() -> Self
{
Self { fields: Vec::new(), named: false }
fn from_unit() -> Self {
Self {
fields: Vec::new(),
named: false
}
}
}
pub fn expand_from_body(input : DeriveInput) -> Result<TokenStream>
{
pub fn expand_from_body(input: DeriveInput) -> Result<TokenStream> {
let krate = super::krate();
let ident = input.ident;
let generics = input.generics;
@ -53,7 +45,8 @@ pub fn expand_from_body(input : DeriveInput) -> Result<TokenStream>
Data::Enum(inum) => Err(inum.enum_token.span()),
Data::Struct(strukt) => Ok(strukt),
Data::Union(uni) => Err(uni.union_token.span())
}.map_err(|span| Error::new(span, "#[derive(FromBody)] only works for structs"))?;
}
.map_err(|span| Error::new(span, "#[derive(FromBody)] only works for structs"))?;
let fields = match strukt.fields {
Fields::Named(named) => ParsedFields::from_named(named.named.into_iter()),
@ -66,8 +59,7 @@ pub fn expand_from_body(input : DeriveInput) -> Result<TokenStream>
let mut body_ident = format_ident!("_body");
let mut type_ident = format_ident!("_type");
if let Some(body_field) = fields.fields.get(0)
{
if let Some(body_field) = fields.fields.get(0) {
body_ident = body_field.0.clone();
let body_ty = &body_field.1;
where_clause = quote! {
@ -81,8 +73,7 @@ pub fn expand_from_body(input : DeriveInput) -> Result<TokenStream>
};
}
if let Some(type_field) = fields.fields.get(1)
{
if let Some(type_field) = fields.fields.get(1) {
type_ident = type_field.0.clone();
let type_ty = &type_field.1;
where_clause = quote! {
@ -95,8 +86,7 @@ pub fn expand_from_body(input : DeriveInput) -> Result<TokenStream>
};
}
for field in &fields.fields[min(2, fields.fields.len())..]
{
for field in &fields.fields[min(2, fields.fields.len())..] {
let field_ident = &field.0;
let field_ty = &field.1;
where_clause = quote! {

View file

@ -21,8 +21,7 @@ mod openapi_type;
use openapi_type::expand_openapi_type;
#[inline]
fn print_tokens(tokens : TokenStream2) -> TokenStream
{
fn print_tokens(tokens: TokenStream2) -> TokenStream {
//eprintln!("{}", tokens);
tokens.into()
}
@ -32,8 +31,7 @@ fn expand_derive<F>(input : TokenStream, expand : F) -> TokenStream
where
F: FnOnce(DeriveInput) -> Result<TokenStream2>
{
print_tokens(expand(parse_macro_input!(input))
.unwrap_or_else(|err| err.to_compile_error()))
print_tokens(expand(parse_macro_input!(input)).unwrap_or_else(|err| err.to_compile_error()))
}
#[inline]
@ -43,92 +41,76 @@ where
A: ParseMacroInput,
I: ParseMacroInput
{
print_tokens(expand(parse_macro_input!(attrs), parse_macro_input!(item))
.unwrap_or_else(|err| err.to_compile_error()))
print_tokens(expand(parse_macro_input!(attrs), parse_macro_input!(item)).unwrap_or_else(|err| err.to_compile_error()))
}
#[inline]
fn krate() -> TokenStream2
{
fn krate() -> TokenStream2 {
quote!(::gotham_restful)
}
#[proc_macro_derive(FromBody)]
pub fn derive_from_body(input : TokenStream) -> TokenStream
{
pub fn derive_from_body(input: TokenStream) -> TokenStream {
expand_derive(input, expand_from_body)
}
#[cfg(feature = "openapi")]
#[proc_macro_derive(OpenapiType, attributes(openapi))]
pub fn derive_openapi_type(input : TokenStream) -> TokenStream
{
pub fn derive_openapi_type(input: TokenStream) -> TokenStream {
expand_derive(input, expand_openapi_type)
}
#[proc_macro_derive(RequestBody, attributes(supported_types))]
pub fn derive_request_body(input : TokenStream) -> TokenStream
{
pub fn derive_request_body(input: TokenStream) -> TokenStream {
expand_derive(input, expand_request_body)
}
#[proc_macro_derive(Resource, attributes(resource))]
pub fn derive_resource(input : TokenStream) -> TokenStream
{
pub fn derive_resource(input: TokenStream) -> TokenStream {
expand_derive(input, expand_resource)
}
#[proc_macro_derive(ResourceError, attributes(display, from, status))]
pub fn derive_resource_error(input : TokenStream) -> TokenStream
{
pub fn derive_resource_error(input: TokenStream) -> TokenStream {
expand_derive(input, expand_resource_error)
}
#[proc_macro_attribute]
pub fn read_all(attr : TokenStream, item : TokenStream) -> TokenStream
{
pub fn read_all(attr: TokenStream, item: TokenStream) -> TokenStream {
expand_macro(attr, item, |attr, item| expand_method(Method::ReadAll, attr, item))
}
#[proc_macro_attribute]
pub fn read(attr : TokenStream, item : TokenStream) -> TokenStream
{
pub fn read(attr: TokenStream, item: TokenStream) -> TokenStream {
expand_macro(attr, item, |attr, item| expand_method(Method::Read, attr, item))
}
#[proc_macro_attribute]
pub fn search(attr : TokenStream, item : TokenStream) -> TokenStream
{
pub fn search(attr: TokenStream, item: TokenStream) -> TokenStream {
expand_macro(attr, item, |attr, item| expand_method(Method::Search, attr, item))
}
#[proc_macro_attribute]
pub fn create(attr : TokenStream, item : TokenStream) -> TokenStream
{
pub fn create(attr: TokenStream, item: TokenStream) -> TokenStream {
expand_macro(attr, item, |attr, item| expand_method(Method::Create, attr, item))
}
#[proc_macro_attribute]
pub fn change_all(attr : TokenStream, item : TokenStream) -> TokenStream
{
pub fn change_all(attr: TokenStream, item: TokenStream) -> TokenStream {
expand_macro(attr, item, |attr, item| expand_method(Method::ChangeAll, attr, item))
}
#[proc_macro_attribute]
pub fn change(attr : TokenStream, item : TokenStream) -> TokenStream
{
pub fn change(attr: TokenStream, item: TokenStream) -> TokenStream {
expand_macro(attr, item, |attr, item| expand_method(Method::Change, attr, item))
}
#[proc_macro_attribute]
pub fn remove_all(attr : TokenStream, item : TokenStream) -> TokenStream
{
pub fn remove_all(attr: TokenStream, item: TokenStream) -> TokenStream {
expand_macro(attr, item, |attr, item| expand_method(Method::RemoveAll, attr, item))
}
#[proc_macro_attribute]
pub fn remove(attr : TokenStream, item : TokenStream) -> TokenStream
{
pub fn remove(attr: TokenStream, item: TokenStream) -> TokenStream {
expand_macro(attr, item, |attr, item| expand_method(Method::Remove, attr, item))
}

View file

@ -2,26 +2,13 @@ use crate::util::CollectToResult;
use heck::{CamelCase, SnakeCase};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote};
use syn::{
spanned::Spanned,
Attribute,
AttributeArgs,
Error,
FnArg,
ItemFn,
Lit,
LitBool,
Meta,
NestedMeta,
PatType,
Result,
ReturnType,
Type
};
use std::str::FromStr;
use syn::{
spanned::Spanned, Attribute, AttributeArgs, Error, FnArg, ItemFn, Lit, LitBool, Meta, NestedMeta, PatType, Result,
ReturnType, Type
};
pub enum Method
{
pub enum Method {
ReadAll,
Read,
Search,
@ -32,12 +19,10 @@ pub enum Method
Remove
}
impl FromStr for Method
{
impl FromStr for Method {
type Err = Error;
fn from_str(str : &str) -> Result<Self>
{
fn from_str(str: &str) -> Result<Self> {
match str {
"ReadAll" | "read_all" => Ok(Self::ReadAll),
"Read" | "read" => Ok(Self::Read),
@ -52,10 +37,8 @@ impl FromStr for Method
}
}
impl Method
{
pub fn type_names(&self) -> Vec<&'static str>
{
impl Method {
pub fn type_names(&self) -> Vec<&'static str> {
use Method::*;
match self {
@ -67,8 +50,7 @@ impl Method
}
}
pub fn trait_ident(&self) -> Ident
{
pub fn trait_ident(&self) -> Ident {
use Method::*;
let name = match self {
@ -84,8 +66,7 @@ impl Method
format_ident!("Resource{}", name)
}
pub fn fn_ident(&self) -> Ident
{
pub fn fn_ident(&self) -> Ident {
use Method::*;
let name = match self {
@ -101,25 +82,25 @@ impl Method
format_ident!("{}", name)
}
pub fn mod_ident(&self, resource : &str) -> Ident
{
format_ident!("_gotham_restful_resource_{}_method_{}", resource.to_snake_case(), self.fn_ident())
pub fn mod_ident(&self, resource: &str) -> Ident {
format_ident!(
"_gotham_restful_resource_{}_method_{}",
resource.to_snake_case(),
self.fn_ident()
)
}
pub fn handler_struct_ident(&self, resource : &str) -> Ident
{
pub fn handler_struct_ident(&self, resource: &str) -> Ident {
format_ident!("{}{}Handler", resource.to_camel_case(), self.trait_ident())
}
pub fn setup_ident(&self, resource : &str) -> Ident
{
pub fn setup_ident(&self, resource: &str) -> Ident {
format_ident!("{}_{}_setup_impl", resource.to_snake_case(), self.fn_ident())
}
}
#[allow(clippy::large_enum_variant)]
enum MethodArgumentType
{
enum MethodArgumentType {
StateRef,
StateMutRef,
MethodArg(Type),
@ -128,81 +109,77 @@ enum MethodArgumentType
AuthStatusRef(Type)
}
impl MethodArgumentType
{
fn is_state_ref(&self) -> bool
{
impl MethodArgumentType {
fn is_state_ref(&self) -> bool {
matches!(self, Self::StateRef | Self::StateMutRef)
}
fn is_method_arg(&self) -> bool
{
fn is_method_arg(&self) -> bool {
matches!(self, Self::MethodArg(_))
}
fn is_database_conn(&self) -> bool
{
fn is_database_conn(&self) -> bool {
matches!(self, Self::DatabaseConnection(_))
}
fn is_auth_status(&self) -> bool
{
fn is_auth_status(&self) -> bool {
matches!(self, Self::AuthStatus(_) | Self::AuthStatusRef(_))
}
fn ty(&self) -> Option<&Type>
{
fn ty(&self) -> Option<&Type> {
match self {
Self::MethodArg(ty) | Self::DatabaseConnection(ty) | Self::AuthStatus(ty) | Self::AuthStatusRef(ty) => Some(ty),
_ => None
}
}
fn quote_ty(&self) -> Option<TokenStream>
{
fn quote_ty(&self) -> Option<TokenStream> {
self.ty().map(|ty| quote!(#ty))
}
}
struct MethodArgument
{
struct MethodArgument {
ident: Ident,
ident_span: Span,
ty: MethodArgumentType
}
impl Spanned for MethodArgument
{
fn span(&self) -> Span
{
impl Spanned for MethodArgument {
fn span(&self) -> Span {
self.ident_span
}
}
fn interpret_arg_ty(attrs : &[Attribute], name : &str, ty : Type) -> Result<MethodArgumentType>
{
let attr = attrs.iter()
fn interpret_arg_ty(attrs: &[Attribute], name: &str, ty: Type) -> Result<MethodArgumentType> {
let attr = attrs
.iter()
.find(|arg| arg.path.segments.iter().any(|path| &path.ident.to_string() == "rest_arg"))
.map(|arg| arg.tokens.to_string());
// TODO issue a warning for _state usage once diagnostics become stable
if attr.as_deref() == Some("state") || (attr.is_none() && (name == "state" || name == "_state"))
{
if attr.as_deref() == Some("state") || (attr.is_none() && (name == "state" || name == "_state")) {
return match ty {
Type::Reference(ty) => Ok(if ty.mutability.is_none() { MethodArgumentType::StateRef } else { MethodArgumentType::StateMutRef }),
_ => Err(Error::new(ty.span(), "The state parameter has to be a (mutable) reference to gotham_restful::State"))
Type::Reference(ty) => Ok(if ty.mutability.is_none() {
MethodArgumentType::StateRef
} else {
MethodArgumentType::StateMutRef
}),
_ => Err(Error::new(
ty.span(),
"The state parameter has to be a (mutable) reference to gotham_restful::State"
))
};
}
if cfg!(feature = "auth") && (attr.as_deref() == Some("auth") || (attr.is_none() && name == "auth"))
{
if cfg!(feature = "auth") && (attr.as_deref() == Some("auth") || (attr.is_none() && name == "auth")) {
return Ok(match ty {
Type::Reference(ty) => MethodArgumentType::AuthStatusRef(*ty.elem),
ty => MethodArgumentType::AuthStatus(ty)
});
}
if cfg!(feature = "database") && (attr.as_deref() == Some("connection") || attr.as_deref() == Some("conn") || (attr.is_none() && name == "conn"))
if cfg!(feature = "database")
&& (attr.as_deref() == Some("connection") || attr.as_deref() == Some("conn") || (attr.is_none() && name == "conn"))
{
return Ok(MethodArgumentType::DatabaseConnection(match ty {
Type::Reference(ty) => *ty.elem,
@ -213,26 +190,25 @@ fn interpret_arg_ty(attrs : &[Attribute], name : &str, ty : Type) -> Result<Meth
Ok(MethodArgumentType::MethodArg(ty))
}
fn interpret_arg(index : usize, arg : &PatType) -> Result<MethodArgument>
{
fn interpret_arg(index: usize, arg: &PatType) -> Result<MethodArgument> {
let pat = &arg.pat;
let ident = format_ident!("arg{}", index);
let orig_name = quote!(#pat);
let ty = interpret_arg_ty(&arg.attrs, &orig_name.to_string(), *arg.ty.clone())?;
Ok(MethodArgument { ident, ident_span: arg.pat.span(), ty })
Ok(MethodArgument {
ident,
ident_span: arg.pat.span(),
ty
})
}
#[cfg(feature = "openapi")]
fn expand_operation_id(attrs : &[NestedMeta]) -> TokenStream
{
fn expand_operation_id(attrs: &[NestedMeta]) -> TokenStream {
let mut operation_id: Option<&Lit> = None;
for meta in attrs
{
if let NestedMeta::Meta(Meta::NameValue(kv)) = meta
{
if kv.path.segments.last().map(|p| p.ident.to_string()) == Some("operation_id".to_owned())
{
for meta in attrs {
if let NestedMeta::Meta(Meta::NameValue(kv)) = meta {
if kv.path.segments.last().map(|p| p.ident.to_string()) == Some("operation_id".to_owned()) {
operation_id = Some(&kv.lit)
}
}
@ -250,21 +226,19 @@ fn expand_operation_id(attrs : &[NestedMeta]) -> TokenStream
}
#[cfg(not(feature = "openapi"))]
fn expand_operation_id(_ : &[NestedMeta]) -> TokenStream
{
fn expand_operation_id(_: &[NestedMeta]) -> TokenStream {
quote!()
}
fn expand_wants_auth(attrs : &[NestedMeta], default : bool) -> TokenStream
{
let default_lit = Lit::Bool(LitBool { value: default, span: Span::call_site() });
fn expand_wants_auth(attrs: &[NestedMeta], default: bool) -> TokenStream {
let default_lit = Lit::Bool(LitBool {
value: default,
span: Span::call_site()
});
let mut wants_auth = &default_lit;
for meta in attrs
{
if let NestedMeta::Meta(Meta::NameValue(kv)) = meta
{
if kv.path.segments.last().map(|p| p.ident.to_string()) == Some("wants_auth".to_owned())
{
for meta in attrs {
if let NestedMeta::Meta(Meta::NameValue(kv)) = meta {
if kv.path.segments.last().map(|p| p.ident.to_string()) == Some("wants_auth".to_owned()) {
wants_auth = &kv.lit
}
}
@ -279,28 +253,36 @@ fn expand_wants_auth(attrs : &[NestedMeta], default : bool) -> TokenStream
}
#[allow(clippy::comparison_chain)]
pub fn expand_method(method : Method, mut attrs : AttributeArgs, fun : ItemFn) -> Result<TokenStream>
{
pub fn expand_method(method: Method, mut attrs: AttributeArgs, fun: ItemFn) -> Result<TokenStream> {
let krate = super::krate();
// parse attributes
if attrs.len() < 1
{
return Err(Error::new(Span::call_site(), "Missing Resource struct. Example: #[read_all(MyResource)]"));
if attrs.len() < 1 {
return Err(Error::new(
Span::call_site(),
"Missing Resource struct. Example: #[read_all(MyResource)]"
));
}
let resource_path = match attrs.remove(0) {
NestedMeta::Meta(Meta::Path(path)) => path,
p => return Err(Error::new(p.span(), "Expected name of the Resource struct this method belongs to"))
p => {
return Err(Error::new(
p.span(),
"Expected name of the Resource struct this method belongs to"
))
},
};
let resource_name = resource_path.segments.last().map(|s| s.ident.to_string())
let resource_name = resource_path
.segments
.last()
.map(|s| s.ident.to_string())
.ok_or_else(|| Error::new(resource_path.span(), "Resource name must not be empty"))?;
let fun_ident = &fun.sig.ident;
let fun_vis = &fun.vis;
let fun_is_async = fun.sig.asyncness.is_some();
if let Some(unsafety) = fun.sig.unsafety
{
if let Some(unsafety) = fun.sig.unsafety {
return Err(Error::new(unsafety.span(), "Resource methods must not be unsafe"));
}
@ -323,7 +305,10 @@ pub fn expand_method(method : Method, mut attrs : AttributeArgs, fun : ItemFn) -
let res_ident = format_ident!("res");
// extract arguments into pattern, ident and type
let args = fun.sig.inputs.iter()
let args = fun
.sig
.inputs
.iter()
.enumerate()
.map(|(i, arg)| match arg {
FnArg::Typed(arg) => interpret_arg(i, arg),
@ -334,18 +319,14 @@ pub fn expand_method(method : Method, mut attrs : AttributeArgs, fun : ItemFn) -
// extract the generic parameters to use
let ty_names = method.type_names();
let ty_len = ty_names.len();
let generics_args : Vec<&MethodArgument> = args.iter()
.filter(|arg| (*arg).ty.is_method_arg())
.collect();
if generics_args.len() > ty_len
{
let generics_args: Vec<&MethodArgument> = args.iter().filter(|arg| (*arg).ty.is_method_arg()).collect();
if generics_args.len() > ty_len {
return Err(Error::new(generics_args[ty_len].span(), "Too many arguments"));
}
else if generics_args.len() < ty_len
{
} else if generics_args.len() < ty_len {
return Err(Error::new(fun_ident.span(), "Too few arguments"));
}
let generics : Vec<TokenStream> = generics_args.iter()
let generics: Vec<TokenStream> = generics_args
.iter()
.map(|arg| arg.ty.quote_ty().unwrap())
.zip(ty_names)
.map(|(arg, name)| {
@ -355,45 +336,51 @@ pub fn expand_method(method : Method, mut attrs : AttributeArgs, fun : ItemFn) -
.collect();
// extract the definition of our method
let mut args_def : Vec<TokenStream> = args.iter()
let mut args_def: Vec<TokenStream> = args
.iter()
.filter(|arg| (*arg).ty.is_method_arg())
.map(|arg| {
let ident = &arg.ident;
let ty = arg.ty.quote_ty();
quote!(#ident : #ty)
}).collect();
})
.collect();
args_def.insert(0, quote!(mut #state_ident : #krate::State));
// extract the arguments to pass over to the supplied method
let args_pass : Vec<TokenStream> = args.iter().map(|arg| match (&arg.ty, &arg.ident) {
let args_pass: Vec<TokenStream> = args
.iter()
.map(|arg| match (&arg.ty, &arg.ident) {
(MethodArgumentType::StateRef, _) => quote!(&#state_ident),
(MethodArgumentType::StateMutRef, _) => quote!(&mut #state_ident),
(MethodArgumentType::MethodArg(_), ident) => quote!(#ident),
(MethodArgumentType::DatabaseConnection(_), _) => quote!(&#conn_ident),
(MethodArgumentType::AuthStatus(_), _) => quote!(#auth_ident),
(MethodArgumentType::AuthStatusRef(_), _) => quote!(&#auth_ident)
}).collect();
})
.collect();
// prepare the method block
let mut block = quote!(#fun_ident(#(#args_pass),*));
let mut state_block = quote!();
if fun_is_async
{
if let Some(arg) = args.iter().find(|arg| (*arg).ty.is_state_ref())
{
return Err(Error::new(arg.span(), "async fn must not take &State as an argument as State is not Sync, consider boxing"));
if fun_is_async {
if let Some(arg) = args.iter().find(|arg| (*arg).ty.is_state_ref()) {
return Err(Error::new(
arg.span(),
"async fn must not take &State as an argument as State is not Sync, consider boxing"
));
}
block = quote!(#block.await);
}
if is_no_content
{
if is_no_content {
block = quote!(#block; Default::default())
}
if let Some(arg) = args.iter().find(|arg| (*arg).ty.is_database_conn())
{
if fun_is_async
{
return Err(Error::new(arg.span(), "async fn is not supported when database support is required, consider boxing"));
if let Some(arg) = args.iter().find(|arg| (*arg).ty.is_database_conn()) {
if fun_is_async {
return Err(Error::new(
arg.span(),
"async fn is not supported when database support is required, consider boxing"
));
}
let conn_ty = arg.ty.quote_ty();
state_block = quote! {
@ -411,8 +398,7 @@ pub fn expand_method(method : Method, mut attrs : AttributeArgs, fun : ItemFn) -
}
};
}
if let Some(arg) = args.iter().find(|arg| (*arg).ty.is_auth_status())
{
if let Some(arg) = args.iter().find(|arg| (*arg).ty.is_auth_status()) {
let auth_ty = arg.ty.quote_ty();
state_block = quote! {
#state_block
@ -422,8 +408,7 @@ pub fn expand_method(method : Method, mut attrs : AttributeArgs, fun : ItemFn) -
// prepare the where clause
let mut where_clause = quote!(#resource_path : #krate::Resource,);
for arg in args.iter().filter(|arg| (*arg).ty.is_auth_status())
{
for arg in args.iter().filter(|arg| (*arg).ty.is_auth_status()) {
let auth_ty = arg.ty.quote_ty();
where_clause = quote!(#where_clause #auth_ty : Clone,);
}

View file

@ -1,46 +1,31 @@
use crate::util::{CollectToResult, remove_parens};
use crate::util::{remove_parens, CollectToResult};
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{
parse_macro_input,
spanned::Spanned,
Attribute,
AttributeArgs,
Data,
DataEnum,
DataStruct,
DeriveInput,
Error,
Field,
Fields,
Generics,
GenericParam,
Lit,
LitStr,
Meta,
NestedMeta,
Result,
Variant
parse_macro_input, spanned::Spanned, Attribute, AttributeArgs, Data, DataEnum, DataStruct, DeriveInput, Error, Field,
Fields, GenericParam, Generics, Lit, LitStr, Meta, NestedMeta, Result, Variant
};
pub fn expand_openapi_type(input : DeriveInput) -> Result<TokenStream>
{
pub fn expand_openapi_type(input: DeriveInput) -> Result<TokenStream> {
match (input.ident, input.generics, input.attrs, input.data) {
(ident, generics, attrs, Data::Enum(inum)) => expand_enum(ident, generics, attrs, inum),
(ident, generics, attrs, Data::Struct(strukt)) => expand_struct(ident, generics, attrs, strukt),
(_, _, _, Data::Union(uni)) => Err(Error::new(uni.union_token.span(), "#[derive(OpenapiType)] only works for structs and enums"))
(_, _, _, Data::Union(uni)) => Err(Error::new(
uni.union_token.span(),
"#[derive(OpenapiType)] only works for structs and enums"
))
}
}
fn expand_where(generics : &Generics) -> TokenStream
{
if generics.params.is_empty()
{
fn expand_where(generics: &Generics) -> TokenStream {
if generics.params.is_empty() {
return quote!();
}
let krate = super::krate();
let idents = generics.params.iter()
let idents = generics
.params
.iter()
.map(|param| match param {
GenericParam::Type(ty) => Some(ty.ident.clone()),
_ => None
@ -54,46 +39,39 @@ fn expand_where(generics : &Generics) -> TokenStream
}
#[derive(Debug, Default)]
struct Attrs
{
struct Attrs {
nullable: bool,
rename: Option<String>
}
fn to_string(lit : &Lit) -> Result<String>
{
fn to_string(lit: &Lit) -> Result<String> {
match lit {
Lit::Str(str) => Ok(str.value()),
_ => Err(Error::new(lit.span(), "Expected string literal"))
}
}
fn to_bool(lit : &Lit) -> Result<bool>
{
fn to_bool(lit: &Lit) -> Result<bool> {
match lit {
Lit::Bool(bool) => Ok(bool.value),
_ => Err(Error::new(lit.span(), "Expected bool"))
}
}
fn parse_attributes(input : &[Attribute]) -> Result<Attrs>
{
fn parse_attributes(input: &[Attribute]) -> Result<Attrs> {
let mut parsed = Attrs::default();
for attr in input
{
if attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("openapi".to_owned())
{
for attr in input {
if attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("openapi".to_owned()) {
let tokens = remove_parens(attr.tokens.clone());
// TODO this is not public api but syn currently doesn't offer another convenient way to parse AttributeArgs
let nested = parse_macro_input::parse::<AttributeArgs>(tokens.into())?;
for meta in nested
{
for meta in nested {
match &meta {
NestedMeta::Meta(Meta::NameValue(kv)) => match kv.path.segments.last().map(|s| s.ident.to_string()) {
Some(key) => match key.as_ref() {
"nullable" => parsed.nullable = to_bool(&kv.lit)?,
"rename" => parsed.rename = Some(to_string(&kv.lit)?),
_ => return Err(Error::new(kv.path.span(), "Unknown key")),
_ => return Err(Error::new(kv.path.span(), "Unknown key"))
},
_ => return Err(Error::new(meta.span(), "Unexpected token"))
},
@ -105,11 +83,12 @@ fn parse_attributes(input : &[Attribute]) -> Result<Attrs>
Ok(parsed)
}
fn expand_variant(variant : &Variant) -> Result<TokenStream>
{
if variant.fields != Fields::Unit
{
return Err(Error::new(variant.span(), "#[derive(OpenapiType)] does not support enum variants with fields"));
fn expand_variant(variant: &Variant) -> Result<TokenStream> {
if variant.fields != Fields::Unit {
return Err(Error::new(
variant.span(),
"#[derive(OpenapiType)] does not support enum variants with fields"
));
}
let ident = &variant.ident;
@ -125,8 +104,7 @@ fn expand_variant(variant : &Variant) -> Result<TokenStream>
})
}
fn expand_enum(ident : Ident, generics : Generics, attrs : Vec<Attribute>, input : DataEnum) -> Result<TokenStream>
{
fn expand_enum(ident: Ident, generics: Generics, attrs: Vec<Attribute>, input: DataEnum) -> Result<TokenStream> {
let krate = super::krate();
let where_clause = expand_where(&generics);
@ -137,9 +115,7 @@ fn expand_enum(ident : Ident, generics : Generics, attrs : Vec<Attribute>, input
None => ident.to_string()
};
let variants = input.variants.iter()
.map(expand_variant)
.collect_to_result()?;
let variants = input.variants.iter().map(expand_variant).collect_to_result()?;
Ok(quote! {
impl #generics #krate::OpenapiType for #ident #generics
@ -170,11 +146,15 @@ fn expand_enum(ident : Ident, generics : Generics, attrs : Vec<Attribute>, input
})
}
fn expand_field(field : &Field) -> Result<TokenStream>
{
fn expand_field(field: &Field) -> Result<TokenStream> {
let ident = match &field.ident {
Some(ident) => ident,
None => return Err(Error::new(field.span(), "#[derive(OpenapiType)] does not support fields without an ident"))
None => {
return Err(Error::new(
field.span(),
"#[derive(OpenapiType)] does not support fields without an ident"
))
},
};
let ident_str = LitStr::new(&ident.to_string(), ident.span());
let ty = &field.ty;
@ -226,8 +206,7 @@ fn expand_field(field : &Field) -> Result<TokenStream>
}})
}
fn expand_struct(ident : Ident, generics : Generics, attrs : Vec<Attribute>, input : DataStruct) -> Result<TokenStream>
{
fn expand_struct(ident: Ident, generics: Generics, attrs: Vec<Attribute>, input: DataStruct) -> Result<TokenStream> {
let krate = super::krate();
let where_clause = expand_where(&generics);
@ -239,12 +218,13 @@ fn expand_struct(ident : Ident, generics : Generics, attrs : Vec<Attribute>, inp
};
let fields: Vec<TokenStream> = match input.fields {
Fields::Named(named_fields) => {
named_fields.named.iter()
.map(expand_field)
.collect_to_result()?
Fields::Named(named_fields) => named_fields.named.iter().map(expand_field).collect_to_result()?,
Fields::Unnamed(fields) => {
return Err(Error::new(
fields.span(),
"#[derive(OpenapiType)] does not support unnamed fields"
))
},
Fields::Unnamed(fields) => return Err(Error::new(fields.span(), "#[derive(OpenapiType)] does not support unnamed fields")),
Fields::Unit => Vec::new()
};

View file

@ -6,34 +6,25 @@ use syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
spanned::Spanned,
DeriveInput,
Error,
Generics,
Path,
Result,
Token
DeriveInput, Error, Generics, Path, Result, Token
};
struct MimeList(Punctuated<Path, Token![,]>);
impl Parse for MimeList
{
fn parse(input: ParseStream) -> Result<Self>
{
impl Parse for MimeList {
fn parse(input: ParseStream) -> Result<Self> {
let list = Punctuated::parse_separated_nonempty(&input)?;
Ok(Self(list))
}
}
#[cfg(not(feature = "openapi"))]
fn impl_openapi_type(_ident : &Ident, _generics : &Generics) -> TokenStream
{
fn impl_openapi_type(_ident: &Ident, _generics: &Generics) -> TokenStream {
quote!()
}
#[cfg(feature = "openapi")]
fn impl_openapi_type(ident : &Ident, generics : &Generics) -> TokenStream
{
fn impl_openapi_type(ident: &Ident, generics: &Generics) -> TokenStream {
let krate = super::krate();
quote! {
@ -52,20 +43,26 @@ fn impl_openapi_type(ident : &Ident, generics : &Generics) -> TokenStream
}
}
pub fn expand_request_body(input : DeriveInput) -> Result<TokenStream>
{
pub fn expand_request_body(input: DeriveInput) -> Result<TokenStream> {
let krate = super::krate();
let ident = input.ident;
let generics = input.generics;
let types = input.attrs.into_iter()
.filter(|attr| attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("supported_types".to_string()))
let types = input
.attrs
.into_iter()
.filter(|attr| {
attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("supported_types".to_string())
})
.flat_map(|attr| {
let span = attr.span();
attr.parse_args::<MimeList>()
.map(|list| Box::new(list.0.into_iter().map(Ok)) as Box<dyn Iterator<Item = Result<Path>>>)
.unwrap_or_else(|mut err| {
err.combine(Error::new(span, "Hint: Types list should look like #[supported_types(TEXT_PLAIN, APPLICATION_JSON)]"));
err.combine(Error::new(
span,
"Hint: Types list should look like #[supported_types(TEXT_PLAIN, APPLICATION_JSON)]"
));
Box::new(iter::once(Err(err)))
})
})

View file

@ -1,23 +1,18 @@
use crate::{method::Method, util::CollectToResult};
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use std::{iter, str::FromStr};
use syn::{
parenthesized,
parse::{Parse, ParseStream},
punctuated::Punctuated,
DeriveInput,
Error,
Result,
Token
DeriveInput, Error, Result, Token
};
use std::{iter, str::FromStr};
struct MethodList(Punctuated<Ident, Token![,]>);
impl Parse for MethodList
{
fn parse(input: ParseStream) -> Result<Self>
{
impl Parse for MethodList {
fn parse(input: ParseStream) -> Result<Self> {
let content;
let _paren = parenthesized!(content in input);
let list = Punctuated::parse_separated_nonempty(&content)?;
@ -25,17 +20,22 @@ impl Parse for MethodList
}
}
pub fn expand_resource(input : DeriveInput) -> Result<TokenStream>
{
pub fn expand_resource(input: DeriveInput) -> Result<TokenStream> {
let krate = super::krate();
let ident = input.ident;
let name = ident.to_string();
let methods = input.attrs.into_iter().filter(|attr|
attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("resource".to_string()) // TODO wtf
).map(|attr| {
syn::parse2(attr.tokens).map(|m : MethodList| m.0.into_iter())
}).flat_map(|list| match list {
let methods =
input
.attrs
.into_iter()
.filter(
|attr| {
attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("resource".to_string())
} // TODO wtf
)
.map(|attr| syn::parse2(attr.tokens).map(|m: MethodList| m.0.into_iter()))
.flat_map(|list| match list {
Ok(iter) => Box::new(iter.map(|method| {
let method = Method::from_str(&method.to_string()).map_err(|err| Error::new(method.span(), err))?;
let mod_ident = method.mod_ident(&name);
@ -43,7 +43,8 @@ pub fn expand_resource(input : DeriveInput) -> Result<TokenStream>
Ok(quote!(#mod_ident::#ident(&mut route);))
})) as Box<dyn Iterator<Item = Result<TokenStream>>>,
Err(err) => Box::new(iter::once(Err(err)))
}).collect_to_result()?;
})
.collect_to_result()?;
Ok(quote! {
impl #krate::Resource for #ident

View file

@ -1,33 +1,19 @@
use crate::util::{CollectToResult, remove_parens};
use crate::util::{remove_parens, CollectToResult};
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};
use std::iter;
use syn::{
spanned::Spanned,
Attribute,
Data,
DeriveInput,
Error,
Fields,
GenericParam,
LitStr,
Path,
PathSegment,
Result,
Type,
spanned::Spanned, Attribute, Data, DeriveInput, Error, Fields, GenericParam, LitStr, Path, PathSegment, Result, Type,
Variant
};
struct ErrorVariantField
{
struct ErrorVariantField {
attrs: Vec<Attribute>,
ident: Ident,
ty: Type
}
struct ErrorVariant
{
struct ErrorVariant {
ident: Ident,
status: Option<Path>,
is_named: bool,
@ -36,11 +22,11 @@ struct ErrorVariant
display: Option<LitStr>
}
fn process_variant(variant : Variant) -> Result<ErrorVariant>
{
let status = match variant.attrs.iter()
.find(|attr| attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("status".to_string()))
{
fn process_variant(variant: Variant) -> Result<ErrorVariant> {
let status =
match variant.attrs.iter().find(|attr| {
attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("status".to_string())
}) {
Some(attr) => Some(syn::parse2(remove_parens(attr.tokens.clone()))?),
None => None
};
@ -50,19 +36,19 @@ fn process_variant(variant : Variant) -> Result<ErrorVariant>
match variant.fields {
Fields::Named(named) => {
is_named = true;
for field in named.named
{
for field in named.named {
let span = field.span();
fields.push(ErrorVariantField {
attrs: field.attrs,
ident: field.ident.ok_or_else(|| Error::new(span, "Missing ident for this enum variant field"))?,
ident: field
.ident
.ok_or_else(|| Error::new(span, "Missing ident for this enum variant field"))?,
ty: field.ty
});
}
},
Fields::Unnamed(unnamed) => {
for (i, field) in unnamed.unnamed.into_iter().enumerate()
{
for (i, field) in unnamed.unnamed.into_iter().enumerate() {
fields.push(ErrorVariantField {
attrs: field.attrs,
ident: format_ident!("arg{}", i),
@ -73,14 +59,20 @@ fn process_variant(variant : Variant) -> Result<ErrorVariant>
Fields::Unit => {}
}
let from_ty = fields.iter()
let from_ty = fields
.iter()
.enumerate()
.find(|(_, field)| field.attrs.iter().any(|attr| attr.path.segments.last().map(|segment| segment.ident.to_string()) == Some("from".to_string())))
.find(|(_, field)| {
field
.attrs
.iter()
.any(|attr| attr.path.segments.last().map(|segment| segment.ident.to_string()) == Some("from".to_string()))
})
.map(|(i, field)| (i, field.ty.clone()));
let display = match variant.attrs.iter()
.find(|attr| attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("display".to_string()))
{
let display = match variant.attrs.iter().find(|attr| {
attr.path.segments.iter().last().map(|segment| segment.ident.to_string()) == Some("display".to_string())
}) {
Some(attr) => Some(syn::parse2(remove_parens(attr.tokens.clone()))?),
None => None
};
@ -95,18 +87,15 @@ fn process_variant(variant : Variant) -> Result<ErrorVariant>
})
}
fn path_segment(name : &str) -> PathSegment
{
fn path_segment(name: &str) -> PathSegment {
PathSegment {
ident: format_ident!("{}", name),
arguments: Default::default()
}
}
impl ErrorVariant
{
fn fields_pat(&self) -> TokenStream
{
impl ErrorVariant {
fn fields_pat(&self) -> TokenStream {
let mut fields = self.fields.iter().map(|field| &field.ident).peekable();
if fields.peek().is_none() {
quote!()
@ -117,10 +106,12 @@ impl ErrorVariant
}
}
fn to_display_match_arm(&self, formatter_ident : &Ident, enum_ident : &Ident) -> Result<TokenStream>
{
fn to_display_match_arm(&self, formatter_ident: &Ident, enum_ident: &Ident) -> Result<TokenStream> {
let ident = &self.ident;
let display = self.display.as_ref().ok_or_else(|| Error::new(self.ident.span(), "Missing display string for this variant"))?;
let display = self
.display
.as_ref()
.ok_or_else(|| Error::new(self.ident.span(), "Missing display string for this variant"))?;
// lets find all required format parameters
let display_str = display.value();
@ -128,38 +119,45 @@ impl ErrorVariant
let len = display_str.len();
let mut start = len;
let mut iter = display_str.chars().enumerate().peekable();
while let Some((i, c)) = iter.next()
{
while let Some((i, c)) = iter.next() {
// we found a new opening brace
if start == len && c == '{'
{
if start == len && c == '{' {
start = i + 1;
}
// we found a duplicate opening brace
else if start == i && c == '{'
{
else if start == i && c == '{' {
start = len;
}
// we found a closing brace
else if start < i && c == '}'
{
else if start < i && c == '}' {
match iter.peek() {
Some((_, '}')) => return Err(Error::new(display.span(), "Error parsing format string: curly braces not allowed inside parameter name")),
Some((_, '}')) => {
return Err(Error::new(
display.span(),
"Error parsing format string: curly braces not allowed inside parameter name"
))
},
_ => params.push(&display_str[start..i])
};
start = len;
}
// we found a closing brace without content
else if start == i && c == '}'
{
return Err(Error::new(display.span(), "Error parsing format string: parameter name must not be empty"))
else if start == i && c == '}' {
return Err(Error::new(
display.span(),
"Error parsing format string: parameter name must not be empty"
));
}
}
if start != len
{
return Err(Error::new(display.span(), "Error parsing format string: Unmatched opening brace"));
if start != len {
return Err(Error::new(
display.span(),
"Error parsing format string: Unmatched opening brace"
));
}
let params = params.into_iter().map(|name| format_ident!("{}{}", if self.is_named { "" } else { "arg" }, name));
let params = params
.into_iter()
.map(|name| format_ident!("{}{}", if self.is_named { "" } else { "arg" }, name));
let fields_pat = self.fields_pat();
Ok(quote! {
@ -167,21 +165,28 @@ impl ErrorVariant
})
}
fn into_match_arm(self, krate : &TokenStream, enum_ident : &Ident) -> Result<TokenStream>
{
fn into_match_arm(self, krate: &TokenStream, enum_ident: &Ident) -> Result<TokenStream> {
let ident = &self.ident;
let fields_pat = self.fields_pat();
let status = self.status.map(|status| {
// the status might be relative to StatusCode, so let's fix that
if status.leading_colon.is_none() && status.segments.len() < 2
{
if status.leading_colon.is_none() && status.segments.len() < 2 {
let status_ident = status.segments.first().cloned().unwrap_or_else(|| path_segment("OK"));
Path {
leading_colon: Some(Default::default()),
segments: vec![path_segment("gotham_restful"), path_segment("gotham"), path_segment("hyper"), path_segment("StatusCode"), status_ident].into_iter().collect()
segments: vec![
path_segment("gotham_restful"),
path_segment("gotham"),
path_segment("hyper"),
path_segment("StatusCode"),
status_ident,
]
.into_iter()
.collect()
}
} else {
status
}
else { status }
});
// the response will come directly from the from_ty if present
@ -204,8 +209,7 @@ impl ErrorVariant
})
}
fn were(&self) -> Option<TokenStream>
{
fn were(&self) -> Option<TokenStream> {
match self.from_ty.as_ref() {
Some((_, ty)) => Some(quote!( #ty : ::std::error::Error )),
None => None
@ -213,8 +217,7 @@ impl ErrorVariant
}
}
pub fn expand_resource_error(input : DeriveInput) -> Result<TokenStream>
{
pub fn expand_resource_error(input: DeriveInput) -> Result<TokenStream> {
let krate = super::krate();
let ident = input.ident;
let generics = input.generics;
@ -223,12 +226,13 @@ pub fn expand_resource_error(input : DeriveInput) -> Result<TokenStream>
Data::Enum(inum) => Ok(inum),
Data::Struct(strukt) => Err(strukt.struct_token.span()),
Data::Union(uni) => Err(uni.union_token.span())
}.map_err(|span| Error::new(span, "#[derive(ResourceError)] only works for enums"))?;
let variants = inum.variants.into_iter()
.map(process_variant)
.collect_to_result()?;
}
.map_err(|span| Error::new(span, "#[derive(ResourceError)] only works for enums"))?;
let variants = inum.variants.into_iter().map(process_variant).collect_to_result()?;
let display_impl = if variants.iter().any(|v| v.display.is_none()) { None } else {
let display_impl = if variants.iter().any(|v| v.display.is_none()) {
None
} else {
let were = generics.params.iter().filter_map(|param| match param {
GenericParam::Type(ty) => {
let ident = &ty.ident;
@ -237,7 +241,8 @@ pub fn expand_resource_error(input : DeriveInput) -> Result<TokenStream>
_ => None
});
let formatter_ident = format_ident!("resource_error_display_formatter");
let match_arms = variants.iter()
let match_arms = variants
.iter()
.map(|v| v.to_display_match_arm(&formatter_ident, &ident))
.collect_to_result()?;
Some(quote! {
@ -256,8 +261,7 @@ pub fn expand_resource_error(input : DeriveInput) -> Result<TokenStream>
let mut from_impls: Vec<TokenStream> = Vec::new();
for var in &variants
{
for var in &variants {
let var_ident = &var.ident;
let (from_index, from_ty) = match var.from_ty.as_ref() {
Some(f) => f,
@ -266,14 +270,20 @@ pub fn expand_resource_error(input : DeriveInput) -> Result<TokenStream>
let from_ident = &var.fields[*from_index].ident;
let fields_pat = var.fields_pat();
let fields_where = var.fields.iter().enumerate()
let fields_where = var
.fields
.iter()
.enumerate()
.filter(|(i, _)| i != from_index)
.map(|(_, field)| {
let ty = &field.ty;
quote!( #ty : Default )
})
.chain(iter::once(quote!( #from_ty : ::std::error::Error )));
let fields_let = var.fields.iter().enumerate()
let fields_let = var
.fields
.iter()
.enumerate()
.filter(|(i, _)| i != from_index)
.map(|(_, field)| {
let id = &field.ident;
@ -295,7 +305,8 @@ pub fn expand_resource_error(input : DeriveInput) -> Result<TokenStream>
}
let were = variants.iter().filter_map(|variant| variant.were()).collect::<Vec<_>>();
let variants = variants.into_iter()
let variants = variants
.into_iter()
.map(|variant| variant.into_match_arm(&krate, &ident))
.collect_to_result()?;

View file

@ -2,8 +2,7 @@ use proc_macro2::{Delimiter, TokenStream, TokenTree};
use std::iter;
use syn::Error;
pub trait CollectToResult
{
pub trait CollectToResult {
type Item;
fn collect_to_result(self) -> Result<Vec<Self::Item>, Error>;
@ -15,27 +14,26 @@ where
{
type Item = Item;
fn collect_to_result(self) -> Result<Vec<Item>, Error>
{
self.fold(<Result<Vec<Item>, Error>>::Ok(Vec::new()), |res, code| {
match (code, res) {
(Ok(code), Ok(mut codes)) => { codes.push(code); Ok(codes) },
fn collect_to_result(self) -> Result<Vec<Item>, Error> {
self.fold(<Result<Vec<Item>, Error>>::Ok(Vec::new()), |res, code| match (code, res) {
(Ok(code), Ok(mut codes)) => {
codes.push(code);
Ok(codes)
},
(Ok(_), Err(errors)) => Err(errors),
(Err(err), Ok(_)) => Err(err),
(Err(err), Err(mut errors)) => { errors.combine(err); Err(errors) }
(Err(err), Err(mut errors)) => {
errors.combine(err);
Err(errors)
}
})
}
}
pub fn remove_parens(input : TokenStream) -> TokenStream
{
pub fn remove_parens(input: TokenStream) -> TokenStream {
let iter = input.into_iter().flat_map(|tt| {
if let TokenTree::Group(group) = &tt
{
if group.delimiter() == Delimiter::Parenthesis
{
if let TokenTree::Group(group) = &tt {
if group.delimiter() == Delimiter::Parenthesis {
return Box::new(group.stream().into_iter()) as Box<dyn Iterator<Item = TokenTree>>;
}
}

View file

@ -1,5 +1,7 @@
#[macro_use] extern crate gotham_derive;
#[macro_use] extern crate log;
#[macro_use]
extern crate gotham_derive;
#[macro_use]
extern crate log;
use fake::{faker::internet::en::Username, Fake};
use gotham::{
@ -20,25 +22,19 @@ use serde::{Deserialize, Serialize};
#[derive(Resource)]
#[resource(read_all, read, search, create, change_all, change, remove, remove_all)]
struct Users
{
}
struct Users {}
#[derive(Resource)]
#[resource(ReadAll)]
struct Auth
{
}
struct Auth {}
#[derive(Deserialize, OpenapiType, Serialize, StateData, StaticResponseExtender)]
struct User
{
struct User {
username: String
}
#[read_all(Users)]
fn read_all() -> Success<Vec<Option<User>>>
{
fn read_all() -> Success<Vec<Option<User>>> {
vec![Username().fake(), Username().fake()]
.into_iter()
.map(|username| Some(User { username }))
@ -47,51 +43,49 @@ fn read_all() -> Success<Vec<Option<User>>>
}
#[read(Users)]
fn read(id : u64) -> Success<User>
{
fn read(id: u64) -> Success<User> {
let username: String = Username().fake();
User { username: format!("{}{}", username, id) }.into()
User {
username: format!("{}{}", username, id)
}
.into()
}
#[search(Users)]
fn search(query : User) -> Success<User>
{
fn search(query: User) -> Success<User> {
query.into()
}
#[create(Users)]
fn create(body : User)
{
fn create(body: User) {
info!("Created User: {}", body.username);
}
#[change_all(Users)]
fn update_all(body : Vec<User>)
{
info!("Changing all Users to {:?}", body.into_iter().map(|u| u.username).collect::<Vec<String>>());
fn update_all(body: Vec<User>) {
info!(
"Changing all Users to {:?}",
body.into_iter().map(|u| u.username).collect::<Vec<String>>()
);
}
#[change(Users)]
fn update(id : u64, body : User)
{
fn update(id: u64, body: User) {
info!("Change User {} to {}", id, body.username);
}
#[remove_all(Users)]
fn remove_all()
{
fn remove_all() {
info!("Delete all Users");
}
#[remove(Users)]
fn remove(id : u64)
{
fn remove(id: u64) {
info!("Delete User {}", id);
}
#[read_all(Auth)]
fn auth_read_all(auth : AuthStatus<()>) -> AuthSuccess<String>
{
fn auth_read_all(auth: AuthStatus<()>) -> AuthSuccess<String> {
match auth {
AuthStatus::Authenticated(data) => Ok(format!("{:?}", data)),
_ => Err(Forbidden)
@ -102,25 +96,19 @@ const ADDR : &str = "127.0.0.1:18080";
#[derive(Clone, Default)]
struct Handler;
impl<T> AuthHandler<T> for Handler
{
fn jwt_secret<F : FnOnce() -> Option<T>>(&self, _state : &mut State, _decode_data : F) -> Option<Vec<u8>>
{
impl<T> AuthHandler<T> for Handler {
fn jwt_secret<F: FnOnce() -> Option<T>>(&self, _state: &mut State, _decode_data: F) -> Option<Vec<u8>> {
None
}
}
fn main()
{
fn main() {
let encoder = PatternEncoder::new("{d(%Y-%m-%d %H:%M:%S%.3f %Z)} [{l}] {M} - {m}\n");
let config = Config::builder()
.appender(
Appender::builder()
.build("stdout", Box::new(
ConsoleAppender::builder()
.encoder(Box::new(encoder))
.build()
)))
.appender(Appender::builder().build(
"stdout",
Box::new(ConsoleAppender::builder().encoder(Box::new(encoder)).build())
))
.build(Root::builder().appender("stdout").build(LevelFilter::Info))
.unwrap();
log4rs::init_config(config).unwrap();
@ -134,15 +122,11 @@ fn main()
let auth = <AuthMiddleware<(), Handler>>::from_source(AuthSource::AuthorizationHeader);
let logging = RequestLogger::new(log::Level::Info);
let (chain, pipelines) = single_pipeline(
new_pipeline()
.add(auth)
.add(logging)
.add(cors)
.build()
);
let (chain, pipelines) = single_pipeline(new_pipeline().add(auth).add(logging).add(cors).build());
gotham::start(ADDR, build_router(chain, pipelines, |route| {
gotham::start(
ADDR,
build_router(chain, pipelines, |route| {
let info = OpenapiInfo {
title: "Users Example".to_owned(),
version: "0.0.1".to_owned(),
@ -153,7 +137,7 @@ fn main()
route.resource::<Auth>("auth");
route.get_openapi("openapi");
});
}));
})
);
println!("Gotham started on {} for testing", ADDR);
}

19
rustfmt.toml Normal file
View file

@ -0,0 +1,19 @@
edition = "2018"
max_width = 125
newline_style = "Unix"
unstable_features = true
# always use tabs.
hard_tabs = true
tab_spaces = 4
# commas inbetween but not after
match_block_trailing_comma = true
trailing_comma = "Never"
# misc
format_code_in_doc_comments = true
merge_imports = true
overflow_delimited_expr = true
use_field_init_shorthand = true
use_try_shorthand = true

View file

@ -1,29 +1,24 @@
use crate::{AuthError, Forbidden, HeaderName};
use cookie::CookieJar;
use futures_util::{future, future::{FutureExt, TryFutureExt}};
use futures_util::{
future,
future::{FutureExt, TryFutureExt}
};
use gotham::{
handler::HandlerFuture,
hyper::header::{AUTHORIZATION, HeaderMap},
hyper::header::{HeaderMap, AUTHORIZATION},
middleware::{Middleware, NewMiddleware},
state::{FromState, State}
};
use jsonwebtoken::{
errors::ErrorKind,
DecodingKey
};
use jsonwebtoken::{errors::ErrorKind, DecodingKey};
use serde::de::DeserializeOwned;
use std::{
marker::PhantomData,
panic::RefUnwindSafe,
pin::Pin
};
use std::{marker::PhantomData, panic::RefUnwindSafe, pin::Pin};
pub use jsonwebtoken::Validation as AuthValidation;
/// The authentication status returned by the auth middleware for each request.
#[derive(Debug, StateData)]
pub enum AuthStatus<T : Send + 'static>
{
pub enum AuthStatus<T: Send + 'static> {
/// The auth status is unknown.
Unknown,
/// The request has been performed without any kind of authentication.
@ -40,8 +35,7 @@ impl<T> Clone for AuthStatus<T>
where
T: Clone + Send + 'static
{
fn clone(&self) -> Self
{
fn clone(&self) -> Self {
match self {
Self::Unknown => Self::Unknown,
Self::Unauthenticated => Self::Unauthenticated,
@ -52,16 +46,10 @@ where
}
}
impl<T> Copy for AuthStatus<T>
where
T : Copy + Send + 'static
{
}
impl<T> Copy for AuthStatus<T> where T: Copy + Send + 'static {}
impl<T : Send + 'static> AuthStatus<T>
{
pub fn ok(self) -> Result<T, AuthError>
{
impl<T: Send + 'static> AuthStatus<T> {
pub fn ok(self) -> Result<T, AuthError> {
match self {
Self::Authenticated(data) => Ok(data),
_ => Err(Forbidden)
@ -71,8 +59,7 @@ impl<T : Send + 'static> AuthStatus<T>
/// The source of the authentication token in the request.
#[derive(Clone, Debug, StateData)]
pub enum AuthSource
{
pub enum AuthSource {
/// Take the token from a cookie with the given name.
Cookie(String),
/// Take the token from a header with the given name.
@ -100,36 +87,29 @@ impl<T> AuthHandler<T> for CustomAuthHandler {
}
```
*/
pub trait AuthHandler<Data>
{
pub trait AuthHandler<Data> {
/// Return the SHA256-HMAC secret used to verify the JWT token.
fn jwt_secret<F: FnOnce() -> Option<Data>>(&self, state: &mut State, decode_data: F) -> Option<Vec<u8>>;
}
/// An `AuthHandler` returning always the same secret. See `AuthMiddleware` for a usage example.
#[derive(Clone, Debug)]
pub struct StaticAuthHandler
{
pub struct StaticAuthHandler {
secret: Vec<u8>
}
impl StaticAuthHandler
{
pub fn from_vec(secret : Vec<u8>) -> Self
{
impl StaticAuthHandler {
pub fn from_vec(secret: Vec<u8>) -> Self {
Self { secret }
}
pub fn from_array(secret : &[u8]) -> Self
{
pub fn from_array(secret: &[u8]) -> Self {
Self::from_vec(secret.to_vec())
}
}
impl<T> AuthHandler<T> for StaticAuthHandler
{
fn jwt_secret<F : FnOnce() -> Option<T>>(&self, _state : &mut State, _decode_data : F) -> Option<Vec<u8>>
{
impl<T> AuthHandler<T> for StaticAuthHandler {
fn jwt_secret<F: FnOnce() -> Option<T>>(&self, _state: &mut State, _decode_data: F) -> Option<Vec<u8>> {
Some(self.secret.clone())
}
}
@ -173,8 +153,7 @@ fn main() {
```
*/
#[derive(Debug)]
pub struct AuthMiddleware<Data, Handler>
{
pub struct AuthMiddleware<Data, Handler> {
source: AuthSource,
validation: AuthValidation,
handler: Handler,
@ -182,10 +161,10 @@ pub struct AuthMiddleware<Data, Handler>
}
impl<Data, Handler> Clone for AuthMiddleware<Data, Handler>
where Handler : Clone
{
fn clone(&self) -> Self
where
Handler: Clone
{
fn clone(&self) -> Self {
Self {
source: self.source.clone(),
validation: self.validation.clone(),
@ -200,8 +179,7 @@ where
Data: DeserializeOwned + Send,
Handler: AuthHandler<Data> + Default
{
pub fn from_source(source : AuthSource) -> Self
{
pub fn from_source(source: AuthSource) -> Self {
Self {
source,
validation: Default::default(),
@ -216,8 +194,7 @@ where
Data: DeserializeOwned + Send,
Handler: AuthHandler<Data>
{
pub fn new(source : AuthSource, validation : AuthValidation, handler : Handler) -> Self
{
pub fn new(source: AuthSource, validation: AuthValidation, handler: Handler) -> Self {
Self {
source,
validation,
@ -226,28 +203,21 @@ where
}
}
fn auth_status(&self, state : &mut State) -> AuthStatus<Data>
{
fn auth_status(&self, state: &mut State) -> AuthStatus<Data> {
// extract the provided token, if any
let token = match &self.source {
AuthSource::Cookie(name) => {
CookieJar::try_borrow_from(&state)
AuthSource::Cookie(name) => CookieJar::try_borrow_from(&state)
.and_then(|jar| jar.get(&name))
.map(|cookie| cookie.value().to_owned())
},
AuthSource::Header(name) => {
HeaderMap::try_borrow_from(&state)
.map(|cookie| cookie.value().to_owned()),
AuthSource::Header(name) => HeaderMap::try_borrow_from(&state)
.and_then(|map| map.get(name))
.and_then(|header| header.to_str().ok())
.map(|value| value.to_owned())
},
AuthSource::AuthorizationHeader => {
HeaderMap::try_borrow_from(&state)
.map(|value| value.to_owned()),
AuthSource::AuthorizationHeader => HeaderMap::try_borrow_from(&state)
.and_then(|map| map.get(AUTHORIZATION))
.and_then(|header| header.to_str().ok())
.and_then(|value| value.split_whitespace().nth(1))
.map(|value| value.to_owned())
}
};
// unauthed if no token
@ -310,16 +280,14 @@ where
{
type Instance = Self;
fn new_middleware(&self) -> Result<Self::Instance, std::io::Error>
{
fn new_middleware(&self) -> Result<Self::Instance, std::io::Error> {
let c: Self = self.clone();
Ok(c)
}
}
#[cfg(test)]
mod test
{
mod test {
use super::*;
use cookie::Cookie;
use std::fmt::Debug;
@ -333,18 +301,15 @@ mod test
const INVALID_TOKEN : &'static str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJtc3JkMCIsInN1YiI6ImdvdGhhbS1yZXN0ZnVsIiwiaWF0IjoxNTc3ODM2ODAwLCJleHAiOjQxMDI0NDQ4MDB9";
#[derive(Debug, Deserialize, PartialEq)]
struct TestData
{
struct TestData {
iss: String,
sub: String,
iat: u64,
exp: u64
}
impl Default for TestData
{
fn default() -> Self
{
impl Default for TestData {
fn default() -> Self {
Self {
iss: "msrd0".to_owned(),
sub: "gotham-restful".to_owned(),
@ -356,17 +321,14 @@ mod test
#[derive(Default)]
struct NoneAuthHandler;
impl<T> AuthHandler<T> for NoneAuthHandler
{
fn jwt_secret<F : FnOnce() -> Option<T>>(&self, _state : &mut State, _decode_data : F) -> Option<Vec<u8>>
{
impl<T> AuthHandler<T> for NoneAuthHandler {
fn jwt_secret<F: FnOnce() -> Option<T>>(&self, _state: &mut State, _decode_data: F) -> Option<Vec<u8>> {
None
}
}
#[test]
fn test_auth_middleware_none_secret()
{
fn test_auth_middleware_none_secret() {
let middleware = <AuthMiddleware<TestData, NoneAuthHandler>>::from_source(AuthSource::AuthorizationHeader);
State::with_new(|mut state| {
let mut headers = HeaderMap::new();
@ -379,18 +341,17 @@ mod test
#[derive(Default)]
struct TestAssertingHandler;
impl<T> AuthHandler<T> for TestAssertingHandler
where T : Debug + Default + PartialEq
{
fn jwt_secret<F : FnOnce() -> Option<T>>(&self, _state : &mut State, decode_data : F) -> Option<Vec<u8>>
where
T: Debug + Default + PartialEq
{
fn jwt_secret<F: FnOnce() -> Option<T>>(&self, _state: &mut State, decode_data: F) -> Option<Vec<u8>> {
assert_eq!(decode_data(), Some(T::default()));
Some(JWT_SECRET.to_vec())
}
}
#[test]
fn test_auth_middleware_decode_data()
{
fn test_auth_middleware_decode_data() {
let middleware = <AuthMiddleware<TestData, TestAssertingHandler>>::from_source(AuthSource::AuthorizationHeader);
State::with_new(|mut state| {
let mut headers = HeaderMap::new();
@ -401,14 +362,14 @@ mod test
}
fn new_middleware<T>(source: AuthSource) -> AuthMiddleware<T, StaticAuthHandler>
where T : DeserializeOwned + Send
where
T: DeserializeOwned + Send
{
AuthMiddleware::new(source, Default::default(), StaticAuthHandler::from_array(JWT_SECRET))
}
#[test]
fn test_auth_middleware_no_token()
{
fn test_auth_middleware_no_token() {
let middleware = new_middleware::<TestData>(AuthSource::AuthorizationHeader);
State::with_new(|mut state| {
let status = middleware.auth_status(&mut state);
@ -420,8 +381,7 @@ mod test
}
#[test]
fn test_auth_middleware_expired_token()
{
fn test_auth_middleware_expired_token() {
let middleware = new_middleware::<TestData>(AuthSource::AuthorizationHeader);
State::with_new(|mut state| {
let mut headers = HeaderMap::new();
@ -436,8 +396,7 @@ mod test
}
#[test]
fn test_auth_middleware_invalid_token()
{
fn test_auth_middleware_invalid_token() {
let middleware = new_middleware::<TestData>(AuthSource::AuthorizationHeader);
State::with_new(|mut state| {
let mut headers = HeaderMap::new();
@ -452,8 +411,7 @@ mod test
}
#[test]
fn test_auth_middleware_auth_header_token()
{
fn test_auth_middleware_auth_header_token() {
let middleware = new_middleware::<TestData>(AuthSource::AuthorizationHeader);
State::with_new(|mut state| {
let mut headers = HeaderMap::new();
@ -468,8 +426,7 @@ mod test
}
#[test]
fn test_auth_middleware_header_token()
{
fn test_auth_middleware_header_token() {
let header_name = "x-znoiprwmvfexju";
let middleware = new_middleware::<TestData>(AuthSource::Header(HeaderName::from_static(header_name)));
State::with_new(|mut state| {
@ -485,8 +442,7 @@ mod test
}
#[test]
fn test_auth_middleware_cookie_token()
{
fn test_auth_middleware_cookie_token() {
let cookie_name = "znoiprwmvfexju";
let middleware = new_middleware::<TestData>(AuthSource::Cookie(cookie_name.to_owned()));
State::with_new(|mut state| {

View file

@ -4,22 +4,19 @@ use gotham::{
helpers::http::response::create_empty_response,
hyper::{
header::{
ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS,
ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_MAX_AGE, ACCESS_CONTROL_REQUEST_METHOD, ORIGIN, VARY,
HeaderMap, HeaderName, HeaderValue
HeaderMap, HeaderName, HeaderValue, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS,
ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_MAX_AGE,
ACCESS_CONTROL_REQUEST_METHOD, ORIGIN, VARY
},
Body, Method, Response, StatusCode
},
middleware::Middleware,
pipeline::chain::PipelineHandleChain,
router::builder::*,
state::{FromState, State},
state::{FromState, State}
};
use itertools::Itertools;
use std::{
panic::RefUnwindSafe,
pin::Pin
};
use std::{panic::RefUnwindSafe, pin::Pin};
/**
Specify the allowed origins of the request. It is up to the browser to check the validity of the
@ -27,8 +24,7 @@ origin. This, when sent to the browser, will indicate whether or not the request
allowed to make the request.
*/
#[derive(Clone, Debug)]
pub enum Origin
{
pub enum Origin {
/// Do not send any `Access-Control-Allow-Origin` headers.
None,
/// Send `Access-Control-Allow-Origin: *`. Note that browser will not send credentials.
@ -39,19 +35,15 @@ pub enum Origin
Copy
}
impl Default for Origin
{
fn default() -> Self
{
impl Default for Origin {
fn default() -> Self {
Self::None
}
}
impl Origin
{
impl Origin {
/// Get the header value for the `Access-Control-Allow-Origin` header.
fn header_value(&self, state : &State) -> Option<HeaderValue>
{
fn header_value(&self, state: &State) -> Option<HeaderValue> {
match self {
Self::None => None,
Self::Star => Some("*".parse().unwrap()),
@ -126,8 +118,7 @@ gotham::start("127.0.0.1:8080", build_router((), pipeline_set, |route| {
[`State`]: ../gotham/state/struct.State.html
*/
#[derive(Clone, Debug, Default, NewMiddleware, StateData)]
pub struct CorsConfig
{
pub struct CorsConfig {
/// The allowed origins.
pub origin: Origin,
/// The allowed headers.
@ -138,8 +129,7 @@ pub struct CorsConfig
pub credentials: bool
}
impl Middleware for CorsConfig
{
impl Middleware for CorsConfig {
fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
where
Chain: FnOnce(State) -> Pin<Box<HandlerFuture>>
@ -161,27 +151,23 @@ For further information on CORS, read https://developer.mozilla.org/en-US/docs/W
[`CorsConfig`]: ./struct.CorsConfig.html
*/
pub fn handle_cors(state : &State, res : &mut Response<Body>)
{
pub fn handle_cors(state: &State, res: &mut Response<Body>) {
let config = CorsConfig::try_borrow_from(state);
let headers = res.headers_mut();
// non-preflight requests require the Access-Control-Allow-Origin header
if let Some(header) = config.and_then(|cfg| cfg.origin.header_value(state))
{
if let Some(header) = config.and_then(|cfg| cfg.origin.header_value(state)) {
headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, header);
}
// if the origin is copied over, we should tell the browser by specifying the Vary header
if matches!(config.map(|cfg| &cfg.origin), Some(Origin::Copy))
{
if matches!(config.map(|cfg| &cfg.origin), Some(Origin::Copy)) {
let vary = headers.get(VARY).map(|vary| format!("{},Origin", vary.to_str().unwrap()));
headers.insert(VARY, vary.as_deref().unwrap_or("Origin").parse().unwrap());
}
// if we allow credentials, tell the browser
if config.map(|cfg| cfg.credentials).unwrap_or(false)
{
if config.map(|cfg| cfg.credentials).unwrap_or(false) {
headers.insert(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true".parse().unwrap());
}
}
@ -214,8 +200,7 @@ where
fn cors(&mut self, path: &str, method: Method);
}
fn cors_preflight_handler(state : State) -> (State, Response<Body>)
{
fn cors_preflight_handler(state: State) -> (State, Response<Body>) {
let config = CorsConfig::try_borrow_from(&state);
// prepare the response
@ -223,22 +208,22 @@ fn cors_preflight_handler(state : State) -> (State, Response<Body>)
let headers = res.headers_mut();
// copy the request method over to the response
let method = HeaderMap::borrow_from(&state).get(ACCESS_CONTROL_REQUEST_METHOD).unwrap().clone();
let method = HeaderMap::borrow_from(&state)
.get(ACCESS_CONTROL_REQUEST_METHOD)
.unwrap()
.clone();
headers.insert(ACCESS_CONTROL_ALLOW_METHODS, method);
// if we allow any headers, put them in
if let Some(hdrs) = config.map(|cfg| &cfg.headers)
{
if hdrs.len() > 0
{
if let Some(hdrs) = config.map(|cfg| &cfg.headers) {
if hdrs.len() > 0 {
// TODO do we want to return all headers or just those asked by the browser?
headers.insert(ACCESS_CONTROL_ALLOW_HEADERS, hdrs.iter().join(",").parse().unwrap());
}
}
// set the max age for the preflight cache
if let Some(age) = config.map(|cfg| cfg.max_age)
{
if let Some(age) = config.map(|cfg| cfg.max_age) {
headers.insert(ACCESS_CONTROL_MAX_AGE, age.into());
}
@ -255,11 +240,8 @@ where
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static
{
fn cors(&mut self, path : &str, method : Method)
{
fn cors(&mut self, path: &str, method: Method) {
let matcher = AccessControlRequestMethodMatcher::new(method);
self.options(path)
.extend_route_matcher(matcher)
.to(cors_preflight_handler);
self.options(path).extend_route_matcher(matcher).to(cors_preflight_handler);
}
}

View file

@ -370,9 +370,12 @@ Licensed under your option of:
// weird proc macro issue
extern crate self as gotham_restful;
#[macro_use] extern crate gotham_derive;
#[macro_use] extern crate log;
#[macro_use] extern crate serde;
#[macro_use]
extern crate gotham_derive;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde;
#[doc(no_inline)]
pub use gotham;
@ -388,8 +391,7 @@ pub use gotham_restful_derive::*;
/// Not public API
#[doc(hidden)]
pub mod export
{
pub mod export {
pub use futures_util::future::FutureExt;
pub use serde_json;
@ -406,24 +408,12 @@ pub mod export
#[cfg(feature = "auth")]
mod auth;
#[cfg(feature = "auth")]
pub use auth::{
AuthHandler,
AuthMiddleware,
AuthSource,
AuthStatus,
AuthValidation,
StaticAuthHandler
};
pub use auth::{AuthHandler, AuthMiddleware, AuthSource, AuthStatus, AuthValidation, StaticAuthHandler};
#[cfg(feature = "cors")]
mod cors;
#[cfg(feature = "cors")]
pub use cors::{
handle_cors,
CorsConfig,
CorsRoute,
Origin
};
pub use cors::{handle_cors, CorsConfig, CorsRoute, Origin};
pub mod matcher;
@ -438,16 +428,8 @@ pub use openapi::{
mod resource;
pub use resource::{
Resource,
ResourceMethod,
ResourceReadAll,
ResourceRead,
ResourceSearch,
ResourceCreate,
ResourceChangeAll,
ResourceChange,
ResourceRemoveAll,
ResourceRemove
Resource, ResourceChange, ResourceChangeAll, ResourceCreate, ResourceMethod, ResourceRead, ResourceReadAll,
ResourceRemove, ResourceRemoveAll, ResourceSearch
};
mod response;
@ -455,22 +437,14 @@ pub use response::Response;
mod result;
pub use result::{
AuthError,
AuthError::Forbidden,
AuthErrorOrOther,
AuthResult,
AuthSuccess,
IntoResponseError,
NoContent,
Raw,
ResourceResult,
Success
AuthError, AuthError::Forbidden, AuthErrorOrOther, AuthResult, AuthSuccess, IntoResponseError, NoContent, Raw,
ResourceResult, Success
};
mod routing;
pub use routing::{DrawResources, DrawResourceRoutes};
#[cfg(feature = "openapi")]
pub use routing::WithOpenapi;
pub use routing::{DrawResourceRoutes, DrawResources};
mod types;
pub use types::*;

View file

@ -1,5 +1,8 @@
use gotham::{
hyper::{header::{ACCESS_CONTROL_REQUEST_METHOD, HeaderMap}, Method, StatusCode},
hyper::{
header::{HeaderMap, ACCESS_CONTROL_REQUEST_METHOD},
Method, StatusCode
},
router::{non_match::RouteNonMatch, route::matcher::RouteMatcher},
state::{FromState, State}
};
@ -18,9 +21,7 @@ use gotham::{
///
/// # build_simple_router(|route| {
/// // use the matcher for your request
/// route.options("/foo")
/// .extend_route_matcher(matcher)
/// .to(|state| {
/// route.options("/foo").extend_route_matcher(matcher).to(|state| {
/// // we know that this is a CORS preflight for a PUT request
/// let mut res = create_empty_response(&state, StatusCode::NO_CONTENT);
/// res.headers_mut().insert(ACCESS_CONTROL_ALLOW_METHODS, "PUT".parse().unwrap());
@ -29,30 +30,26 @@ use gotham::{
/// # });
/// ```
#[derive(Clone, Debug)]
pub struct AccessControlRequestMethodMatcher
{
pub struct AccessControlRequestMethodMatcher {
method: Method
}
impl AccessControlRequestMethodMatcher
{
impl AccessControlRequestMethodMatcher {
/// Construct a new matcher that matches if the `Access-Control-Request-Method` header matches `method`.
/// Note that during matching the method is normalized according to the fetch specification, that is,
/// byte-uppercased. This means that when using a custom `method` instead of a predefined one, make sure
/// it is uppercased or this matcher will never succeed.
pub fn new(method : Method) -> Self
{
pub fn new(method: Method) -> Self {
Self { method }
}
}
impl RouteMatcher for AccessControlRequestMethodMatcher
{
fn is_match(&self, state : &State) -> Result<(), RouteNonMatch>
{
impl RouteMatcher for AccessControlRequestMethodMatcher {
fn is_match(&self, state: &State) -> Result<(), RouteNonMatch> {
// according to the fetch specification, methods should be normalized by byte-uppercase
// https://fetch.spec.whatwg.org/#concept-method
match HeaderMap::borrow_from(state).get(ACCESS_CONTROL_REQUEST_METHOD)
match HeaderMap::borrow_from(state)
.get(ACCESS_CONTROL_REQUEST_METHOD)
.and_then(|value| value.to_str().ok())
.and_then(|str| str.to_ascii_uppercase().parse::<Method>().ok())
{
@ -62,19 +59,17 @@ impl RouteMatcher for AccessControlRequestMethodMatcher
}
}
#[cfg(test)]
mod test
{
mod test {
use super::*;
fn with_state<F>(accept: Option<&str>, block: F)
where F : FnOnce(&mut State) -> ()
where
F: FnOnce(&mut State) -> ()
{
State::with_new(|state| {
let mut headers = HeaderMap::new();
if let Some(acc) = accept
{
if let Some(acc) = accept {
headers.insert(ACCESS_CONTROL_REQUEST_METHOD, acc.parse().unwrap());
}
state.put(headers);
@ -83,23 +78,20 @@ mod test
}
#[test]
fn no_acrm_header()
{
fn no_acrm_header() {
let matcher = AccessControlRequestMethodMatcher::new(Method::PUT);
with_state(None, |state| assert!(matcher.is_match(&state).is_err()));
}
#[test]
fn correct_acrm_header()
{
fn correct_acrm_header() {
let matcher = AccessControlRequestMethodMatcher::new(Method::PUT);
with_state(Some("PUT"), |state| assert!(matcher.is_match(&state).is_ok()));
with_state(Some("put"), |state| assert!(matcher.is_match(&state).is_ok()));
}
#[test]
fn incorrect_acrm_header()
{
fn incorrect_acrm_header() {
let matcher = AccessControlRequestMethodMatcher::new(Method::PUT);
with_state(Some("DELETE"), |state| assert!(matcher.is_match(&state).is_err()));
}

View file

@ -2,4 +2,3 @@
mod access_control_request_method;
#[cfg(feature = "cors")]
pub use access_control_request_method::AccessControlRequestMethodMatcher;

View file

@ -1,29 +1,26 @@
use crate::{OpenapiType, OpenapiSchema};
use crate::{OpenapiSchema, OpenapiType};
use indexmap::IndexMap;
use openapiv3::{
Components, OpenAPI, PathItem, ReferenceOr, ReferenceOr::Item, ReferenceOr::Reference, Schema,
Server
Components, OpenAPI, PathItem, ReferenceOr,
ReferenceOr::{Item, Reference},
Schema, Server
};
use std::sync::{Arc, RwLock};
#[derive(Clone, Debug)]
pub struct OpenapiInfo
{
pub struct OpenapiInfo {
pub title: String,
pub version: String,
pub urls: Vec<String>
}
#[derive(Clone, Debug)]
pub struct OpenapiBuilder
{
pub struct OpenapiBuilder {
pub openapi: Arc<RwLock<OpenAPI>>
}
impl OpenapiBuilder
{
pub fn new(info : OpenapiInfo) -> Self
{
impl OpenapiBuilder {
pub fn new(info: OpenapiInfo) -> Self {
Self {
openapi: Arc::new(RwLock::new(OpenAPI {
openapi: "3.0.2".to_string(),
@ -32,8 +29,13 @@ impl OpenapiBuilder
version: info.version,
..Default::default()
},
servers: info.urls.into_iter()
.map(|url| Server { url, ..Default::default() })
servers: info
.urls
.into_iter()
.map(|url| Server {
url,
..Default::default()
})
.collect(),
..Default::default()
}))
@ -42,8 +44,7 @@ impl OpenapiBuilder
/// Remove path from the OpenAPI spec, or return an empty one if not included. This is handy if you need to
/// modify the path and add it back after the modification
pub fn remove_path(&mut self, path : &str) -> PathItem
{
pub fn remove_path(&mut self, path: &str) -> PathItem {
let mut openapi = self.openapi.write().unwrap();
match openapi.paths.swap_remove(path) {
Some(Item(item)) => item,
@ -51,14 +52,12 @@ impl OpenapiBuilder
}
}
pub fn add_path<Path : ToString>(&mut self, path : Path, item : PathItem)
{
pub fn add_path<Path: ToString>(&mut self, path: Path, item: PathItem) {
let mut openapi = self.openapi.write().unwrap();
openapi.paths.insert(path.to_string(), Item(item));
}
fn add_schema_impl(&mut self, name : String, mut schema : OpenapiSchema)
{
fn add_schema_impl(&mut self, name: String, mut schema: OpenapiSchema) {
self.add_schema_dependencies(&mut schema.dependencies);
let mut openapi = self.openapi.write().unwrap();
@ -74,25 +73,23 @@ impl OpenapiBuilder
};
}
fn add_schema_dependencies(&mut self, dependencies : &mut IndexMap<String, OpenapiSchema>)
{
fn add_schema_dependencies(&mut self, dependencies: &mut IndexMap<String, OpenapiSchema>) {
let keys: Vec<String> = dependencies.keys().map(|k| k.to_string()).collect();
for dep in keys
{
for dep in keys {
let dep_schema = dependencies.swap_remove(&dep);
if let Some(dep_schema) = dep_schema
{
if let Some(dep_schema) = dep_schema {
self.add_schema_impl(dep, dep_schema);
}
}
}
pub fn add_schema<T : OpenapiType>(&mut self) -> ReferenceOr<Schema>
{
pub fn add_schema<T: OpenapiType>(&mut self) -> ReferenceOr<Schema> {
let mut schema = T::schema();
match schema.name.clone() {
Some(name) => {
let reference = Reference { reference: format!("#/components/schemas/{}", name) };
let reference = Reference {
reference: format!("#/components/schemas/{}", name)
};
self.add_schema_impl(name, schema);
reference
},
@ -104,27 +101,22 @@ impl OpenapiBuilder
}
}
#[cfg(test)]
#[allow(dead_code)]
mod test
{
mod test {
use super::*;
#[derive(OpenapiType)]
struct Message
{
struct Message {
msg: String
}
#[derive(OpenapiType)]
struct Messages
{
struct Messages {
msgs: Vec<Message>
}
fn info() -> OpenapiInfo
{
fn info() -> OpenapiInfo {
OpenapiInfo {
title: "TEST CASE".to_owned(),
version: "1.2.3".to_owned(),
@ -132,14 +124,12 @@ mod test
}
}
fn openapi(builder : OpenapiBuilder) -> OpenAPI
{
fn openapi(builder: OpenapiBuilder) -> OpenAPI {
Arc::try_unwrap(builder.openapi).unwrap().into_inner().unwrap()
}
#[test]
fn new_builder()
{
fn new_builder() {
let info = info();
let builder = OpenapiBuilder::new(info.clone());
let openapi = openapi(builder);
@ -150,13 +140,18 @@ mod test
}
#[test]
fn add_schema()
{
fn add_schema() {
let mut builder = OpenapiBuilder::new(info());
builder.add_schema::<Option<Messages>>();
let openapi = openapi(builder);
assert_eq!(openapi.components.clone().unwrap_or_default().schemas["Message"] , ReferenceOr::Item(Message ::schema().into_schema()));
assert_eq!(openapi.components.clone().unwrap_or_default().schemas["Messages"], ReferenceOr::Item(Messages::schema().into_schema()));
assert_eq!(
openapi.components.clone().unwrap_or_default().schemas["Message"],
ReferenceOr::Item(Message::schema().into_schema())
);
assert_eq!(
openapi.components.clone().unwrap_or_default().schemas["Messages"],
ReferenceOr::Item(Messages::schema().into_schema())
);
}
}

View file

@ -15,32 +15,26 @@ use std::{
};
#[derive(Clone)]
pub struct OpenapiHandler
{
pub struct OpenapiHandler {
openapi: Arc<RwLock<OpenAPI>>
}
impl OpenapiHandler
{
pub fn new(openapi : Arc<RwLock<OpenAPI>>) -> Self
{
impl OpenapiHandler {
pub fn new(openapi: Arc<RwLock<OpenAPI>>) -> Self {
Self { openapi }
}
}
impl NewHandler for OpenapiHandler
{
impl NewHandler for OpenapiHandler {
type Instance = Self;
fn new_handler(&self) -> Result<Self>
{
fn new_handler(&self) -> Result<Self> {
Ok(self.clone())
}
}
#[cfg(feature = "auth")]
fn get_security(state : &mut State) -> IndexMap<String, ReferenceOr<SecurityScheme>>
{
fn get_security(state: &mut State) -> IndexMap<String, ReferenceOr<SecurityScheme>> {
use crate::AuthSource;
use gotham::state::FromState;
@ -71,21 +65,18 @@ fn get_security(state : &mut State) -> IndexMap<String, ReferenceOr<SecuritySche
}
#[cfg(not(feature = "auth"))]
fn get_security(state : &mut State) -> (Vec<SecurityRequirement>, IndexMap<String, ReferenceOr<SecurityScheme>>)
{
fn get_security(state: &mut State) -> (Vec<SecurityRequirement>, IndexMap<String, ReferenceOr<SecurityScheme>>) {
Default::default()
}
impl Handler for OpenapiHandler
{
fn handle(self, mut state : State) -> Pin<Box<HandlerFuture>>
{
impl Handler for OpenapiHandler {
fn handle(self, mut state: State) -> Pin<Box<HandlerFuture>> {
let openapi = match self.openapi.read() {
Ok(openapi) => openapi,
Err(e) => {
error!("Unable to acquire read lock for the OpenAPI specification: {}", e);
let res = create_response(&state, crate::StatusCode::INTERNAL_SERVER_ERROR, TEXT_PLAIN, "");
return future::ok((state, res)).boxed()
return future::ok((state, res)).boxed();
}
};

View file

@ -1,4 +1,3 @@
const SECURITY_NAME: &str = "authToken";
pub mod builder;

View file

@ -1,32 +1,21 @@
use crate::{
resource::*,
result::*,
OpenapiSchema,
RequestBody
};
use super::SECURITY_NAME;
use crate::{resource::*, result::*, OpenapiSchema, RequestBody};
use indexmap::IndexMap;
use mime::Mime;
use openapiv3::{
MediaType, Operation, Parameter, ParameterData, ParameterSchemaOrContent, ReferenceOr,
ReferenceOr::Item, RequestBody as OARequestBody, Response, Responses, Schema, SchemaKind,
StatusCode, Type
MediaType, Operation, Parameter, ParameterData, ParameterSchemaOrContent, ReferenceOr, ReferenceOr::Item,
RequestBody as OARequestBody, Response, Responses, Schema, SchemaKind, StatusCode, Type
};
#[derive(Default)]
struct OperationParams<'a>
{
struct OperationParams<'a> {
path_params: Vec<(&'a str, ReferenceOr<Schema>)>,
query_params: Option<OpenapiSchema>
}
impl<'a> OperationParams<'a>
{
fn add_path_params(&self, params : &mut Vec<ReferenceOr<Parameter>>)
{
for param in &self.path_params
{
impl<'a> OperationParams<'a> {
fn add_path_params(&self, params: &mut Vec<ReferenceOr<Parameter>>) {
for param in &self.path_params {
params.push(Item(Parameter::Path {
parameter_data: ParameterData {
name: (*param).0.to_string(),
@ -37,13 +26,12 @@ impl<'a> OperationParams<'a>
example: None,
examples: IndexMap::new()
},
style: Default::default(),
style: Default::default()
}));
}
}
fn add_query_params(self, params : &mut Vec<ReferenceOr<Parameter>>)
{
fn add_query_params(self, params: &mut Vec<ReferenceOr<Parameter>>) {
let query_params = match self.query_params {
Some(qp) => qp.schema,
None => return
@ -52,8 +40,7 @@ impl<'a> OperationParams<'a>
SchemaKind::Type(Type::Object(ty)) => ty,
_ => panic!("Query Parameters needs to be a plain struct")
};
for (name, schema) in query_params.properties
{
for (name, schema) in query_params.properties {
let required = query_params.required.contains(&name);
params.push(Item(Parameter::Query {
parameter_data: ParameterData {
@ -72,8 +59,7 @@ impl<'a> OperationParams<'a>
}
}
fn into_params(self) -> Vec<ReferenceOr<Parameter>>
{
fn into_params(self) -> Vec<ReferenceOr<Parameter>> {
let mut params: Vec<ReferenceOr<Parameter>> = Vec::new();
self.add_path_params(&mut params);
self.add_query_params(&mut params);
@ -81,8 +67,7 @@ impl<'a> OperationParams<'a>
}
}
pub struct OperationDescription<'a>
{
pub struct OperationDescription<'a> {
operation_id: Option<String>,
default_status: crate::StatusCode,
accepted_types: Option<Vec<Mime>>,
@ -93,10 +78,8 @@ pub struct OperationDescription<'a>
requires_auth: bool
}
impl<'a> OperationDescription<'a>
{
pub fn new<Handler : ResourceMethod>(schema : ReferenceOr<Schema>) -> Self
{
impl<'a> OperationDescription<'a> {
pub fn new<Handler: ResourceMethod>(schema: ReferenceOr<Schema>) -> Self {
Self {
operation_id: Handler::operation_id(),
default_status: Handler::Res::default_status(),
@ -109,31 +92,25 @@ impl<'a> OperationDescription<'a>
}
}
pub fn add_path_param(mut self, name : &'a str, schema : ReferenceOr<Schema>) -> Self
{
pub fn add_path_param(mut self, name: &'a str, schema: ReferenceOr<Schema>) -> Self {
self.params.path_params.push((name, schema));
self
}
pub fn with_query_params(mut self, params : OpenapiSchema) -> Self
{
pub fn with_query_params(mut self, params: OpenapiSchema) -> Self {
self.params.query_params = Some(params);
self
}
pub fn with_body<Body : RequestBody>(mut self, schema : ReferenceOr<Schema>) -> Self
{
pub fn with_body<Body: RequestBody>(mut self, schema: ReferenceOr<Schema>) -> Self {
self.body_schema = Some(schema);
self.supported_types = Body::supported_types();
self
}
fn schema_to_content(types : Vec<Mime>, schema : ReferenceOr<Schema>) -> IndexMap<String, MediaType>
{
fn schema_to_content(types: Vec<Mime>, schema: ReferenceOr<Schema>) -> IndexMap<String, MediaType> {
let mut content: IndexMap<String, MediaType> = IndexMap::new();
for ty in types
{
for ty in types {
content.insert(ty.to_string(), MediaType {
schema: Some(schema.clone()),
..Default::default()
@ -142,30 +119,41 @@ impl<'a> OperationDescription<'a>
content
}
pub fn into_operation(self) -> Operation
{
pub fn into_operation(self) -> Operation {
// this is unfortunately neccessary to prevent rust from complaining about partially moving self
let (operation_id, default_status, accepted_types, schema, params, body_schema, supported_types, requires_auth) = (
self.operation_id, self.default_status, self.accepted_types, self.schema, self.params, self.body_schema, self.supported_types, self.requires_auth);
self.operation_id,
self.default_status,
self.accepted_types,
self.schema,
self.params,
self.body_schema,
self.supported_types,
self.requires_auth
);
let content = Self::schema_to_content(accepted_types.or_all_types(), schema);
let mut responses: IndexMap<StatusCode, ReferenceOr<Response>> = IndexMap::new();
responses.insert(StatusCode::Code(default_status.as_u16()), Item(Response {
responses.insert(
StatusCode::Code(default_status.as_u16()),
Item(Response {
description: default_status.canonical_reason().map(|d| d.to_string()).unwrap_or_default(),
content,
..Default::default()
}));
})
);
let request_body = body_schema.map(|schema| Item(OARequestBody {
let request_body = body_schema.map(|schema| {
Item(OARequestBody {
description: None,
content: Self::schema_to_content(supported_types.or_all_types(), schema),
required: true
}));
})
});
let mut security = Vec::new();
if requires_auth
{
if requires_auth {
let mut sec = IndexMap::new();
sec.insert(SECURITY_NAME.to_owned(), Vec::new());
security.push(sec);
@ -187,16 +175,13 @@ impl<'a> OperationDescription<'a>
}
}
#[cfg(test)]
mod test
{
use crate::{OpenapiType, ResourceResult};
mod test {
use super::*;
use crate::{OpenapiType, ResourceResult};
#[test]
fn no_content_schema_to_content()
{
fn no_content_schema_to_content() {
let types = NoContent::accepted_types();
let schema = <NoContent as OpenapiType>::schema();
let content = OperationDescription::schema_to_content(types.or_all_types(), Item(schema.into_schema()));
@ -204,8 +189,7 @@ mod test
}
#[test]
fn raw_schema_to_content()
{
fn raw_schema_to_content() {
let types = Raw::<&str>::accepted_types();
let schema = <Raw<&str> as OpenapiType>::schema();
let content = OperationDescription::schema_to_content(types.or_all_types(), Item(schema.into_schema()));

View file

@ -1,24 +1,15 @@
use crate::{
resource::*,
routing::*,
OpenapiType,
};
use super::{builder::OpenapiBuilder, handler::OpenapiHandler, operation::OperationDescription};
use gotham::{
pipeline::chain::PipelineHandleChain,
router::builder::*
};
use crate::{resource::*, routing::*, OpenapiType};
use gotham::{pipeline::chain::PipelineHandleChain, router::builder::*};
use std::panic::RefUnwindSafe;
/// This trait adds the `get_openapi` method to an OpenAPI-aware router.
pub trait GetOpenapi
{
pub trait GetOpenapi {
fn get_openapi(&mut self, path: &str);
}
#[derive(Debug)]
pub struct OpenapiRouter<'a, D>
{
pub struct OpenapiRouter<'a, D> {
pub(crate) router: &'a mut D,
pub(crate) scope: Option<&'a str>,
pub(crate) openapi_builder: &'a mut OpenapiBuilder
@ -26,7 +17,6 @@ pub struct OpenapiRouter<'a, D>
macro_rules! implOpenapiRouter {
($implType:ident) => {
impl<'a, 'b, C, P> OpenapiRouter<'a, $implType<'b, C, P>>
where
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
@ -54,9 +44,10 @@ macro_rules! implOpenapiRouter {
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static
{
fn get_openapi(&mut self, path : &str)
{
self.router.get(path).to_new_handler(OpenapiHandler::new(self.openapi_builder.openapi.clone()));
fn get_openapi(&mut self, path: &str) {
self.router
.get(path)
.to_new_handler(OpenapiHandler::new(self.openapi_builder.openapi.clone()));
}
}
@ -65,8 +56,7 @@ macro_rules! implOpenapiRouter {
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static
{
fn resource<R : Resource>(&mut self, path : &str)
{
fn resource<R: Resource>(&mut self, path: &str) {
R::setup((self, path));
}
}
@ -76,8 +66,7 @@ macro_rules! implOpenapiRouter {
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static
{
fn read_all<Handler : ResourceReadAll>(&mut self)
{
fn read_all<Handler: ResourceReadAll>(&mut self) {
let schema = (self.0).openapi_builder.add_schema::<Handler::Res>();
let path = format!("{}/{}", self.0.scope.unwrap_or_default(), self.1);
@ -88,26 +77,32 @@ macro_rules! implOpenapiRouter {
(&mut *(self.0).router, self.1).read_all::<Handler>()
}
fn read<Handler : ResourceRead>(&mut self)
{
fn read<Handler: ResourceRead>(&mut self) {
let schema = (self.0).openapi_builder.add_schema::<Handler::Res>();
let id_schema = (self.0).openapi_builder.add_schema::<Handler::ID>();
let path = format!("{}/{}/{{id}}", self.0.scope.unwrap_or_default(), self.1);
let mut item = (self.0).openapi_builder.remove_path(&path);
item.get = Some(OperationDescription::new::<Handler>(schema).add_path_param("id", id_schema).into_operation());
item.get = Some(
OperationDescription::new::<Handler>(schema)
.add_path_param("id", id_schema)
.into_operation()
);
(self.0).openapi_builder.add_path(path, item);
(&mut *(self.0).router, self.1).read::<Handler>()
}
fn search<Handler : ResourceSearch>(&mut self)
{
fn search<Handler: ResourceSearch>(&mut self) {
let schema = (self.0).openapi_builder.add_schema::<Handler::Res>();
let path = format!("{}/{}/search", self.0.scope.unwrap_or_default(), self.1);
let mut item = (self.0).openapi_builder.remove_path(&path);
item.get = Some(OperationDescription::new::<Handler>(schema).with_query_params(Handler::Query::schema()).into_operation());
item.get = Some(
OperationDescription::new::<Handler>(schema)
.with_query_params(Handler::Query::schema())
.into_operation()
);
(self.0).openapi_builder.add_path(path, item);
(&mut *(self.0).router, self.1).search::<Handler>()
@ -123,7 +118,11 @@ macro_rules! implOpenapiRouter {
let path = format!("{}/{}", self.0.scope.unwrap_or_default(), self.1);
let mut item = (self.0).openapi_builder.remove_path(&path);
item.post = Some(OperationDescription::new::<Handler>(schema).with_body::<Handler::Body>(body_schema).into_operation());
item.post = Some(
OperationDescription::new::<Handler>(schema)
.with_body::<Handler::Body>(body_schema)
.into_operation()
);
(self.0).openapi_builder.add_path(path, item);
(&mut *(self.0).router, self.1).create::<Handler>()
@ -139,7 +138,11 @@ macro_rules! implOpenapiRouter {
let path = format!("{}/{}", self.0.scope.unwrap_or_default(), self.1);
let mut item = (self.0).openapi_builder.remove_path(&path);
item.put = Some(OperationDescription::new::<Handler>(schema).with_body::<Handler::Body>(body_schema).into_operation());
item.put = Some(
OperationDescription::new::<Handler>(schema)
.with_body::<Handler::Body>(body_schema)
.into_operation()
);
(self.0).openapi_builder.add_path(path, item);
(&mut *(self.0).router, self.1).change_all::<Handler>()
@ -156,14 +159,18 @@ macro_rules! implOpenapiRouter {
let path = format!("{}/{}/{{id}}", self.0.scope.unwrap_or_default(), self.1);
let mut item = (self.0).openapi_builder.remove_path(&path);
item.put = Some(OperationDescription::new::<Handler>(schema).add_path_param("id", id_schema).with_body::<Handler::Body>(body_schema).into_operation());
item.put = Some(
OperationDescription::new::<Handler>(schema)
.add_path_param("id", id_schema)
.with_body::<Handler::Body>(body_schema)
.into_operation()
);
(self.0).openapi_builder.add_path(path, item);
(&mut *(self.0).router, self.1).change::<Handler>()
}
fn remove_all<Handler : ResourceRemoveAll>(&mut self)
{
fn remove_all<Handler: ResourceRemoveAll>(&mut self) {
let schema = (self.0).openapi_builder.add_schema::<Handler::Res>();
let path = format!("{}/{}", self.0.scope.unwrap_or_default(), self.1);
@ -174,21 +181,23 @@ macro_rules! implOpenapiRouter {
(&mut *(self.0).router, self.1).remove_all::<Handler>()
}
fn remove<Handler : ResourceRemove>(&mut self)
{
fn remove<Handler: ResourceRemove>(&mut self) {
let schema = (self.0).openapi_builder.add_schema::<Handler::Res>();
let id_schema = (self.0).openapi_builder.add_schema::<Handler::ID>();
let path = format!("{}/{}/{{id}}", self.0.scope.unwrap_or_default(), self.1);
let mut item = (self.0).openapi_builder.remove_path(&path);
item.delete = Some(OperationDescription::new::<Handler>(schema).add_path_param("id", id_schema).into_operation());
item.delete = Some(
OperationDescription::new::<Handler>(schema)
.add_path_param("id", id_schema)
.into_operation()
);
(self.0).openapi_builder.add_path(path, item);
(&mut *(self.0).router, self.1).remove::<Handler>()
}
}
}
};
}
implOpenapiRouter!(RouterBuilder);

View file

@ -1,18 +1,17 @@
#[cfg(feature = "chrono")]
use chrono::{
Date, DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, Utc
};
use chrono::{Date, DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, Utc};
use indexmap::IndexMap;
use openapiv3::{
AdditionalProperties, ArrayType, IntegerType, NumberFormat, NumberType, ObjectType, ReferenceOr::Item,
ReferenceOr::Reference, Schema, SchemaData, SchemaKind, StringType, Type, VariantOrUnknownOrEmpty
AdditionalProperties, ArrayType, IntegerType, NumberFormat, NumberType, ObjectType,
ReferenceOr::{Item, Reference},
Schema, SchemaData, SchemaKind, StringType, Type, VariantOrUnknownOrEmpty
};
#[cfg(feature = "uuid")]
use uuid::Uuid;
use std::{
collections::{BTreeSet, HashMap, HashSet},
hash::BuildHasher
};
#[cfg(feature = "uuid")]
use uuid::Uuid;
/**
This struct needs to be available for every type that can be part of an OpenAPI Spec. It is
@ -22,8 +21,7 @@ for your type, simply derive from [`OpenapiType`].
[`OpenapiType`]: trait.OpenapiType.html
*/
#[derive(Debug, Clone, PartialEq)]
pub struct OpenapiSchema
{
pub struct OpenapiSchema {
/// The name of this schema. If it is None, the schema will be inlined.
pub name: Option<String>,
/// Whether this particular schema is nullable. Note that there is no guarantee that this will
@ -37,11 +35,9 @@ pub struct OpenapiSchema
pub dependencies: IndexMap<String, OpenapiSchema>
}
impl OpenapiSchema
{
impl OpenapiSchema {
/// Create a new schema that has no name.
pub fn new(schema : SchemaKind) -> Self
{
pub fn new(schema: SchemaKind) -> Self {
Self {
name: None,
nullable: false,
@ -51,8 +47,7 @@ impl OpenapiSchema
}
/// Convert this schema to an `openapiv3::Schema` that can be serialized to the OpenAPI Spec.
pub fn into_schema(self) -> Schema
{
pub fn into_schema(self) -> Schema {
Schema {
schema_data: SchemaData {
nullable: self.nullable,
@ -80,15 +75,12 @@ struct MyResponse {
[`OpenapiSchema`]: struct.OpenapiSchema.html
*/
pub trait OpenapiType
{
pub trait OpenapiType {
fn schema() -> OpenapiSchema;
}
impl OpenapiType for ()
{
fn schema() -> OpenapiSchema
{
impl OpenapiType for () {
fn schema() -> OpenapiSchema {
OpenapiSchema::new(SchemaKind::Type(Type::Object(ObjectType {
additional_properties: Some(AdditionalProperties::Any(false)),
..Default::default()
@ -96,10 +88,8 @@ impl OpenapiType for ()
}
}
impl OpenapiType for bool
{
fn schema() -> OpenapiSchema
{
impl OpenapiType for bool {
fn schema() -> OpenapiSchema {
OpenapiSchema::new(SchemaKind::Type(Type::Boolean {}))
}
}
@ -231,20 +221,26 @@ str_types!(String, &str);
#[cfg(feature = "chrono")]
str_types!(format = Date, Date<FixedOffset>, Date<Local>, Date<Utc>, NaiveDate);
#[cfg(feature = "chrono")]
str_types!(format = DateTime, DateTime<FixedOffset>, DateTime<Local>, DateTime<Utc>, NaiveDateTime);
str_types!(
format = DateTime,
DateTime<FixedOffset>,
DateTime<Local>,
DateTime<Utc>,
NaiveDateTime
);
#[cfg(feature = "uuid")]
str_types!(format_str = "uuid", Uuid);
impl<T : OpenapiType> OpenapiType for Option<T>
{
fn schema() -> OpenapiSchema
{
impl<T: OpenapiType> OpenapiType for Option<T> {
fn schema() -> OpenapiSchema {
let schema = T::schema();
let mut dependencies = schema.dependencies.clone();
let schema = match schema.name.clone() {
Some(name) => {
let reference = Reference { reference: format!("#/components/schemas/{}", name) };
let reference = Reference {
reference: format!("#/components/schemas/{}", name)
};
dependencies.insert(name, schema);
SchemaKind::AllOf { all_of: vec![reference] }
},
@ -260,16 +256,16 @@ impl<T : OpenapiType> OpenapiType for Option<T>
}
}
impl<T : OpenapiType> OpenapiType for Vec<T>
{
fn schema() -> OpenapiSchema
{
impl<T: OpenapiType> OpenapiType for Vec<T> {
fn schema() -> OpenapiSchema {
let schema = T::schema();
let mut dependencies = schema.dependencies.clone();
let items = match schema.name.clone() {
Some(name) => {
let reference = Reference { reference: format!("#/components/schemas/{}", name) };
let reference = Reference {
reference: format!("#/components/schemas/{}", name)
};
dependencies.insert(name, schema);
reference
},
@ -290,32 +286,28 @@ impl<T : OpenapiType> OpenapiType for Vec<T>
}
}
impl<T : OpenapiType> OpenapiType for BTreeSet<T>
{
fn schema() -> OpenapiSchema
{
impl<T: OpenapiType> OpenapiType for BTreeSet<T> {
fn schema() -> OpenapiSchema {
<Vec<T> as OpenapiType>::schema()
}
}
impl<T : OpenapiType, S : BuildHasher> OpenapiType for HashSet<T, S>
{
fn schema() -> OpenapiSchema
{
impl<T: OpenapiType, S: BuildHasher> OpenapiType for HashSet<T, S> {
fn schema() -> OpenapiSchema {
<Vec<T> as OpenapiType>::schema()
}
}
impl<K, T : OpenapiType, S : BuildHasher> OpenapiType for HashMap<K, T, S>
{
fn schema() -> OpenapiSchema
{
impl<K, T: OpenapiType, S: BuildHasher> OpenapiType for HashMap<K, T, S> {
fn schema() -> OpenapiSchema {
let schema = T::schema();
let mut dependencies = schema.dependencies.clone();
let items = Box::new(match schema.name.clone() {
Some(name) => {
let reference = Reference { reference: format!("#/components/schemas/{}", name) };
let reference = Reference {
reference: format!("#/components/schemas/{}", name)
};
dependencies.insert(name, schema);
reference
},
@ -334,10 +326,8 @@ impl<K, T : OpenapiType, S : BuildHasher> OpenapiType for HashMap<K, T, S>
}
}
impl OpenapiType for serde_json::Value
{
fn schema() -> OpenapiSchema
{
impl OpenapiType for serde_json::Value {
fn schema() -> OpenapiSchema {
OpenapiSchema {
nullable: true,
name: None,
@ -347,10 +337,8 @@ impl OpenapiType for serde_json::Value
}
}
#[cfg(test)]
mod test
{
mod test {
use super::*;
use serde_json::Value;

View file

@ -1,20 +1,12 @@
use crate::{DrawResourceRoutes, RequestBody, ResourceID, ResourceResult, ResourceType};
use gotham::{
extractor::QueryStringExtractor,
hyper::Body,
state::State
};
use std::{
future::Future,
pin::Pin
};
use gotham::{extractor::QueryStringExtractor, hyper::Body, state::State};
use std::{future::Future, pin::Pin};
/// This trait must be implemented for every resource. It allows you to register the different
/// methods that can be handled by this resource to be registered with the underlying router.
///
/// It is not recommended to implement this yourself, rather just use `#[derive(Resource)]`.
pub trait Resource
{
pub trait Resource {
/// Register all methods handled by this resource with the underlying router.
fn setup<D: DrawResourceRoutes>(route: D);
}
@ -25,32 +17,27 @@ pub trait Resource
/// It is not recommended to implement this yourself. Rather, just write your handler method and
/// annotate it with `#[<method>(YourResource)]`, where `<method>` is one of the supported
/// resource methods.
pub trait ResourceMethod
{
pub trait ResourceMethod {
type Res: ResourceResult + Send + 'static;
#[cfg(feature = "openapi")]
fn operation_id() -> Option<String>
{
fn operation_id() -> Option<String> {
None
}
fn wants_auth() -> bool
{
fn wants_auth() -> bool {
false
}
}
/// The read_all [`ResourceMethod`](trait.ResourceMethod.html).
pub trait ResourceReadAll : ResourceMethod
{
pub trait ResourceReadAll: ResourceMethod {
/// Handle a GET request on the Resource root.
fn read_all(state: State) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
}
/// The read [`ResourceMethod`](trait.ResourceMethod.html).
pub trait ResourceRead : ResourceMethod
{
pub trait ResourceRead: ResourceMethod {
/// The ID type to be parsed from the request path.
type ID: ResourceID + 'static;
@ -59,8 +46,7 @@ pub trait ResourceRead : ResourceMethod
}
/// The search [`ResourceMethod`](trait.ResourceMethod.html).
pub trait ResourceSearch : ResourceMethod
{
pub trait ResourceSearch: ResourceMethod {
/// The Query type to be parsed from the request parameters.
type Query: ResourceType + QueryStringExtractor<Body> + Sync;
@ -69,8 +55,7 @@ pub trait ResourceSearch : ResourceMethod
}
/// The create [`ResourceMethod`](trait.ResourceMethod.html).
pub trait ResourceCreate : ResourceMethod
{
pub trait ResourceCreate: ResourceMethod {
/// The Body type to be parsed from the request body.
type Body: RequestBody;
@ -79,8 +64,7 @@ pub trait ResourceCreate : ResourceMethod
}
/// The change_all [`ResourceMethod`](trait.ResourceMethod.html).
pub trait ResourceChangeAll : ResourceMethod
{
pub trait ResourceChangeAll: ResourceMethod {
/// The Body type to be parsed from the request body.
type Body: RequestBody;
@ -89,8 +73,7 @@ pub trait ResourceChangeAll : ResourceMethod
}
/// The change [`ResourceMethod`](trait.ResourceMethod.html).
pub trait ResourceChange : ResourceMethod
{
pub trait ResourceChange: ResourceMethod {
/// The Body type to be parsed from the request body.
type Body: RequestBody;
/// The ID type to be parsed from the request path.
@ -101,15 +84,13 @@ pub trait ResourceChange : ResourceMethod
}
/// The remove_all [`ResourceMethod`](trait.ResourceMethod.html).
pub trait ResourceRemoveAll : ResourceMethod
{
pub trait ResourceRemoveAll: ResourceMethod {
/// Handle a DELETE request on the Resource root.
fn remove_all(state: State) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
}
/// The remove [`ResourceMethod`](trait.ResourceMethod.html).
pub trait ResourceRemove : ResourceMethod
{
pub trait ResourceRemove: ResourceMethod {
/// The ID type to be parsed from the request path.
type ID: ResourceID + 'static;

View file

@ -3,18 +3,15 @@ use mime::{Mime, APPLICATION_JSON};
/// A response, used to create the final gotham response from.
#[derive(Debug)]
pub struct Response
{
pub struct Response {
pub status: StatusCode,
pub body: Body,
pub mime: Option<Mime>
}
impl Response
{
impl Response {
/// Create a new `Response` from raw data.
pub fn new<B : Into<Body>>(status : StatusCode, body : B, mime : Option<Mime>) -> Self
{
pub fn new<B: Into<Body>>(status: StatusCode, body: B, mime: Option<Mime>) -> Self {
Self {
status,
body: body.into(),
@ -23,8 +20,7 @@ impl Response
}
/// Create a `Response` with mime type json from already serialized data.
pub fn json<B : Into<Body>>(status : StatusCode, body : B) -> Self
{
pub fn json<B: Into<Body>>(status: StatusCode, body: B) -> Self {
Self {
status,
body: body.into(),
@ -33,8 +29,7 @@ impl Response
}
/// Create a _204 No Content_ `Response`.
pub fn no_content() -> Self
{
pub fn no_content() -> Self {
Self {
status: StatusCode::NO_CONTENT,
body: Body::empty(),
@ -43,8 +38,7 @@ impl Response
}
/// Create an empty _403 Forbidden_ `Response`.
pub fn forbidden() -> Self
{
pub fn forbidden() -> Self {
Self {
status: StatusCode::FORBIDDEN,
body: Body::empty(),
@ -53,8 +47,7 @@ impl Response
}
#[cfg(test)]
pub(crate) fn full_body(mut self) -> Result<Vec<u8>, <Body as gotham::hyper::body::HttpBody>::Error>
{
pub(crate) fn full_body(mut self) -> Result<Vec<u8>, <Body as gotham::hyper::body::HttpBody>::Error> {
use futures_executor::block_on;
use gotham::hyper::body::to_bytes;

View file

@ -1,6 +1,5 @@
use gotham_restful_derive::ResourceError;
/**
This is an error type that always yields a _403 Forbidden_ response. This type is best used in
combination with [`AuthSuccess`] or [`AuthResult`].
@ -9,8 +8,7 @@ combination with [`AuthSuccess`] or [`AuthResult`].
[`AuthResult`]: type.AuthResult.html
*/
#[derive(Debug, Clone, Copy, ResourceError)]
pub enum AuthError
{
pub enum AuthError {
#[status(FORBIDDEN)]
#[display("Forbidden")]
Forbidden
@ -57,8 +55,7 @@ error, or delegates to another error type. This type is best used with [`AuthRes
[`AuthResult`]: type.AuthResult.html
*/
#[derive(Debug, ResourceError)]
pub enum AuthErrorOrOther<E>
{
pub enum AuthErrorOrOther<E> {
#[status(FORBIDDEN)]
#[display("Forbidden")]
Forbidden,
@ -67,10 +64,8 @@ pub enum AuthErrorOrOther<E>
Other(E)
}
impl<E> From<AuthError> for AuthErrorOrOther<E>
{
fn from(err : AuthError) -> Self
{
impl<E> From<AuthError> for AuthErrorOrOther<E> {
fn from(err: AuthError) -> Self {
match err {
AuthError::Forbidden => Self::Forbidden
}
@ -82,8 +77,7 @@ where
// TODO https://gitlab.com/msrd0/gotham-restful/-/issues/20
F: std::error::Error + Into<E>
{
fn from(err : F) -> Self
{
fn from(err: F) -> Self {
Self::Other(err.into())
}
}

View file

@ -1,13 +1,13 @@
use crate::Response;
#[cfg(feature = "openapi")]
use crate::OpenapiSchema;
use crate::Response;
use futures_util::future::FutureExt;
use mime::{Mime, STAR_STAR};
use serde::Serialize;
use std::{
error::Error,
future::Future,
fmt::{Debug, Display},
future::Future,
pin::Pin
};
@ -27,33 +27,26 @@ pub use result::IntoResponseError;
mod success;
pub use success::Success;
pub(crate) trait OrAllTypes
{
pub(crate) trait OrAllTypes {
fn or_all_types(self) -> Vec<Mime>;
}
impl OrAllTypes for Option<Vec<Mime>>
{
fn or_all_types(self) -> Vec<Mime>
{
impl OrAllTypes for Option<Vec<Mime>> {
fn or_all_types(self) -> Vec<Mime> {
self.unwrap_or_else(|| vec![STAR_STAR])
}
}
/// A trait provided to convert a resource's result to json.
pub trait ResourceResult
{
type Err : Error + Send + 'static;
pub trait ResourceResult {
type Err: Error + Send + Sync + 'static;
/// Turn this into a response that can be returned to the browser. This api will likely
/// change in the future.
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>>;
/// Return a list of supported mime types.
fn accepted_types() -> Option<Vec<Mime>>
{
fn accepted_types() -> Option<Vec<Mime>> {
None
}
@ -61,33 +54,27 @@ pub trait ResourceResult
fn schema() -> OpenapiSchema;
#[cfg(feature = "openapi")]
fn default_status() -> crate::StatusCode
{
fn default_status() -> crate::StatusCode {
crate::StatusCode::OK
}
}
#[cfg(feature = "openapi")]
impl<Res : ResourceResult> crate::OpenapiType for Res
{
fn schema() -> OpenapiSchema
{
impl<Res: ResourceResult> crate::OpenapiType for Res {
fn schema() -> OpenapiSchema {
Self::schema()
}
}
/// The default json returned on an 500 Internal Server Error.
#[derive(Debug, Serialize)]
pub(crate) struct ResourceError
{
pub(crate) struct ResourceError {
error: bool,
message: String
}
impl<T : ToString> From<T> for ResourceError
{
fn from(message : T) -> Self
{
impl<T: ToString> From<T> for ResourceError {
fn from(message: T) -> Self {
Self {
error: true,
message: message.to_string()
@ -105,8 +92,7 @@ where
}
#[cfg(feature = "errorlog")]
fn errorlog<E : Display>(e : E)
{
fn errorlog<E: Display>(e: E) {
error!("The handler encountered an error: {}", e);
}
@ -123,51 +109,40 @@ where
})
}
impl<Res> ResourceResult for Pin<Box<dyn Future<Output = Res> + Send>>
where
Res: ResourceResult + 'static
{
type Err = Res::Err;
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>>
{
self.then(|result| {
result.into_response()
}).boxed()
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>> {
self.then(|result| result.into_response()).boxed()
}
fn accepted_types() -> Option<Vec<Mime>>
{
fn accepted_types() -> Option<Vec<Mime>> {
Res::accepted_types()
}
#[cfg(feature = "openapi")]
fn schema() -> OpenapiSchema
{
fn schema() -> OpenapiSchema {
Res::schema()
}
#[cfg(feature = "openapi")]
fn default_status() -> crate::StatusCode
{
fn default_status() -> crate::StatusCode {
Res::default_status()
}
}
#[cfg(test)]
mod test
{
mod test {
use super::*;
use futures_executor::block_on;
use thiserror::Error;
#[derive(Debug, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "openapi", derive(crate::OpenapiType))]
struct Msg
{
struct Msg {
msg: String
}
@ -176,8 +151,7 @@ mod test
struct MsgError;
#[test]
fn result_from_future()
{
fn result_from_future() {
let nc = NoContent::default();
let res = block_on(nc.into_response()).unwrap();

View file

@ -1,14 +1,10 @@
use super::{ResourceResult, handle_error};
use super::{handle_error, ResourceResult};
use crate::{IntoResponseError, Response};
#[cfg(feature = "openapi")]
use crate::{OpenapiSchema, OpenapiType};
use futures_util::{future, future::FutureExt};
use mime::Mime;
use std::{
fmt::Display,
future::Future,
pin::Pin
};
use std::{fmt::Display, future::Future, pin::Pin};
/**
This is the return type of a resource that doesn't actually return something. It will result
@ -35,41 +31,34 @@ fn read_all(_state: &mut State) {
#[derive(Clone, Copy, Debug, Default)]
pub struct NoContent;
impl From<()> for NoContent
{
fn from(_ : ()) -> Self
{
impl From<()> for NoContent {
fn from(_: ()) -> Self {
Self {}
}
}
impl ResourceResult for NoContent
{
impl ResourceResult for NoContent {
// TODO this shouldn't be a serde_json::Error
type Err = serde_json::Error; // just for easier handling of `Result<NoContent, E>`
/// This will always be a _204 No Content_ together with an empty string.
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>>
{
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>> {
future::ok(Response::no_content()).boxed()
}
fn accepted_types() -> Option<Vec<Mime>>
{
fn accepted_types() -> Option<Vec<Mime>> {
Some(Vec::new())
}
/// Returns the schema of the `()` type.
#[cfg(feature = "openapi")]
fn schema() -> OpenapiSchema
{
fn schema() -> OpenapiSchema {
<()>::schema()
}
/// This will always be a _204 No Content_
#[cfg(feature = "openapi")]
fn default_status() -> crate::StatusCode
{
fn default_status() -> crate::StatusCode {
crate::StatusCode::NO_CONTENT
}
}
@ -80,36 +69,30 @@ where
{
type Err = serde_json::Error;
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, serde_json::Error>> + Send>>
{
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, serde_json::Error>> + Send>> {
match self {
Ok(nc) => nc.into_response(),
Err(e) => handle_error(e)
}
}
fn accepted_types() -> Option<Vec<Mime>>
{
fn accepted_types() -> Option<Vec<Mime>> {
NoContent::accepted_types()
}
#[cfg(feature = "openapi")]
fn schema() -> OpenapiSchema
{
fn schema() -> OpenapiSchema {
<NoContent as ResourceResult>::schema()
}
#[cfg(feature = "openapi")]
fn default_status() -> crate::StatusCode
{
fn default_status() -> crate::StatusCode {
NoContent::default_status()
}
}
#[cfg(test)]
mod test
{
mod test {
use super::*;
use futures_executor::block_on;
use gotham::hyper::StatusCode;
@ -120,8 +103,7 @@ mod test
struct MsgError;
#[test]
fn no_content_has_empty_response()
{
fn no_content_has_empty_response() {
let no_content = NoContent::default();
let res = block_on(no_content.into_response()).expect("didn't expect error response");
assert_eq!(res.status, StatusCode::NO_CONTENT);
@ -130,8 +112,7 @@ mod test
}
#[test]
fn no_content_result()
{
fn no_content_result() {
let no_content: Result<NoContent, MsgError> = Ok(NoContent::default());
let res = block_on(no_content.into_response()).expect("didn't expect error response");
assert_eq!(res.status, StatusCode::NO_CONTENT);

View file

@ -1,7 +1,7 @@
use super::{IntoResponseError, ResourceResult, handle_error};
use crate::{FromBody, RequestBody, ResourceType, Response, StatusCode};
use super::{handle_error, IntoResponseError, ResourceResult};
#[cfg(feature = "openapi")]
use crate::OpenapiSchema;
use crate::{FromBody, RequestBody, ResourceType, Response, StatusCode};
use futures_core::future::Future;
use futures_util::{future, future::FutureExt};
use gotham::hyper::body::{Body, Bytes};
@ -9,11 +9,7 @@ use mime::Mime;
#[cfg(feature = "openapi")]
use openapiv3::{SchemaKind, StringFormat, StringType, Type, VariantOrUnknownOrEmpty};
use serde_json::error::Error as SerdeJsonError;
use std::{
convert::Infallible,
fmt::Display,
pin::Pin
};
use std::{convert::Infallible, fmt::Display, pin::Pin};
/**
This type can be used both as a raw request body, as well as as a raw response. However, all types
@ -43,16 +39,13 @@ fn create(body : Raw<Vec<u8>>) -> Raw<Vec<u8>> {
[`OpenapiType`]: trait.OpenapiType.html
*/
#[derive(Debug)]
pub struct Raw<T>
{
pub struct Raw<T> {
pub raw: T,
pub mime: Mime
}
impl<T> Raw<T>
{
pub fn new(raw : T, mime : Mime) -> Self
{
impl<T> Raw<T> {
pub fn new(raw: T, mime: Mime) -> Self {
Self { raw, mime }
}
}
@ -61,8 +54,7 @@ impl<T, U> AsMut<U> for Raw<T>
where
T: AsMut<U>
{
fn as_mut(&mut self) -> &mut U
{
fn as_mut(&mut self) -> &mut U {
self.raw.as_mut()
}
}
@ -71,16 +63,13 @@ impl<T, U> AsRef<U> for Raw<T>
where
T: AsRef<U>
{
fn as_ref(&self) -> &U
{
fn as_ref(&self) -> &U {
self.raw.as_ref()
}
}
impl<T : Clone> Clone for Raw<T>
{
fn clone(&self) -> Self
{
impl<T: Clone> Clone for Raw<T> {
fn clone(&self) -> Self {
Self {
raw: self.raw.clone(),
mime: self.mime.clone()
@ -88,21 +77,15 @@ impl<T : Clone> Clone for Raw<T>
}
}
impl<T : for<'a> From<&'a [u8]>> FromBody for Raw<T>
{
impl<T: for<'a> From<&'a [u8]>> FromBody for Raw<T> {
type Err = Infallible;
fn from_body(body : Bytes, mime : Mime) -> Result<Self, Self::Err>
{
fn from_body(body: Bytes, mime: Mime) -> Result<Self, Self::Err> {
Ok(Self::new(body.as_ref().into(), mime))
}
}
impl<T> RequestBody for Raw<T>
where
Raw<T> : FromBody + ResourceType
{
}
impl<T> RequestBody for Raw<T> where Raw<T>: FromBody + ResourceType {}
impl<T: Into<Body>> ResourceResult for Raw<T>
where
@ -110,14 +93,12 @@ where
{
type Err = SerdeJsonError; // just for easier handling of `Result<Raw<T>, E>`
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, SerdeJsonError>> + Send>>
{
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, SerdeJsonError>> + Send>> {
future::ok(Response::new(StatusCode::OK, self.raw, Some(self.mime.clone()))).boxed()
}
#[cfg(feature = "openapi")]
fn schema() -> OpenapiSchema
{
fn schema() -> OpenapiSchema {
OpenapiSchema::new(SchemaKind::Type(Type::String(StringType {
format: VariantOrUnknownOrEmpty::Item(StringFormat::Binary),
..Default::default()
@ -132,8 +113,7 @@ where
{
type Err = E::Err;
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>>
{
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>> {
match self {
Ok(raw) => raw.into_response(),
Err(e) => handle_error(e)
@ -141,23 +121,19 @@ where
}
#[cfg(feature = "openapi")]
fn schema() -> OpenapiSchema
{
fn schema() -> OpenapiSchema {
<Raw<T> as ResourceResult>::schema()
}
}
#[cfg(test)]
mod test
{
mod test {
use super::*;
use futures_executor::block_on;
use mime::TEXT_PLAIN;
#[test]
fn raw_response()
{
fn raw_response() {
let msg = "Test";
let raw = Raw::new(msg, TEXT_PLAIN);
let res = block_on(raw.into_response()).expect("didn't expect error response");

View file

@ -1,33 +1,26 @@
use super::{ResourceResult, handle_error, into_response_helper};
use crate::{
result::ResourceError,
Response, ResponseBody, StatusCode
};
use super::{handle_error, into_response_helper, ResourceResult};
#[cfg(feature = "openapi")]
use crate::OpenapiSchema;
use crate::{result::ResourceError, Response, ResponseBody, StatusCode};
use futures_core::future::Future;
use mime::{Mime, APPLICATION_JSON};
use std::{
error::Error,
fmt::Display,
pin::Pin
};
use std::{error::Error, fmt::Display, pin::Pin};
pub trait IntoResponseError
{
pub trait IntoResponseError {
type Err: Error + Send + 'static;
fn into_response_error(self) -> Result<Response, Self::Err>;
}
impl<E : Error> IntoResponseError for E
{
impl<E: Error> IntoResponseError for E {
type Err = serde_json::Error;
fn into_response_error(self) -> Result<Response, Self::Err>
{
fn into_response_error(self) -> Result<Response, Self::Err> {
let err: ResourceError = self.into();
Ok(Response::json(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?))
Ok(Response::json(
StatusCode::INTERNAL_SERVER_ERROR,
serde_json::to_string(&err)?
))
}
}
@ -38,30 +31,25 @@ where
{
type Err = E::Err;
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>>
{
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>> {
match self {
Ok(r) => into_response_helper(|| Ok(Response::json(StatusCode::OK, serde_json::to_string(&r)?))),
Err(e) => handle_error(e)
}
}
fn accepted_types() -> Option<Vec<Mime>>
{
fn accepted_types() -> Option<Vec<Mime>> {
Some(vec![APPLICATION_JSON])
}
#[cfg(feature = "openapi")]
fn schema() -> OpenapiSchema
{
fn schema() -> OpenapiSchema {
R::schema()
}
}
#[cfg(test)]
mod test
{
mod test {
use super::*;
use crate::result::OrAllTypes;
use futures_executor::block_on;
@ -69,8 +57,7 @@ mod test
#[derive(Debug, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "openapi", derive(crate::OpenapiType))]
struct Msg
{
struct Msg {
msg: String
}
@ -79,8 +66,7 @@ mod test
struct MsgError;
#[test]
fn result_ok()
{
fn result_ok() {
let ok: Result<Msg, MsgError> = Ok(Msg::default());
let res = block_on(ok.into_response()).expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
@ -89,18 +75,21 @@ mod test
}
#[test]
fn result_err()
{
fn result_err() {
let err: Result<Msg, MsgError> = Err(MsgError::default());
let res = block_on(err.into_response()).expect("didn't expect error response");
assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(res.mime, Some(APPLICATION_JSON));
assert_eq!(res.full_body().unwrap(), format!(r#"{{"error":true,"message":"{}"}}"#, MsgError::default()).as_bytes());
assert_eq!(
res.full_body().unwrap(),
format!(r#"{{"error":true,"message":"{}"}}"#, MsgError::default()).as_bytes()
);
}
#[test]
fn success_accepts_json()
{
assert!(<Result<Msg, MsgError>>::accepted_types().or_all_types().contains(&APPLICATION_JSON))
fn success_accepts_json() {
assert!(<Result<Msg, MsgError>>::accepted_types()
.or_all_types()
.contains(&APPLICATION_JSON))
}
}

View file

@ -1,14 +1,14 @@
use super::{ResourceResult, into_response_helper};
use crate::{Response, ResponseBody};
use super::{into_response_helper, ResourceResult};
#[cfg(feature = "openapi")]
use crate::OpenapiSchema;
use crate::{Response, ResponseBody};
use gotham::hyper::StatusCode;
use mime::{Mime, APPLICATION_JSON};
use std::{
fmt::Debug,
future::Future,
pin::Pin,
ops::{Deref, DerefMut}
ops::{Deref, DerefMut},
pin::Pin
};
/**
@ -45,64 +45,48 @@ fn read_all(_state: &mut State) -> Success<MyResponse> {
#[derive(Debug)]
pub struct Success<T>(T);
impl<T> AsMut<T> for Success<T>
{
fn as_mut(&mut self) -> &mut T
{
impl<T> AsMut<T> for Success<T> {
fn as_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T> AsRef<T> for Success<T>
{
fn as_ref(&self) -> &T
{
impl<T> AsRef<T> for Success<T> {
fn as_ref(&self) -> &T {
&self.0
}
}
impl<T> Deref for Success<T>
{
impl<T> Deref for Success<T> {
type Target = T;
fn deref(&self) -> &T
{
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for Success<T>
{
fn deref_mut(&mut self) -> &mut T
{
impl<T> DerefMut for Success<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T> From<T> for Success<T>
{
fn from(t : T) -> Self
{
impl<T> From<T> for Success<T> {
fn from(t: T) -> Self {
Self(t)
}
}
impl<T : Clone> Clone for Success<T>
{
fn clone(&self) -> Self
{
impl<T: Clone> Clone for Success<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T : Copy> Copy for Success<T>
{
}
impl<T: Copy> Copy for Success<T> {}
impl<T : Default> Default for Success<T>
{
fn default() -> Self
{
impl<T: Default> Default for Success<T> {
fn default() -> Self {
Self(T::default())
}
}
@ -113,41 +97,34 @@ where
{
type Err = serde_json::Error;
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>>
{
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>> {
into_response_helper(|| Ok(Response::json(StatusCode::OK, serde_json::to_string(self.as_ref())?)))
}
fn accepted_types() -> Option<Vec<Mime>>
{
fn accepted_types() -> Option<Vec<Mime>> {
Some(vec![APPLICATION_JSON])
}
#[cfg(feature = "openapi")]
fn schema() -> OpenapiSchema
{
fn schema() -> OpenapiSchema {
T::schema()
}
}
#[cfg(test)]
mod test
{
mod test {
use super::*;
use crate::result::OrAllTypes;
use futures_executor::block_on;
#[derive(Debug, Default, Serialize)]
#[cfg_attr(feature = "openapi", derive(crate::OpenapiType))]
struct Msg
{
struct Msg {
msg: String
}
#[test]
fn success_always_successfull()
{
fn success_always_successfull() {
let success: Success<Msg> = Msg::default().into();
let res = block_on(success.into_response()).expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
@ -156,8 +133,7 @@ mod test
}
#[test]
fn success_accepts_json()
{
fn success_accepts_json() {
assert!(<Success<Msg>>::accepted_types().or_all_types().contains(&APPLICATION_JSON))
}
}

View file

@ -1,22 +1,21 @@
use crate::{
resource::*,
result::{ResourceError, ResourceResult},
RequestBody,
Response,
StatusCode
};
#[cfg(feature = "cors")]
use crate::CorsRoute;
#[cfg(feature = "openapi")]
use crate::openapi::{
builder::{OpenapiBuilder, OpenapiInfo},
router::OpenapiRouter
};
#[cfg(feature = "cors")]
use crate::CorsRoute;
use crate::{
resource::*,
result::{ResourceError, ResourceResult},
RequestBody, Response, StatusCode
};
use futures_util::{future, future::FutureExt};
use gotham::{
handler::{HandlerError, HandlerFuture, IntoHandlerError},
handler::{HandlerError, HandlerFuture},
helpers::http::response::{create_empty_response, create_response},
hyper::{body::to_bytes, header::CONTENT_TYPE, Body, HeaderMap, Method},
pipeline::chain::PipelineHandleChain,
router::{
builder::*,
@ -25,24 +24,12 @@ use gotham::{
},
state::{FromState, State}
};
use gotham::hyper::{
body::to_bytes,
header::CONTENT_TYPE,
Body,
HeaderMap,
Method
};
use mime::{Mime, APPLICATION_JSON};
use std::{
future::Future,
panic::RefUnwindSafe,
pin::Pin
};
use std::{future::Future, panic::RefUnwindSafe, pin::Pin};
/// Allow us to extract an id from a path.
#[derive(Deserialize, StateData, StaticResponseExtender)]
struct PathExtractor<ID : RefUnwindSafe + Send + 'static>
{
struct PathExtractor<ID: RefUnwindSafe + Send + 'static> {
id: ID
}
@ -50,8 +37,7 @@ struct PathExtractor<ID : RefUnwindSafe + Send + 'static>
/// router into one that will only allow RESTful resources, but record them and generate
/// an OpenAPI specification on request.
#[cfg(feature = "openapi")]
pub trait WithOpenapi<D>
{
pub trait WithOpenapi<D> {
fn with_openapi<F>(&mut self, info: OpenapiInfo, block: F)
where
F: FnOnce(OpenapiRouter<'_, D>);
@ -59,15 +45,13 @@ pub trait WithOpenapi<D>
/// This trait adds the `resource` method to gotham's routing. It allows you to register
/// any RESTful `Resource` with a path.
pub trait DrawResources
{
pub trait DrawResources {
fn resource<R: Resource>(&mut self, path: &str);
}
/// This trait allows to draw routes within an resource. Use this only inside the
/// `Resource::setup` method.
pub trait DrawResourceRoutes
{
pub trait DrawResourceRoutes {
fn read_all<Handler: ResourceReadAll>(&mut self);
fn read<Handler: ResourceRead>(&mut self);
@ -94,17 +78,14 @@ pub trait DrawResourceRoutes
fn remove<Handler: ResourceRemove>(&mut self);
}
fn response_from(res : Response, state : &State) -> gotham::hyper::Response<Body>
{
fn response_from(res: Response, state: &State) -> gotham::hyper::Response<Body> {
let mut r = create_empty_response(state, res.status);
if let Some(mime) = res.mime
{
if let Some(mime) = res.mime {
r.headers_mut().insert(CONTENT_TYPE, mime.as_ref().parse().unwrap());
}
let method = Method::borrow_from(state);
if method != Method::HEAD
{
if method != Method::HEAD {
*r.body_mut() = res.body;
}
@ -114,7 +95,10 @@ fn response_from(res : Response, state : &State) -> gotham::hyper::Response<Body
r
}
async fn to_handler_future<F, R>(state : State, get_result : F) -> Result<(State, gotham::hyper::Response<Body>), (State, HandlerError)>
async fn to_handler_future<F, R>(
state: State,
get_result: F
) -> Result<(State, gotham::hyper::Response<Body>), (State, HandlerError)>
where
F: FnOnce(State) -> Pin<Box<dyn Future<Output = (State, R)> + Send>>,
R: ResourceResult
@ -126,11 +110,14 @@ where
let r = response_from(res, &state);
Ok((state, r))
},
Err(e) => Err((state, e.into_handler_error()))
Err(e) => Err((state, e.into()))
}
}
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
B: RequestBody,
F: FnOnce(State, B) -> Pin<Box<dyn Future<Output = (State, R)> + Send>>,
@ -140,14 +127,14 @@ where
let body = match body {
Ok(body) => body,
Err(e) => return (state, Err(e.into_handler_error()))
Err(e) => return (state, Err(e.into()))
};
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 (state, Ok(res))
return (state, Ok(res));
}
};
@ -161,9 +148,9 @@ where
let res = create_response(&state, StatusCode::BAD_REQUEST, APPLICATION_JSON, json);
Ok(res)
},
Err(e) => Err(e.into_handler_error())
Err(e) => Err(e.into())
};
return (state, res)
return (state, res);
}
};
get_result(state, body)
@ -177,7 +164,7 @@ where
let r = response_from(res, &state);
Ok(r)
},
Err(e) => Err(e.into_handler_error())
Err(e) => Err(e.into())
};
(state, res)
}
@ -196,13 +183,11 @@ where
.boxed()
}
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)).boxed()
}
fn read_handler<Handler : ResourceRead>(state : State) -> Pin<Box<HandlerFuture>>
{
fn read_handler<Handler: ResourceRead>(state: State) -> Pin<Box<HandlerFuture>> {
let id = {
let path: &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);
path.id.clone()
@ -210,8 +195,7 @@ fn read_handler<Handler : ResourceRead>(state : State) -> Pin<Box<HandlerFuture>
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);
to_handler_future(state, |state| Handler::search(state, query)).boxed()
}
@ -244,13 +228,11 @@ where
handle_with_body::<Handler::Body, _, _>(state, |state, body| Handler::change(state, id, body))
}
fn remove_all_handler<Handler : ResourceRemoveAll>(state : State) -> Pin<Box<HandlerFuture>>
{
fn remove_all_handler<Handler: ResourceRemoveAll>(state: State) -> Pin<Box<HandlerFuture>> {
to_handler_future(state, |state| Handler::remove_all(state)).boxed()
}
fn remove_handler<Handler : ResourceRemove>(state : State) -> Pin<Box<HandlerFuture>>
{
fn remove_handler<Handler: ResourceRemove>(state: State) -> Pin<Box<HandlerFuture>> {
let id = {
let path: &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);
path.id.clone()
@ -259,15 +241,12 @@ fn remove_handler<Handler : ResourceRemove>(state : State) -> Pin<Box<HandlerFut
}
#[derive(Clone)]
struct MaybeMatchAcceptHeader
{
struct MaybeMatchAcceptHeader {
matcher: Option<AcceptHeaderRouteMatcher>
}
impl RouteMatcher for MaybeMatchAcceptHeader
{
fn is_match(&self, state : &State) -> Result<(), RouteNonMatch>
{
impl RouteMatcher for MaybeMatchAcceptHeader {
fn is_match(&self, state: &State) -> Result<(), RouteNonMatch> {
match &self.matcher {
Some(matcher) => matcher.is_match(state),
None => Ok(())
@ -275,10 +254,8 @@ impl RouteMatcher for MaybeMatchAcceptHeader
}
}
impl From<Option<Vec<Mime>>> for MaybeMatchAcceptHeader
{
fn from(types : Option<Vec<Mime>>) -> Self
{
impl From<Option<Vec<Mime>>> for MaybeMatchAcceptHeader {
fn from(types: Option<Vec<Mime>>) -> Self {
let types = match types {
Some(types) if types.is_empty() => None,
types => types
@ -290,15 +267,12 @@ impl From<Option<Vec<Mime>>> for MaybeMatchAcceptHeader
}
#[derive(Clone)]
struct MaybeMatchContentTypeHeader
{
struct MaybeMatchContentTypeHeader {
matcher: Option<ContentTypeHeaderRouteMatcher>
}
impl RouteMatcher for MaybeMatchContentTypeHeader
{
fn is_match(&self, state : &State) -> Result<(), RouteNonMatch>
{
impl RouteMatcher for MaybeMatchContentTypeHeader {
fn is_match(&self, state: &State) -> Result<(), RouteNonMatch> {
match &self.matcher {
Some(matcher) => matcher.is_match(state),
None => Ok(())
@ -306,10 +280,8 @@ impl RouteMatcher for MaybeMatchContentTypeHeader
}
}
impl From<Option<Vec<Mime>>> for MaybeMatchContentTypeHeader
{
fn from(types : Option<Vec<Mime>>) -> Self
{
impl From<Option<Vec<Mime>>> for MaybeMatchContentTypeHeader {
fn from(types: Option<Vec<Mime>>) -> Self {
Self {
matcher: types.map(|types| ContentTypeHeaderRouteMatcher::new(types).allow_no_type())
}
@ -318,7 +290,6 @@ impl From<Option<Vec<Mime>>> for MaybeMatchContentTypeHeader
macro_rules! implDrawResourceRoutes {
($implType:ident) => {
#[cfg(feature = "openapi")]
impl<'a, C, P> WithOpenapi<Self> for $implType<'a, C, P>
where
@ -343,8 +314,7 @@ macro_rules! implDrawResourceRoutes {
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static
{
fn resource<R : Resource>(&mut self, path : &str)
{
fn resource<R: Resource>(&mut self, path: &str) {
R::setup((self, path));
}
}
@ -355,27 +325,27 @@ macro_rules! implDrawResourceRoutes {
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static
{
fn read_all<Handler : ResourceReadAll>(&mut self)
{
fn read_all<Handler: ResourceReadAll>(&mut self) {
let matcher: MaybeMatchAcceptHeader = Handler::Res::accepted_types().into();
self.0.get(&self.1)
self.0
.get(&self.1)
.extend_route_matcher(matcher)
.to(|state| read_all_handler::<Handler>(state));
}
fn read<Handler : ResourceRead>(&mut self)
{
fn read<Handler: ResourceRead>(&mut self) {
let matcher: MaybeMatchAcceptHeader = Handler::Res::accepted_types().into();
self.0.get(&format!("{}/:id", self.1))
self.0
.get(&format!("{}/:id", self.1))
.extend_route_matcher(matcher)
.with_path_extractor::<PathExtractor<Handler::ID>>()
.to(|state| read_handler::<Handler>(state));
}
fn search<Handler : ResourceSearch>(&mut self)
{
fn search<Handler: ResourceSearch>(&mut self) {
let matcher: MaybeMatchAcceptHeader = Handler::Res::accepted_types().into();
self.0.get(&format!("{}/search", self.1))
self.0
.get(&format!("{}/search", self.1))
.extend_route_matcher(matcher)
.with_query_string_extractor::<Handler::Query>()
.to(|state| search_handler::<Handler>(state));
@ -388,7 +358,8 @@ macro_rules! implDrawResourceRoutes {
{
let accept_matcher: MaybeMatchAcceptHeader = Handler::Res::accepted_types().into();
let content_matcher: MaybeMatchContentTypeHeader = Handler::Body::supported_types().into();
self.0.post(&self.1)
self.0
.post(&self.1)
.extend_route_matcher(accept_matcher)
.extend_route_matcher(content_matcher)
.to(|state| create_handler::<Handler>(state));
@ -403,7 +374,8 @@ macro_rules! implDrawResourceRoutes {
{
let accept_matcher: MaybeMatchAcceptHeader = Handler::Res::accepted_types().into();
let content_matcher: MaybeMatchContentTypeHeader = Handler::Body::supported_types().into();
self.0.put(&self.1)
self.0
.put(&self.1)
.extend_route_matcher(accept_matcher)
.extend_route_matcher(content_matcher)
.to(|state| change_all_handler::<Handler>(state));
@ -419,7 +391,8 @@ macro_rules! implDrawResourceRoutes {
let accept_matcher: MaybeMatchAcceptHeader = Handler::Res::accepted_types().into();
let content_matcher: MaybeMatchContentTypeHeader = Handler::Body::supported_types().into();
let path = format!("{}/:id", self.1);
self.0.put(&path)
self.0
.put(&path)
.extend_route_matcher(accept_matcher)
.extend_route_matcher(content_matcher)
.with_path_extractor::<PathExtractor<Handler::ID>>()
@ -428,21 +401,21 @@ macro_rules! implDrawResourceRoutes {
self.0.cors(&path, Method::PUT);
}
fn remove_all<Handler : ResourceRemoveAll>(&mut self)
{
fn remove_all<Handler: ResourceRemoveAll>(&mut self) {
let matcher: MaybeMatchAcceptHeader = Handler::Res::accepted_types().into();
self.0.delete(&self.1)
self.0
.delete(&self.1)
.extend_route_matcher(matcher)
.to(|state| remove_all_handler::<Handler>(state));
#[cfg(feature = "cors")]
self.0.cors(&self.1, Method::DELETE);
}
fn remove<Handler : ResourceRemove>(&mut self)
{
fn remove<Handler: ResourceRemove>(&mut self) {
let matcher: MaybeMatchAcceptHeader = Handler::Res::accepted_types().into();
let path = format!("{}/:id", self.1);
self.0.delete(&path)
self.0
.delete(&path)
.extend_route_matcher(matcher)
.with_path_extractor::<PathExtractor<Handler::ID>>()
.to(|state| remove_handler::<Handler>(state));
@ -450,7 +423,7 @@ macro_rules! implDrawResourceRoutes {
self.0.cors(&path, Method::POST);
}
}
}
};
}
implDrawResourceRoutes!(RouterBuilder);

View file

@ -4,43 +4,26 @@ use crate::OpenapiType;
use gotham::hyper::body::Bytes;
use mime::{Mime, APPLICATION_JSON};
use serde::{de::DeserializeOwned, Serialize};
use std::{
error::Error,
panic::RefUnwindSafe
};
use std::{error::Error, panic::RefUnwindSafe};
#[cfg(not(feature = "openapi"))]
pub trait ResourceType
{
}
pub trait ResourceType {}
#[cfg(not(feature = "openapi"))]
impl<T> ResourceType for T
{
}
impl<T> ResourceType for T {}
#[cfg(feature = "openapi")]
pub trait ResourceType : OpenapiType
{
}
pub trait ResourceType: OpenapiType {}
#[cfg(feature = "openapi")]
impl<T : OpenapiType> ResourceType for T
{
}
impl<T: OpenapiType> ResourceType for T {}
/// A type that can be used inside a response body. Implemented for every type that is
/// serializable with serde. If the `openapi` feature is used, it must also be of type
/// `OpenapiType`.
pub trait ResponseBody : ResourceType + Serialize
{
}
impl<T : ResourceType + Serialize> ResponseBody for T
{
}
pub trait ResponseBody: ResourceType + Serialize {}
impl<T: ResourceType + Serialize> ResponseBody for T {}
/**
This trait should be implemented for every type that can be built from an HTTP request body
@ -64,8 +47,7 @@ struct RawImage {
[`Bytes`]: ../bytes/struct.Bytes.html
[`Mime`]: ../mime/struct.Mime.html
*/
pub trait FromBody : Sized
{
pub trait FromBody: Sized {
/// The error type returned by the conversion if it was unsuccessfull. When using the derive
/// macro, there is no way to trigger an error, so `Infallible` is used here. However, this
/// might change in the future.
@ -75,17 +57,14 @@ pub trait FromBody : Sized
fn from_body(body: Bytes, content_type: Mime) -> Result<Self, Self::Err>;
}
impl<T : DeserializeOwned> FromBody for T
{
impl<T: DeserializeOwned> FromBody for T {
type Err = serde_json::Error;
fn from_body(body : Bytes, _content_type : Mime) -> Result<Self, Self::Err>
{
fn from_body(body: Bytes, _content_type: Mime) -> Result<Self, Self::Err> {
serde_json::from_slice(&body)
}
}
/**
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`].
@ -108,19 +87,15 @@ struct RawImage {
[`FromBody`]: trait.FromBody.html
[`OpenapiType`]: trait.OpenapiType.html
*/
pub trait RequestBody : ResourceType + FromBody
{
pub trait RequestBody: ResourceType + FromBody {
/// Return all types that are supported as content types. Use `None` if all types are supported.
fn supported_types() -> Option<Vec<Mime>>
{
fn supported_types() -> Option<Vec<Mime>> {
None
}
}
impl<T : ResourceType + DeserializeOwned> RequestBody for T
{
fn supported_types() -> Option<Vec<Mime>>
{
impl<T: ResourceType + DeserializeOwned> RequestBody for T {
fn supported_types() -> Option<Vec<Mime>> {
Some(vec![APPLICATION_JSON])
}
}
@ -128,10 +103,6 @@ impl<T : ResourceType + DeserializeOwned> RequestBody for T
/// A type than can be used as a parameter to a resource method. Implemented for every type
/// that is deserialize and thread-safe. If the `openapi` feature is used, it must also be of
/// type `OpenapiType`.
pub trait ResourceID : ResourceType + DeserializeOwned + Clone + RefUnwindSafe + Send + Sync
{
}
pub trait ResourceID: ResourceType + DeserializeOwned + Clone + RefUnwindSafe + Send + Sync {}
impl<T : ResourceType + DeserializeOwned + Clone + RefUnwindSafe + Send + Sync> ResourceID for T
{
}
impl<T: ResourceType + DeserializeOwned + Clone + RefUnwindSafe + Send + Sync> ResourceID for T {}

View file

@ -1,16 +1,15 @@
#[macro_use] extern crate gotham_derive;
#[macro_use]
extern crate gotham_derive;
use gotham::{
router::builder::*,
test::TestServer
};
use gotham::{router::builder::*, test::TestServer};
use gotham_restful::*;
use mime::{APPLICATION_JSON, TEXT_PLAIN};
use serde::Deserialize;
mod util { include!("util/mod.rs"); }
use util::{test_get_response, test_post_response, test_put_response, test_delete_response};
mod util {
include!("util/mod.rs");
}
use util::{test_delete_response, test_get_response, test_post_response, test_put_response};
#[derive(Resource)]
#[resource(read_all, read, search, create, change_all, change, remove_all, remove)]
@ -19,88 +18,96 @@ struct FooResource;
#[derive(Deserialize)]
#[cfg_attr(feature = "openapi", derive(OpenapiType))]
#[allow(dead_code)]
struct FooBody
{
struct FooBody {
data: String
}
#[derive(Deserialize, StateData, StaticResponseExtender)]
#[cfg_attr(feature = "openapi", derive(OpenapiType))]
#[allow(dead_code)]
struct FooSearch
{
struct FooSearch {
query: String
}
const READ_ALL_RESPONSE: &[u8] = b"1ARwwSPVyOKpJKrYwqGgECPVWDl1BqajAAj7g7WJ3e";
#[read_all(FooResource)]
async fn read_all() -> Raw<&'static [u8]>
{
async fn read_all() -> Raw<&'static [u8]> {
Raw::new(READ_ALL_RESPONSE, TEXT_PLAIN)
}
const READ_RESPONSE: &[u8] = b"FEReHoeBKU17X2bBpVAd1iUvktFL43CDu0cFYHdaP9";
#[read(FooResource)]
async fn read(_id : u64) -> Raw<&'static [u8]>
{
async fn read(_id: u64) -> Raw<&'static [u8]> {
Raw::new(READ_RESPONSE, TEXT_PLAIN)
}
const SEARCH_RESPONSE: &[u8] = b"AWqcQUdBRHXKh3at4u79mdupOAfEbnTcx71ogCVF0E";
#[search(FooResource)]
async fn search(_body : FooSearch) -> Raw<&'static [u8]>
{
async fn search(_body: FooSearch) -> Raw<&'static [u8]> {
Raw::new(SEARCH_RESPONSE, TEXT_PLAIN)
}
const CREATE_RESPONSE: &[u8] = b"y6POY7wOMAB0jBRBw0FJT7DOpUNbhmT8KdpQPLkI83";
#[create(FooResource)]
async fn create(_body : FooBody) -> Raw<&'static [u8]>
{
async fn create(_body: FooBody) -> Raw<&'static [u8]> {
Raw::new(CREATE_RESPONSE, TEXT_PLAIN)
}
const CHANGE_ALL_RESPONSE: &[u8] = b"QlbYg8gHE9OQvvk3yKjXJLTSXlIrg9mcqhfMXJmQkv";
#[change_all(FooResource)]
async fn change_all(_body : FooBody) -> Raw<&'static [u8]>
{
async fn change_all(_body: FooBody) -> Raw<&'static [u8]> {
Raw::new(CHANGE_ALL_RESPONSE, TEXT_PLAIN)
}
const CHANGE_RESPONSE: &[u8] = b"qGod55RUXkT1lgPO8h0uVM6l368O2S0GrwENZFFuRu";
#[change(FooResource)]
async fn change(_id : u64, _body : FooBody) -> Raw<&'static [u8]>
{
async fn change(_id: u64, _body: FooBody) -> Raw<&'static [u8]> {
Raw::new(CHANGE_RESPONSE, TEXT_PLAIN)
}
const REMOVE_ALL_RESPONSE: &[u8] = b"Y36kZ749MRk2Nem4BedJABOZiZWPLOtiwLfJlGTwm5";
#[remove_all(FooResource)]
async fn remove_all() -> Raw<&'static [u8]>
{
async fn remove_all() -> Raw<&'static [u8]> {
Raw::new(REMOVE_ALL_RESPONSE, TEXT_PLAIN)
}
const REMOVE_RESPONSE: &[u8] = b"CwRzBrKErsVZ1N7yeNfjZuUn1MacvgBqk4uPOFfDDq";
#[remove(FooResource)]
async fn remove(_id : u64) -> Raw<&'static [u8]>
{
async fn remove(_id: u64) -> Raw<&'static [u8]> {
Raw::new(REMOVE_RESPONSE, TEXT_PLAIN)
}
#[test]
fn async_methods()
{
fn async_methods() {
let server = TestServer::new(build_simple_router(|router| {
router.resource::<FooResource>("foo");
})).unwrap();
}))
.unwrap();
test_get_response(&server, "http://localhost/foo", READ_ALL_RESPONSE);
test_get_response(&server, "http://localhost/foo/1", READ_RESPONSE);
test_get_response(&server, "http://localhost/foo/search?query=hello+world", SEARCH_RESPONSE);
test_post_response(&server, "http://localhost/foo", r#"{"data":"hello world"}"#, APPLICATION_JSON, CREATE_RESPONSE);
test_put_response(&server, "http://localhost/foo", r#"{"data":"hello world"}"#, APPLICATION_JSON, CHANGE_ALL_RESPONSE);
test_put_response(&server, "http://localhost/foo/1", r#"{"data":"hello world"}"#, APPLICATION_JSON, CHANGE_RESPONSE);
test_post_response(
&server,
"http://localhost/foo",
r#"{"data":"hello world"}"#,
APPLICATION_JSON,
CREATE_RESPONSE
);
test_put_response(
&server,
"http://localhost/foo",
r#"{"data":"hello world"}"#,
APPLICATION_JSON,
CHANGE_ALL_RESPONSE
);
test_put_response(
&server,
"http://localhost/foo/1",
r#"{"data":"hello world"}"#,
APPLICATION_JSON,
CHANGE_RESPONSE
);
test_delete_response(&server, "http://localhost/foo", REMOVE_ALL_RESPONSE);
test_delete_response(&server, "http://localhost/foo/1", REMOVE_RESPONSE);
}

View file

@ -5,7 +5,7 @@ use gotham::{
router::builder::*,
test::{Server, TestRequest, TestServer}
};
use gotham_restful::{CorsConfig, DrawResources, Origin, Raw, Resource, change_all, read_all};
use gotham_restful::{change_all, read_all, CorsConfig, DrawResources, Origin, Raw, Resource};
use itertools::Itertools;
use mime::TEXT_PLAIN;
@ -14,21 +14,14 @@ use mime::TEXT_PLAIN;
struct FooResource;
#[read_all(FooResource)]
fn read_all()
{
}
fn read_all() {}
#[change_all(FooResource)]
fn change_all(_body : Raw<Vec<u8>>)
{
}
fn change_all(_body: Raw<Vec<u8>>) {}
fn test_server(cfg : CorsConfig) -> TestServer
{
fn test_server(cfg: CorsConfig) -> TestServer {
let (chain, pipeline) = single_pipeline(new_pipeline().add(cfg).build());
TestServer::new(build_router(chain, pipeline, |router| {
router.resource::<FooResource>("/foo")
})).unwrap()
TestServer::new(build_router(chain, pipeline, |router| router.resource::<FooResource>("/foo"))).unwrap()
}
fn test_response<TS, C>(req: TestRequest<TS, C>, origin: Option<&str>, vary: Option<&str>, credentials: bool)
@ -36,48 +29,93 @@ where
TS: Server + 'static,
C: Connect + Clone + Send + Sync + 'static
{
let res = req.with_header(ORIGIN, "http://example.org".parse().unwrap()).perform().unwrap();
let res = req
.with_header(ORIGIN, "http://example.org".parse().unwrap())
.perform()
.unwrap();
assert_eq!(res.status(), StatusCode::NO_CONTENT);
let headers = res.headers();
println!("{}", headers.keys().join(","));
assert_eq!(headers.get(ACCESS_CONTROL_ALLOW_ORIGIN).and_then(|value| value.to_str().ok()).as_deref(), origin);
assert_eq!(
headers
.get(ACCESS_CONTROL_ALLOW_ORIGIN)
.and_then(|value| value.to_str().ok())
.as_deref(),
origin
);
assert_eq!(headers.get(VARY).and_then(|value| value.to_str().ok()).as_deref(), vary);
assert_eq!(headers.get(ACCESS_CONTROL_ALLOW_CREDENTIALS).and_then(|value| value.to_str().ok()).map(|value| value == "true").unwrap_or(false), credentials);
assert_eq!(
headers
.get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
.and_then(|value| value.to_str().ok())
.map(|value| value == "true")
.unwrap_or(false),
credentials
);
assert!(headers.get(ACCESS_CONTROL_MAX_AGE).is_none());
}
fn test_preflight(server : &TestServer, method : &str, origin : Option<&str>, vary : &str, credentials : bool, max_age : u64)
{
let res = server.client().options("http://example.org/foo")
fn test_preflight(server: &TestServer, method: &str, origin: Option<&str>, vary: &str, credentials: bool, max_age: u64) {
let res = server
.client()
.options("http://example.org/foo")
.with_header(ACCESS_CONTROL_REQUEST_METHOD, method.parse().unwrap())
.with_header(ORIGIN, "http://example.org".parse().unwrap())
.perform().unwrap();
.perform()
.unwrap();
assert_eq!(res.status(), StatusCode::NO_CONTENT);
let headers = res.headers();
println!("{}", headers.keys().join(","));
assert_eq!(headers.get(ACCESS_CONTROL_ALLOW_METHODS).and_then(|value| value.to_str().ok()).as_deref(), Some(method));
assert_eq!(headers.get(ACCESS_CONTROL_ALLOW_ORIGIN).and_then(|value| value.to_str().ok()).as_deref(), origin);
assert_eq!(
headers
.get(ACCESS_CONTROL_ALLOW_METHODS)
.and_then(|value| value.to_str().ok())
.as_deref(),
Some(method)
);
assert_eq!(
headers
.get(ACCESS_CONTROL_ALLOW_ORIGIN)
.and_then(|value| value.to_str().ok())
.as_deref(),
origin
);
assert_eq!(headers.get(VARY).and_then(|value| value.to_str().ok()).as_deref(), Some(vary));
assert_eq!(headers.get(ACCESS_CONTROL_ALLOW_CREDENTIALS).and_then(|value| value.to_str().ok()).map(|value| value == "true").unwrap_or(false), credentials);
assert_eq!(headers.get(ACCESS_CONTROL_MAX_AGE).and_then(|value| value.to_str().ok()).and_then(|value| value.parse().ok()), Some(max_age));
assert_eq!(
headers
.get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
.and_then(|value| value.to_str().ok())
.map(|value| value == "true")
.unwrap_or(false),
credentials
);
assert_eq!(
headers
.get(ACCESS_CONTROL_MAX_AGE)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok()),
Some(max_age)
);
}
#[test]
fn cors_origin_none()
{
fn cors_origin_none() {
let cfg = Default::default();
let server = test_server(cfg);
test_preflight(&server, "PUT", None, "Access-Control-Request-Method", false, 0);
test_response(server.client().get("http://example.org/foo"), None, None, false);
test_response(server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN), None, None, false);
test_response(
server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN),
None,
None,
false
);
}
#[test]
fn cors_origin_star()
{
fn cors_origin_star() {
let cfg = CorsConfig {
origin: Origin::Star,
..Default::default()
@ -87,42 +125,78 @@ fn cors_origin_star()
test_preflight(&server, "PUT", Some("*"), "Access-Control-Request-Method", false, 0);
test_response(server.client().get("http://example.org/foo"), Some("*"), None, false);
test_response(server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN), Some("*"), None, false);
test_response(
server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN),
Some("*"),
None,
false
);
}
#[test]
fn cors_origin_single()
{
fn cors_origin_single() {
let cfg = CorsConfig {
origin: Origin::Single("https://foo.com".to_owned()),
..Default::default()
};
let server = test_server(cfg);
test_preflight(&server, "PUT", Some("https://foo.com"), "Access-Control-Request-Method", false, 0);
test_preflight(
&server,
"PUT",
Some("https://foo.com"),
"Access-Control-Request-Method",
false,
0
);
test_response(server.client().get("http://example.org/foo"), Some("https://foo.com"), None, false);
test_response(server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN), Some("https://foo.com"), None, false);
test_response(
server.client().get("http://example.org/foo"),
Some("https://foo.com"),
None,
false
);
test_response(
server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN),
Some("https://foo.com"),
None,
false
);
}
#[test]
fn cors_origin_copy()
{
fn cors_origin_copy() {
let cfg = CorsConfig {
origin: Origin::Copy,
..Default::default()
};
let server = test_server(cfg);
test_preflight(&server, "PUT", Some("http://example.org"), "Access-Control-Request-Method,Origin", false, 0);
test_preflight(
&server,
"PUT",
Some("http://example.org"),
"Access-Control-Request-Method,Origin",
false,
0
);
test_response(server.client().get("http://example.org/foo"), Some("http://example.org"), Some("Origin"), false);
test_response(server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN), Some("http://example.org"), Some("Origin"), false);
test_response(
server.client().get("http://example.org/foo"),
Some("http://example.org"),
Some("Origin"),
false
);
test_response(
server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN),
Some("http://example.org"),
Some("Origin"),
false
);
}
#[test]
fn cors_credentials()
{
fn cors_credentials() {
let cfg = CorsConfig {
origin: Origin::None,
credentials: true,
@ -133,12 +207,16 @@ fn cors_credentials()
test_preflight(&server, "PUT", None, "Access-Control-Request-Method", true, 0);
test_response(server.client().get("http://example.org/foo"), None, None, true);
test_response(server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN), None, None, true);
test_response(
server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN),
None,
None,
true
);
}
#[test]
fn cors_max_age()
{
fn cors_max_age() {
let cfg = CorsConfig {
origin: Origin::None,
max_age: 31536000,
@ -149,5 +227,10 @@ fn cors_max_age()
test_preflight(&server, "PUT", None, "Access-Control-Request-Method", false, 31536000);
test_response(server.client().get("http://example.org/foo"), None, None, false);
test_response(server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN), None, None, false);
test_response(
server.client().put("http://example.org/foo", Body::empty(), TEXT_PLAIN),
None,
None,
false
);
}

View file

@ -1,12 +1,7 @@
use gotham::{
hyper::header::CONTENT_TYPE,
router::builder::*,
test::TestServer
};
use gotham::{hyper::header::CONTENT_TYPE, router::builder::*, test::TestServer};
use gotham_restful::*;
use mime::TEXT_PLAIN;
const RESPONSE: &[u8] = b"This is the only valid response.";
#[derive(Resource)]
@ -25,17 +20,18 @@ fn create(body : Foo) -> Raw<Vec<u8>> {
Raw::new(body.content, body.content_type)
}
#[test]
fn custom_request_body()
{
fn custom_request_body() {
let server = TestServer::new(build_simple_router(|router| {
router.resource::<FooResource>("foo");
})).unwrap();
}))
.unwrap();
let res = server.client()
let res = server
.client()
.post("http://localhost/foo", RESPONSE, TEXT_PLAIN)
.perform().unwrap();
.perform()
.unwrap();
assert_eq!(res.headers().get(CONTENT_TYPE).unwrap().to_str().unwrap(), "text/plain");
let res = res.read_body().unwrap();
let body: &[u8] = res.as_ref();

View file

@ -1,6 +1,7 @@
#![cfg(all(feature = "auth", feature = "chrono", feature = "openapi"))]
#[macro_use] extern crate gotham_derive;
#[macro_use]
extern crate gotham_derive;
use chrono::{NaiveDate, NaiveDateTime};
use gotham::{
@ -13,10 +14,11 @@ use mime::IMAGE_PNG;
use serde::{Deserialize, Serialize};
#[allow(dead_code)]
mod util { include!("util/mod.rs"); }
mod util {
include!("util/mod.rs");
}
use util::{test_get_response, test_openapi_response};
const IMAGE_RESPONSE : &[u8] = b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUA/wA0XsCoAAAAAXRSTlN/gFy0ywAAAApJREFUeJxjYgAAAAYAAzY3fKgAAAAASUVORK5CYII=";
#[derive(Resource)]
@ -28,24 +30,19 @@ struct ImageResource;
struct Image(Vec<u8>);
#[read(ImageResource, operation_id = "getImage")]
fn get_image(_id : u64) -> Raw<&'static [u8]>
{
fn get_image(_id: u64) -> Raw<&'static [u8]> {
Raw::new(IMAGE_RESPONSE, "image/png;base64".parse().unwrap())
}
#[change(ImageResource, operation_id = "setImage")]
fn set_image(_id : u64, _image : Image)
{
}
fn set_image(_id: u64, _image: Image) {}
#[derive(Resource)]
#[resource(read, search)]
struct SecretResource;
#[derive(Deserialize, Clone)]
struct AuthData
{
struct AuthData {
sub: String,
iat: u64,
exp: u64
@ -54,45 +51,38 @@ struct AuthData
type AuthStatus = gotham_restful::AuthStatus<AuthData>;
#[derive(OpenapiType, Serialize)]
struct Secret
{
struct Secret {
code: f32
}
#[derive(OpenapiType, Serialize)]
struct Secrets
{
struct Secrets {
secrets: Vec<Secret>
}
#[derive(Deserialize, OpenapiType, StateData, StaticResponseExtender)]
struct SecretQuery
{
struct SecretQuery {
date: NaiveDate,
hour: Option<u16>,
minute: Option<u16>
}
#[read(SecretResource)]
fn read_secret(auth : AuthStatus, _id : NaiveDateTime) -> AuthSuccess<Secret>
{
fn read_secret(auth: AuthStatus, _id: NaiveDateTime) -> AuthSuccess<Secret> {
auth.ok()?;
Ok(Secret { code: 4.2 })
}
#[search(SecretResource)]
fn search_secret(auth : AuthStatus, _query : SecretQuery) -> AuthSuccess<Secrets>
{
fn search_secret(auth: AuthStatus, _query: SecretQuery) -> AuthSuccess<Secrets> {
auth.ok()?;
Ok(Secrets {
secrets: vec![Secret { code: 4.2 }, Secret { code: 3.14 }]
})
}
#[test]
fn openapi_supports_scope()
{
fn openapi_supports_scope() {
let info = OpenapiInfo {
title: "This is just a test".to_owned(),
version: "1.2.3".to_owned(),
@ -110,7 +100,8 @@ fn openapi_supports_scope()
router.get_openapi("openapi");
router.resource::<SecretResource>("secret");
});
})).unwrap();
}))
.unwrap();
test_openapi_response(&server, "http://localhost/openapi", "tests/openapi_specification.json");
}

View file

@ -1,16 +1,14 @@
#![cfg(feature = "openapi")]
use gotham::{
router::builder::*,
test::TestServer
};
use gotham::{router::builder::*, test::TestServer};
use gotham_restful::*;
use mime::TEXT_PLAIN;
#[allow(dead_code)]
mod util { include!("util/mod.rs"); }
mod util {
include!("util/mod.rs");
}
use util::{test_get_response, test_openapi_response};
const RESPONSE: &[u8] = b"This is the only valid response.";
#[derive(Resource)]
@ -18,15 +16,12 @@ const RESPONSE : &[u8] = b"This is the only valid response.";
struct FooResource;
#[read_all(FooResource)]
fn read_all() -> Raw<&'static [u8]>
{
fn read_all() -> Raw<&'static [u8]> {
Raw::new(RESPONSE, TEXT_PLAIN)
}
#[test]
fn openapi_supports_scope()
{
fn openapi_supports_scope() {
let info = OpenapiInfo {
title: "Test".to_owned(),
version: "1.2.3".to_owned(),
@ -44,7 +39,8 @@ fn openapi_supports_scope()
});
router.resource::<FooResource>("foo4");
});
})).unwrap();
}))
.unwrap();
test_get_response(&server, "http://localhost/foo1", RESPONSE);
test_get_response(&server, "http://localhost/bar/foo2", RESPONSE);

View file

@ -1,16 +1,15 @@
#[macro_use] extern crate gotham_derive;
#[macro_use]
extern crate gotham_derive;
use gotham::{
router::builder::*,
test::TestServer
};
use gotham::{router::builder::*, test::TestServer};
use gotham_restful::*;
use mime::{APPLICATION_JSON, TEXT_PLAIN};
use serde::Deserialize;
mod util { include!("util/mod.rs"); }
use util::{test_get_response, test_post_response, test_put_response, test_delete_response};
mod util {
include!("util/mod.rs");
}
use util::{test_delete_response, test_get_response, test_post_response, test_put_response};
#[derive(Resource)]
#[resource(read_all, read, search, create, change_all, change, remove_all, remove)]
@ -19,88 +18,96 @@ struct FooResource;
#[derive(Deserialize)]
#[cfg_attr(feature = "openapi", derive(OpenapiType))]
#[allow(dead_code)]
struct FooBody
{
struct FooBody {
data: String
}
#[derive(Deserialize, StateData, StaticResponseExtender)]
#[cfg_attr(feature = "openapi", derive(OpenapiType))]
#[allow(dead_code)]
struct FooSearch
{
struct FooSearch {
query: String
}
const READ_ALL_RESPONSE: &[u8] = b"1ARwwSPVyOKpJKrYwqGgECPVWDl1BqajAAj7g7WJ3e";
#[read_all(FooResource)]
fn read_all() -> Raw<&'static [u8]>
{
fn read_all() -> Raw<&'static [u8]> {
Raw::new(READ_ALL_RESPONSE, TEXT_PLAIN)
}
const READ_RESPONSE: &[u8] = b"FEReHoeBKU17X2bBpVAd1iUvktFL43CDu0cFYHdaP9";
#[read(FooResource)]
fn read(_id : u64) -> Raw<&'static [u8]>
{
fn read(_id: u64) -> Raw<&'static [u8]> {
Raw::new(READ_RESPONSE, TEXT_PLAIN)
}
const SEARCH_RESPONSE: &[u8] = b"AWqcQUdBRHXKh3at4u79mdupOAfEbnTcx71ogCVF0E";
#[search(FooResource)]
fn search(_body : FooSearch) -> Raw<&'static [u8]>
{
fn search(_body: FooSearch) -> Raw<&'static [u8]> {
Raw::new(SEARCH_RESPONSE, TEXT_PLAIN)
}
const CREATE_RESPONSE: &[u8] = b"y6POY7wOMAB0jBRBw0FJT7DOpUNbhmT8KdpQPLkI83";
#[create(FooResource)]
fn create(_body : FooBody) -> Raw<&'static [u8]>
{
fn create(_body: FooBody) -> Raw<&'static [u8]> {
Raw::new(CREATE_RESPONSE, TEXT_PLAIN)
}
const CHANGE_ALL_RESPONSE: &[u8] = b"QlbYg8gHE9OQvvk3yKjXJLTSXlIrg9mcqhfMXJmQkv";
#[change_all(FooResource)]
fn change_all(_body : FooBody) -> Raw<&'static [u8]>
{
fn change_all(_body: FooBody) -> Raw<&'static [u8]> {
Raw::new(CHANGE_ALL_RESPONSE, TEXT_PLAIN)
}
const CHANGE_RESPONSE: &[u8] = b"qGod55RUXkT1lgPO8h0uVM6l368O2S0GrwENZFFuRu";
#[change(FooResource)]
fn change(_id : u64, _body : FooBody) -> Raw<&'static [u8]>
{
fn change(_id: u64, _body: FooBody) -> Raw<&'static [u8]> {
Raw::new(CHANGE_RESPONSE, TEXT_PLAIN)
}
const REMOVE_ALL_RESPONSE: &[u8] = b"Y36kZ749MRk2Nem4BedJABOZiZWPLOtiwLfJlGTwm5";
#[remove_all(FooResource)]
fn remove_all() -> Raw<&'static [u8]>
{
fn remove_all() -> Raw<&'static [u8]> {
Raw::new(REMOVE_ALL_RESPONSE, TEXT_PLAIN)
}
const REMOVE_RESPONSE: &[u8] = b"CwRzBrKErsVZ1N7yeNfjZuUn1MacvgBqk4uPOFfDDq";
#[remove(FooResource)]
fn remove(_id : u64) -> Raw<&'static [u8]>
{
fn remove(_id: u64) -> Raw<&'static [u8]> {
Raw::new(REMOVE_RESPONSE, TEXT_PLAIN)
}
#[test]
fn sync_methods()
{
fn sync_methods() {
let server = TestServer::new(build_simple_router(|router| {
router.resource::<FooResource>("foo");
})).unwrap();
}))
.unwrap();
test_get_response(&server, "http://localhost/foo", READ_ALL_RESPONSE);
test_get_response(&server, "http://localhost/foo/1", READ_RESPONSE);
test_get_response(&server, "http://localhost/foo/search?query=hello+world", SEARCH_RESPONSE);
test_post_response(&server, "http://localhost/foo", r#"{"data":"hello world"}"#, APPLICATION_JSON, CREATE_RESPONSE);
test_put_response(&server, "http://localhost/foo", r#"{"data":"hello world"}"#, APPLICATION_JSON, CHANGE_ALL_RESPONSE);
test_put_response(&server, "http://localhost/foo/1", r#"{"data":"hello world"}"#, APPLICATION_JSON, CHANGE_RESPONSE);
test_post_response(
&server,
"http://localhost/foo",
r#"{"data":"hello world"}"#,
APPLICATION_JSON,
CREATE_RESPONSE
);
test_put_response(
&server,
"http://localhost/foo",
r#"{"data":"hello world"}"#,
APPLICATION_JSON,
CHANGE_ALL_RESPONSE
);
test_put_response(
&server,
"http://localhost/foo/1",
r#"{"data":"hello world"}"#,
APPLICATION_JSON,
CHANGE_RESPONSE
);
test_delete_response(&server, "http://localhost/foo", REMOVE_ALL_RESPONSE);
test_delete_response(&server, "http://localhost/foo/1", REMOVE_RESPONSE);
}

View file

@ -2,8 +2,7 @@ use trybuild::TestCases;
#[test]
#[ignore]
fn trybuild_ui()
{
fn trybuild_ui() {
let t = TestCases::new();
// always enabled
@ -18,8 +17,7 @@ fn trybuild_ui()
t.compile_fail("tests/ui/resource_unknown_method.rs");
// require the openapi feature
if cfg!(feature = "openapi")
{
if cfg!(feature = "openapi") {
t.compile_fail("tests/ui/openapi_type_enum_with_fields.rs");
t.compile_fail("tests/ui/openapi_type_nullable_non_bool.rs");
t.compile_fail("tests/ui/openapi_type_rename_non_string.rs");