Skip to content

Commit 4b0ce05

Browse files
committed
Setting tokio as a core dep instead of compat dep because of the generated_batch_handler which use spawn
Using ::std::vec::Vec instead of simply Vec in code-generation Adding an option to make_operation! allowing to give the path of the module containing the AppSync types, as an alternative to bringing them all in scope when separating the type and operation definitions Various small corrections
1 parent 9b9a90e commit 4b0ce05

8 files changed

Lines changed: 131 additions & 76 deletions

File tree

lambda-appsync-proc/src/internal/make_appsync/graphql.rs

Lines changed: 82 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::cell::RefCell;
33
use graphql_parser::schema::{Definition, TypeDefinition};
44
use proc_macro2::Span;
55
use quote::{quote, quote_spanned, ToTokens};
6+
use syn::Path;
67
use syn::{spanned::Spanned, LitStr};
78

89
use super::super::common::{Name, OperationKind};
@@ -83,7 +84,7 @@ impl ToTokens for Scalar {
8384

8485
enum FieldType {
8586
Overriden(syn::Type),
86-
Custom { name: Name },
87+
Custom { name: Name, path: Option<Path> },
8788
Scalar(Scalar),
8889
List(Box<FieldType>),
8990
Optionnal(Box<FieldType>),
@@ -94,7 +95,7 @@ impl FieldType {
9495
Self::Scalar(scalar)
9596
} else {
9697
let name = Name::from((name, graphql_path_span()));
97-
Self::Custom { name }
98+
Self::Custom { name, path: None }
9899
}
99100
}
100101
fn is_optionnal(&self) -> bool {
@@ -109,6 +110,16 @@ impl FieldType {
109110
FieldType::Optionnal(field_type) => field_type.override_type(type_override),
110111
}
111112
}
113+
fn add_path(&mut self, p: &Path) {
114+
match self {
115+
FieldType::Custom { path, .. } => {
116+
path.replace(p.clone());
117+
}
118+
FieldType::Overriden(_) | FieldType::Scalar(_) => {}
119+
FieldType::List(field_type) => field_type.add_path(p),
120+
FieldType::Optionnal(field_type) => field_type.add_path(p),
121+
}
122+
}
112123
}
113124
impl From<graphql_parser::schema::Type<'_, String>> for FieldType {
114125
fn from(value: graphql_parser::schema::Type<'_, String>) -> Self {
@@ -138,12 +149,17 @@ impl ToTokens for FieldType {
138149
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
139150
let span = graphql_path_span();
140151
match self {
141-
FieldType::Custom { name } => {
152+
FieldType::Custom { name, path } => {
153+
if let Some(path) = path {
154+
tokens.extend(quote_spanned! {span=>#path::})
155+
}
142156
let name = name.to_type_ident();
143157
tokens.extend(quote_spanned! {span=>#name})
144158
}
145159
FieldType::Scalar(scalar) => tokens.extend(quote_spanned! {span=>#scalar}),
146-
FieldType::List(field_type) => tokens.extend(quote_spanned! {span=>Vec<#field_type>}),
160+
FieldType::List(field_type) => {
161+
tokens.extend(quote_spanned! {span=>::std::vec::Vec<#field_type>})
162+
}
147163
FieldType::Optionnal(field_type) => {
148164
tokens.extend(quote_spanned! {span=>::core::option::Option<#field_type>})
149165
}
@@ -605,6 +621,12 @@ impl Operation {
605621
.expect("not empty"))
606622
}
607623
}
624+
fn apply_type_module_path(&mut self, path: &Path) {
625+
for arg in self.args.iter_mut() {
626+
arg.field_type.add_path(path);
627+
}
628+
self.return_type.add_path(path);
629+
}
608630
}
609631
impl From<graphql_parser::schema::Field<'_, String>> for Operation {
610632
fn from(value: graphql_parser::schema::Field<'_, String>) -> Self {
@@ -687,6 +709,12 @@ impl Operations {
687709
.expect("not empty"))
688710
}
689711
}
712+
713+
fn apply_type_module_path(&mut self, path: &Path) {
714+
for op in self.0.iter_mut() {
715+
op.apply_type_module_path(path);
716+
}
717+
}
690718
}
691719

692720
#[derive(Debug)]
@@ -743,7 +771,8 @@ pub(super) struct GraphQLSchema {
743771
impl GraphQLSchema {
744772
pub(super) fn new(
745773
graphql_schema_path: LitStr,
746-
overrides: OverrideParameters,
774+
override_parameters: OverrideParameters,
775+
custom_type_module: Option<Path>,
747776
) -> Result<Self, syn::Error> {
748777
let mut queries = None;
749778
let mut mutations = None;
@@ -803,24 +832,28 @@ impl GraphQLSchema {
803832
let OverrideParameters {
804833
mut type_overrides,
805834
mut name_overrides,
806-
} = overrides;
835+
} = override_parameters;
807836

808837
let mut errors = vec![];
809838
for definition in graphql_schema.definitions {
810839
match definition {
811840
Definition::TypeDefinition(type_definition) => {
812841
match type_definition {
813842
TypeDefinition::Object(object_type) => {
814-
if let Some(sdt) = sd.schema_definition(&object_type.name) {
843+
if let Some(op_kind) = sd.schema_definition(&object_type.name) {
844+
// This is an Object defining operations
815845
let type_overrides = type_overrides.remove(&object_type.name);
816846
let mut ops = Operations::from(object_type);
847+
if let Some(ref custom_type_module) = custom_type_module {
848+
ops.apply_type_module_path(custom_type_module);
849+
}
817850
if let Some(type_overrides) = type_overrides {
818851
match ops.apply_type_overrides(type_overrides) {
819852
Ok(_) => (),
820853
Err(e) => errors.push(e),
821854
};
822855
}
823-
match sdt {
856+
match op_kind {
824857
OperationKind::Query => {
825858
queries.replace(ops);
826859
}
@@ -832,6 +865,7 @@ impl GraphQLSchema {
832865
}
833866
}
834867
} else {
868+
// This is an object defining a structure-style type
835869
let mut structure = Structure::from(object_type);
836870
if let Some(type_overrides) =
837871
type_overrides.remove(structure.name.orig())
@@ -902,33 +936,46 @@ impl GraphQLSchema {
902936
}
903937
}
904938

905-
if !type_overrides.is_empty() {
906-
errors.extend(
907-
type_overrides
908-
.into_values()
909-
.flat_map(|fos| fos.into_values())
910-
.flat_map(|fo| fo.0.into_iter().chain(fo.1.into_values()))
911-
.map(|to| {
912-
syn::Error::new(
913-
to.type_name().span(),
914-
format!("No type or input named `{}`", to.type_name()),
915-
)
916-
}),
917-
);
918-
}
919-
if !name_overrides.is_empty() {
920-
errors.extend(
921-
name_overrides
922-
.into_values()
923-
.flat_map(|no| no.0.into_iter().chain(no.1.into_values()))
924-
.map(|no| {
925-
syn::Error::new(
926-
no.type_name().span(),
927-
format!("No type, enum or input named `{}`", no.type_name()),
928-
)
929-
}),
930-
);
931-
}
939+
// Add an error for each un-matched type_override
940+
errors.extend(
941+
type_overrides
942+
.into_values()
943+
.flat_map(|field_type_overrides| field_type_overrides.into_values())
944+
.flat_map(|field_type_override| {
945+
field_type_override
946+
.0
947+
.into_iter()
948+
.chain(field_type_override.1.into_values())
949+
})
950+
.map(|type_override| {
951+
syn::Error::new(
952+
type_override.type_name().span(),
953+
format!("No type or input named `{}`", type_override.type_name()),
954+
)
955+
}),
956+
);
957+
958+
// Add an error for each un-matched name_override
959+
errors.extend(
960+
name_overrides
961+
.into_values()
962+
.flat_map(|name_overrides| {
963+
name_overrides
964+
.0
965+
.into_iter()
966+
.chain(name_overrides.1.into_values())
967+
})
968+
.map(|name_override| {
969+
syn::Error::new(
970+
name_override.type_name().span(),
971+
format!(
972+
"No type, enum or input named `{}`",
973+
name_override.type_name()
974+
),
975+
)
976+
}),
977+
);
978+
932979
if errors.is_empty() {
933980
Ok(Self {
934981
queries: queries.unwrap_or_default(),

lambda-appsync-proc/src/internal/make_appsync/legacy/appsync_lambda_main.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ impl Parse for AppsyncLambdaMain {
255255
type_overrides: std::mem::take(&mut parameters.tos),
256256
name_overrides: std::mem::take(&mut parameters.nos),
257257
},
258+
None,
258259
)?;
259260

260261
Ok(Self {
@@ -319,12 +320,12 @@ impl AppsyncLambdaMain {
319320
if self.options.batch {
320321
tokens.extend(quote! {
321322
async fn appsync_batch_handler(
322-
events: Vec<::lambda_appsync::AppsyncEvent<Operation>>,
323-
) -> Vec<::lambda_appsync::AppsyncResponse> {
323+
events: ::std::vec::Vec<::lambda_appsync::AppsyncEvent<Operation>>,
324+
) -> ::std::vec::Vec<::lambda_appsync::AppsyncResponse> {
324325
let handles = events
325326
.into_iter()
326327
.map(|e| ::lambda_appsync::tokio::spawn(appsync_handler(e)))
327-
.collect::<Vec<_>>();
328+
.collect::<::std::vec::Vec<_>>();
328329

329330
let mut results = vec![];
330331
for h in handles {
@@ -374,7 +375,7 @@ impl AppsyncLambdaMain {
374375
let (appsync_handler, ret_type) = if self.options.batch {
375376
(
376377
format_ident!("appsync_batch_handler"),
377-
quote! {Vec<::lambda_appsync::AppsyncResponse>},
378+
quote! {::std::vec::Vec<::lambda_appsync::AppsyncResponse>},
378379
)
379380
} else {
380381
(

lambda-appsync-proc/src/internal/make_appsync/make_handlers.rs

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -91,14 +91,14 @@ impl ToTokens for MakeHandlers {
9191
batch_handler.extend(quote! {
9292
#[doc = "Handles a batch of [lambda_appsync::AppsyncEvent<Operation>] concurrently."]
9393
async fn appsync_batch_handler(
94-
events: Vec<::lambda_appsync::AppsyncEvent<#operation>>
95-
) -> Vec<::lambda_appsync::AppsyncResponse> {
94+
events: ::std::vec::Vec<::lambda_appsync::AppsyncEvent<#operation>>
95+
) -> ::std::vec::Vec<::lambda_appsync::AppsyncResponse> {
9696
let handles = events
9797
.into_iter()
9898
.map(|e| ::lambda_appsync::tokio::spawn(Self::appsync_handler(e)))
99-
.collect::<Vec<_>>();
99+
.collect::<::std::vec::Vec<_>>();
100100

101-
let mut results = vec![];
101+
let mut results = ::std::vec::Vec::new();
102102
for h in handles {
103103
results.push(h.await.unwrap())
104104
}
@@ -119,16 +119,28 @@ impl ToTokens for MakeHandlers {
119119
)
120120
};
121121

122+
let appsync_handler = if self.batch {
123+
quote! {
124+
fn appsync_handler(
125+
event: ::lambda_appsync::AppsyncEvent<#operation>
126+
) -> impl std::future::Future<Output = ::lambda_appsync::AppsyncResponse> + Send + 'static {
127+
event.info.operation.execute(event)
128+
}
129+
}
130+
} else {
131+
quote! {
132+
async fn appsync_handler(event: ::lambda_appsync::AppsyncEvent<#operation>) -> ::lambda_appsync::AppsyncResponse {
133+
event.info.operation.execute(event).await
134+
}
135+
}
136+
};
137+
122138
tokens.extend(quote! {
123139

124140
#[deny(dead_code)]
125141
trait Handlers {
126142
#[doc = "Handles a single deserialized [lambda_appsync::AppsyncEvent<Operation>]."]
127-
async fn appsync_handler(
128-
event: ::lambda_appsync::AppsyncEvent<#operation>
129-
) -> ::lambda_appsync::AppsyncResponse {
130-
event.info.operation.execute(event).await
131-
}
143+
#appsync_handler
132144

133145
#batch_handler
134146

lambda-appsync-proc/src/internal/make_appsync/make_operation.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,43 @@ use proc_macro2::TokenStream as TokenStream2;
22
use quote::ToTokens;
33
use syn::{
44
parse::{Parse, ParseStream},
5-
parse_macro_input, LitStr, Result, Token,
5+
parse_macro_input, LitStr, Path, Result, Token,
66
};
77

88
use super::{
99
optional_parameter::{OptionalParameter, OptionalParameters, ParameterError, Unknown},
1010
GraphQLSchema, OverrideParameters,
1111
};
1212

13-
pub(super) enum MakeOperationParameter {}
13+
pub(super) enum MakeOperationParameter {
14+
TypeModule(Path),
15+
}
1416
impl OptionalParameter for MakeOperationParameter {
1517
fn try_parse_parameter(input: ParseStream) -> core::result::Result<Self, ParameterError> {
1618
let ident = Self::parse_ident(input)?;
1719
#[allow(clippy::match_single_binding)]
1820
match ident.to_string().as_str() {
21+
"type_module" => Ok(Self::TypeModule(input.parse()?)),
1922
// Unknown option
2023
_ => ident.unknown(),
2124
}
2225
}
2326
}
2427

2528
#[derive(Default)]
26-
pub(super) struct MakeOperationParameters {}
29+
pub(super) struct MakeOperationParameters {
30+
type_module: Option<Path>,
31+
}
2732
impl OptionalParameters<MakeOperationParameter> for MakeOperationParameters {
2833
fn set_param(&mut self, p: MakeOperationParameter) {
29-
match p {}
34+
match p {
35+
MakeOperationParameter::TypeModule(path) => self.type_module = Some(path),
36+
}
3037
}
3138
}
3239

3340
struct MakeOperation {
3441
graphql_schema: GraphQLSchema,
35-
#[allow(dead_code)]
36-
parameters: MakeOperationParameters,
3742
}
3843

3944
impl Parse for MakeOperation {
@@ -64,12 +69,13 @@ impl Parse for MakeOperation {
6469
parameters.try_parse_parameter(input)?;
6570
}
6671

67-
let graphql_schema = GraphQLSchema::new(graphql_schema_path, override_parameters)?;
72+
let graphql_schema = GraphQLSchema::new(
73+
graphql_schema_path,
74+
override_parameters,
75+
parameters.type_module,
76+
)?;
6877

69-
Ok(Self {
70-
graphql_schema,
71-
parameters,
72-
})
78+
Ok(Self { graphql_schema })
7379
}
7480
}
7581

lambda-appsync-proc/src/internal/make_appsync/make_types.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,6 @@ impl OptionalParameters<MakeTypesParameter> for MakeTypesParameters {
3232

3333
struct MakeTypes {
3434
graphql_schema: GraphQLSchema,
35-
#[allow(dead_code)]
36-
parameters: MakeTypesParameters,
3735
}
3836

3937
impl Parse for MakeTypes {
@@ -64,12 +62,9 @@ impl Parse for MakeTypes {
6462
parameters.try_parse_parameter(input)?;
6563
}
6664

67-
let graphql_schema = GraphQLSchema::new(graphql_schema_path, override_parameters)?;
65+
let graphql_schema = GraphQLSchema::new(graphql_schema_path, override_parameters, None)?;
6866

69-
Ok(Self {
70-
graphql_schema,
71-
parameters,
72-
})
67+
Ok(Self { graphql_schema })
7368
}
7469
}
7570

0 commit comments

Comments
 (0)