From 1b990acdced52069e03b0028d336dad223a76ddf Mon Sep 17 00:00:00 2001 From: Dmitry Tantsur Date: Sat, 15 Apr 2023 19:47:07 +0200 Subject: [PATCH] feat(derive): default resource_id to id when deriving PaginatedResource --- derive/src/lib.rs | 13 ++++++++++++- derive/tests/paginated_resource.rs | 8 +++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/derive/src/lib.rs b/derive/src/lib.rs index e4d3542..aada2ce 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -74,6 +74,7 @@ fn get_attr<'a>(attrs: &'a Vec, attr: &str) -> Option<&'a syn::A } fn get_id_field(input: &syn::DeriveInput) -> syn::Result<(&syn::Ident, &syn::Type)> { + let mut default_id = None; if let syn::Data::Struct(ref st) = input.data { if let syn::Fields::Named(ref fs) = st.fields { for field in &fs.named { @@ -83,6 +84,12 @@ fn get_id_field(input: &syn::DeriveInput) -> syn::Result<(&syn::Ident, &syn::Typ &field.ty, )); } + + if let Some(id) = field.ident.as_ref() { + if id == "id" { + default_id = Some((id, &field.ty)); + } + } } } else { return Err(syn::Error::new_spanned( @@ -97,7 +104,11 @@ fn get_id_field(input: &syn::DeriveInput) -> syn::Result<(&syn::Ident, &syn::Typ )); } - Err(syn::Error::new_spanned(input, "#[resource_id] missing")) + if let Some(id) = default_id { + Ok(id) + } else { + Err(syn::Error::new_spanned(input, "#[resource_id] missing")) + } } fn get_collection_name(input: &syn::DeriveInput) -> syn::Result> { diff --git a/derive/tests/paginated_resource.rs b/derive/tests/paginated_resource.rs index 4b9b95b..4a4ade3 100644 --- a/derive/tests/paginated_resource.rs +++ b/derive/tests/paginated_resource.rs @@ -4,7 +4,6 @@ use osauth_derive::PaginatedResource; #[derive(Debug, Deserialize, PaginatedResource)] struct SimpleResource { - #[resource_id] pub id: String, #[allow(dead_code)] pub not_id: String, @@ -14,13 +13,12 @@ struct SimpleResource { #[collection_name = "items"] struct RenamedResource { #[resource_id] - pub id: String, + pub uuid: String, } #[derive(Debug, Deserialize, PaginatedResource)] #[flat_collection] struct FlatResource { - #[resource_id] pub id: String, } @@ -48,13 +46,13 @@ fn test_renamed_collection() { use osauth::PaginatedResource; let res = RenamedResource { - id: "the id".into(), + uuid: "the id".into(), }; let res_id: String = res.resource_id(); assert_eq!(&res_id, "the id"); - let json = r#"{"items": [{"id": "1"}, {"id": "2"}]}"#; + let json = r#"{"items": [{"uuid": "1"}, {"uuid": "2"}]}"#; let resources: ::Root = serde_json::from_str(json).unwrap(); assert_eq!(resources.items.len(), 2);