Skip to content

Commit

Permalink
Add IntoParams custom module support (#163)
Browse files Browse the repository at this point in the history
Add support for type deriving IntoParams so that it can be defined in another
module than the handler using it. Previously they needed to exists in
same module.
  • Loading branch information
juhaku authored Jun 12, 2022
1 parent 855d16a commit 597fab6
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 20 deletions.
39 changes: 39 additions & 0 deletions tests/path_derive_actix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,45 @@ fn derive_into_params_with_custom_attributes() {
}
}

#[test]
fn derive_into_params_in_another_module() {
use actix_web::{get, HttpResponse, Responder};
use utoipa::OpenApi;
pub mod params {
use serde::Deserialize;
use utoipa::IntoParams;

#[derive(Deserialize, IntoParams)]
pub struct FooParams {
pub id: String,
}
}

/// Foo test
#[utoipa::path(
responses(
(status = 200, description = "Todo foo operation success"),
)
)]
#[get("/todo/foo/{id}")]
pub async fn foo_todos(_path: Path<params::FooParams>) -> impl Responder {
HttpResponse::Ok()
}

#[derive(OpenApi, Default)]
#[openapi(handlers(foo_todos))]
struct ApiDoc;

let doc = serde_json::to_value(ApiDoc::openapi()).unwrap();
let parameters = common::get_json_path(&doc, "paths./todo/foo/{id}.get.parameters");

common::assert_json_array_len(parameters, 1);
assert_value! {parameters=>
"[0].in" = r#""path""#, "Parameter in"
"[0].name" = r#""id""#, "Parameter name"
}
}

macro_rules! test_derive_path_operations {
( $( $name:ident, $mod:ident: $operation:ident)* ) => {
$(
Expand Down
42 changes: 24 additions & 18 deletions utoipa-gen/src/ext/actix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use proc_macro_error::{abort, abort_call_site};
use quote::{format_ident, quote, quote_spanned};
use regex::{Captures, Regex};
use syn::{
parse::Parse, punctuated::Punctuated, token::Comma, Attribute, DeriveInput, FnArg,
GenericArgument, ItemFn, LitStr, Pat, PatType, PathArguments, PathSegment, Type, TypePath,
parse::Parse, punctuated::Punctuated, token::Comma, Attribute, DeriveInput, ExprPath, FnArg,
GenericArgument, ItemFn, LitStr, Pat, PatType, PathArguments, PathSegment, Type, TypeInfer,
TypePath,
};

use crate::{
Expand All @@ -24,8 +25,8 @@ use super::{

#[cfg_attr(feature = "debug", derive(Debug))]
enum Arg<'a> {
Query(&'a Ident),
Path(&'a Ident),
Query(&'a TypePath),
Path(&'a TypePath),
}

impl ArgumentResolver for PathOperations {
Expand All @@ -34,13 +35,13 @@ impl ArgumentResolver for PathOperations {
resolved_path_args: Option<Vec<ResolvedArg>>,
) -> Option<Vec<Argument<'_>>> {
let (primitive_args, non_primitive_args): (Vec<Arg>, Vec<Arg>) = Self::get_fn_args(fn_args)
.partition(|arg| matches!(arg, Arg::Path(ty) if ComponentType(ty).is_primitive()));
.partition(|arg| matches!(arg, Arg::Path(ty) if ComponentType(get_last_ident(ty).unwrap()).is_primitive()));

if let Some(resolved_args) = resolved_path_args {
let primitive_args = Self::to_value_args(resolved_args, primitive_args);
let primitive = Self::to_value_args(resolved_args, primitive_args);

Some(
primitive_args
primitive
.chain(Self::to_token_stream_args(non_primitive_args))
.collect(),
)
Expand All @@ -60,12 +61,14 @@ impl PathOperations {
Arg::Query(arg) => (arg, quote! { utoipa::openapi::path::ParameterIn::Query }),
};

let assert_ty = format_ident!("_Assert{}", &ty);
Argument::TokenStream(quote_spanned! {ty.span()=>
let ident = get_last_ident(ty).unwrap();
let path = ty;
let assert_ty = format_ident!("_Assert{}", ident);
Argument::TokenStream(quote_spanned! {ident.span()=>
{
struct #assert_ty where #ty : utoipa::IntoParams;
struct #assert_ty where #path : utoipa::IntoParams;

<#ty>::into_params(|| Some(#parameter_in))
<#path>::into_params(|| Some(#parameter_in))
}
})
})
Expand All @@ -87,7 +90,7 @@ impl PathOperations {
),
},
ident: match primitive_arg {
Arg::Path(value) => Some(value),
Arg::Path(arg_type) => get_last_ident(arg_type),
_ => {
unreachable!("Arg::Query is not reachable with primitive type")
}
Expand All @@ -106,12 +109,10 @@ impl PathOperations {
}
}

fn get_argument_types(path_segment: &PathSegment) -> impl Iterator<Item = &Ident> {
fn get_argument_types(path_segment: &PathSegment) -> impl Iterator<Item = &TypePath> {
match &path_segment.arguments {
PathArguments::AngleBracketed(angle_bracketed) => angle_bracketed
.args
.iter()
.flat_map(|arg| match arg {
PathArguments::AngleBracketed(angle_bracketed) => {
angle_bracketed.args.iter().flat_map(|arg| match arg {
GenericArgument::Type(ty) => match ty {
Type::Path(path) => vec![path],
Type::Tuple(tuple) => tuple.elems.iter().map(Self::get_type_path).collect(),
Expand All @@ -125,7 +126,7 @@ impl PathOperations {
)
}
})
.flat_map(|type_path| type_path.path.get_ident()),
}
_ => {
abort_call_site!("unexpected argument type, expected Path<...> with angle brakets")
}
Expand Down Expand Up @@ -260,3 +261,8 @@ fn is_valid_request_type(ident: Option<&Ident>) -> bool {
matches!(ident, Some(operation) if ["get", "post", "put", "delete", "head", "connect", "options", "trace", "patch"]
.iter().any(|expected_operation| operation == expected_operation))
}

#[inline]
fn get_last_ident(type_path: &TypePath) -> Option<&Ident> {
type_path.path.segments.last().map(|segment| &segment.ident)
}
3 changes: 1 addition & 2 deletions utoipa-gen/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,8 +489,7 @@ impl ToTokens for Operation<'_> {
let deprecated = self
.deprecated
.map(Into::<Deprecated>::into)
.or(Some(Deprecated::False))
.unwrap();
.unwrap_or(Deprecated::False);
tokens.extend(quote! {
.deprecated(Some(#deprecated))
});
Expand Down

0 comments on commit 597fab6

Please sign in to comment.