Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: custom ser/de for scalars #980

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 41 additions & 9 deletions cynic-codegen/src/fragment_derive/deserialize_impl.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use proc_macro2::TokenStream;
use quote::quote_spanned;

use crate::schema::{types::OutputType, Schema, Unvalidated};

Check warning on line 4 in cynic-codegen/src/fragment_derive/deserialize_impl.rs

View workflow job for this annotation

GitHub Actions / build-rust

unused import: `types::OutputType`

Check warning on line 4 in cynic-codegen/src/fragment_derive/deserialize_impl.rs

View workflow job for this annotation

GitHub Actions / build-rust

unused import: `types::OutputType`

use super::FieldKind;

use {
super::FragmentDeriveField,
crate::{generics_for_serde, schema::types as schema},
Expand Down Expand Up @@ -28,6 +32,8 @@
ty: syn::Type,
field_variant_name: proc_macro2::Ident,
serialized_name: Option<String>,
inner_kind: Option<FieldKind>,
field_marker: syn::Path,
is_spread: bool,
is_flattened: bool,
is_recurse: bool,
Expand All @@ -36,16 +42,20 @@

impl<'a> DeserializeImpl<'a> {
pub fn new(
schema: &Schema<'_, Unvalidated>,
fields: &[(FragmentDeriveField, Option<schema::Field<'_>>)],
name: &'a syn::Ident,
generics: &'a syn::Generics,
field_module_path: &syn::Path,
) -> Self {
let spreading = fields.iter().any(|f| *f.0.spread);

let target_struct = name;
let fields = fields
.iter()
.map(|(field, schema_field)| process_field(field, schema_field.as_ref()))
.map(|(field, schema_field)| {
process_field(schema, field, schema_field.as_ref(), field_module_path)
})
.collect();

match spreading {
Expand Down Expand Up @@ -96,15 +106,23 @@
let field_names = self.fields.iter().map(|f| &f.rust_name).collect::<Vec<_>>();
let field_decodes = self.fields.iter().map(|f| {
let field_name = &f.rust_name;
let field_marker = &f.field_marker;
let ty = &f.ty;
let mut ty = quote! { #ty };
let mut trailer = quote! {};

if matches!(f.inner_kind, Some(FieldKind::Scalar)) {
ty = quote! { cynic::__private::ScalarDeserialize<#ty, <#field_marker as cynic::schema::Field>::Type> };
trailer.append_all(quote! { .into_inner() });
}

if f.is_flattened {
quote! {
#field_name = Some(__map.next_value::<cynic::__private::Flattened<#ty>>()?.into_inner());
}
} else {
quote! {
#field_name = Some(__map.next_value()?);
}
ty = quote! { cynic::__private::Flattened<#ty> };
trailer.append_all(quote! { .into_inner() });
}

quote! {
#field_name = Some(__map.next_value::<#ty>()? #trailer);
}
});

Expand Down Expand Up @@ -267,10 +285,22 @@
}
}

fn process_field(field: &FragmentDeriveField, schema_field: Option<&schema::Field<'_>>) -> Field {
fn process_field(
schema: &Schema<'_, Unvalidated>,
field: &FragmentDeriveField,
schema_field: Option<&schema::Field<'_>>,
field_module_path: &syn::Path,
) -> Field {
// Should be ok to unwrap since we only accept struct style input
let rust_name = field.ident.as_ref().unwrap();
let field_variant_name = rust_name.clone();
let schema_type = schema_field.map(|field| field.field_type.inner_type(schema));
let inner_kind = schema_type.as_ref().map(|ty| ty.as_kind());

let field_marker = match schema_field {
Some(field) => field.marker_ident().to_path(field_module_path),
None => syn::parse_quote!(String),
};

Field {
field_variant_name,
Expand All @@ -283,5 +313,7 @@
is_flattened: *field.flatten,
is_recurse: field.recurse.is_some(),
is_feature_flagged: field.feature.is_some(),
inner_kind,
field_marker,
}
}
26 changes: 8 additions & 18 deletions cynic-codegen/src/fragment_derive/fragment_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use super::{
arguments::{arguments_from_field_attrs, process_arguments},
fragment_derive_type::FragmentDeriveType,
FieldKind,
};

use super::input::FragmentDeriveField;
Expand Down Expand Up @@ -54,14 +55,6 @@
span: proc_macro2::Span,
}

enum FieldKind {
Composite,
Scalar,
Enum,
Interface,
Union,
}

impl<'schema, 'a: 'schema> FragmentImpl<'schema, 'a> {
#[allow(clippy::too_many_arguments)]
pub fn new_for(
Expand Down Expand Up @@ -263,10 +256,10 @@
}
}
FieldKind::Scalar if self.flatten => quote_spanned! { self.span =>
<#aligned_type as cynic::schema::IsScalar<#aligned_type>>::SchemaType
<#aligned_type as cynic::schema::IsOutputScalar<#aligned_type>>::SchemaType
},
FieldKind::Scalar => quote_spanned! { self.span =>
<#aligned_type as cynic::schema::IsScalar<
<#aligned_type as cynic::schema::IsOutputScalar<
<#field_marker_type_path as cynic::schema::Field>::Type
>>::SchemaType
},
Expand Down Expand Up @@ -383,13 +376,10 @@
}

impl OutputType<'_> {
fn as_kind(&self) -> FieldKind {
match self {
OutputType::Scalar(_) => FieldKind::Scalar,
OutputType::Enum(_) => FieldKind::Enum,
OutputType::Object(_) => FieldKind::Composite,
OutputType::Interface(_) => FieldKind::Interface,
OutputType::Union(_) => FieldKind::Union,
}
fn is_composite(&self) -> bool {

Check warning on line 379 in cynic-codegen/src/fragment_derive/fragment_impl.rs

View workflow job for this annotation

GitHub Actions / build-rust

method `is_composite` is never used

Check warning on line 379 in cynic-codegen/src/fragment_derive/fragment_impl.rs

View workflow job for this annotation

GitHub Actions / build-rust

method `is_composite` is never used
matches!(
self,
OutputType::Object(_) | OutputType::Interface(_) | OutputType::Union(_)
)
}
}
33 changes: 31 additions & 2 deletions cynic-codegen/src/fragment_derive/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use proc_macro2::{Span, TokenStream};

use crate::{
schema::{
types::{self as schema},
types::{self as schema, OutputType},
Schema,
},
suggestions::FieldSuggestionError,
Expand Down Expand Up @@ -63,7 +63,15 @@ pub fn fragment_derive_impl(input: FragmentDeriveInput) -> Result<TokenStream, E
variables.as_ref(),
)?;

let deserialize_impl = DeserializeImpl::new(&fields, &input.ident, &input.generics);
let field_module_path = schema_type.field_module.to_path(&schema_module);

let deserialize_impl = DeserializeImpl::new(
&schema,
&fields,
&input.ident,
&input.generics,
&field_module_path,
);

Ok(quote::quote! {
#fragment_impl
Expand Down Expand Up @@ -123,5 +131,26 @@ fn pair_fields<'a>(
Err(errors)
}

impl OutputType<'_> {
fn as_kind(&self) -> FieldKind {
match self {
OutputType::Scalar(_) => FieldKind::Scalar,
OutputType::Enum(_) => FieldKind::Enum,
OutputType::Object(_) => FieldKind::Composite,
OutputType::Interface(_) => FieldKind::Interface,
OutputType::Union(_) => FieldKind::Union,
}
}
}

#[derive(Clone, Copy)]
enum FieldKind {
Composite,
Scalar,
Enum,
Interface,
Union,
}

#[cfg(test)]
mod tests;
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ impl<'de> cynic::serde::Deserialize<'de> for MyQuery {
if post.is_some() {
return Err(cynic::serde::de::Error::duplicate_field("post"));
}
post = Some(__map.next_value()?);
post = Some(__map.next_value::<Option<BlogPostOutput>>()?);
}
__FragmentDeriveField::posts => {
if posts.is_some() {
return Err(cynic::serde::de::Error::duplicate_field("allPosts"));
}
posts = Some(__map.next_value()?);
posts = Some(__map.next_value::<Vec<BlogPostOutput>>()?);
}
__FragmentDeriveField::__Other => {
__map.next_value::<cynic::serde::de::IgnoredAny>()?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl<'de> cynic::serde::Deserialize<'de> for MyQuery {
"filteredPosts",
));
}
filteredPosts = Some(__map.next_value()?);
filteredPosts = Some(__map.next_value::<Vec<BlogPostOutput>>()?);
}
__FragmentDeriveField::__Other => {
__map.next_value::<cynic::serde::de::IgnoredAny>()?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ impl cynic::QueryFragment for MyQuery {
mut builder: cynic::queries::SelectionBuilder<'_, Self::SchemaType, Self::VariablesFields>,
) {
#![allow(unused_mut)]
let mut field_builder = builder
.select_field::<schema::__fields::Query::__typename, <String as cynic::schema::IsScalar<
<schema::__fields::Query::__typename as cynic::schema::Field>::Type,
>>::SchemaType>();
let mut field_builder = builder . select_field :: < schema :: __fields :: Query :: __typename , < String as cynic :: schema :: IsOutputScalar < < schema :: __fields :: Query :: __typename as cynic :: schema :: Field > :: Type >> :: SchemaType > () ;
if builder.is_feature_enabled("2018") {
let mut field_builder = builder . select_field :: < schema :: __fields :: Query :: filteredPosts , < Vec < BlogPostOutput > as cynic :: QueryFragment > :: SchemaType > () ;
<Vec<BlogPostOutput> as cynic::QueryFragment>::query(field_builder.select_children());
Expand Down Expand Up @@ -62,15 +59,15 @@ impl<'de> cynic::serde::Deserialize<'de> for MyQuery {
if __typename.is_some() {
return Err(cynic::serde::de::Error::duplicate_field("__typename"));
}
__typename = Some(__map.next_value()?);
__typename = Some (__map . next_value :: < cynic :: __private :: ScalarDeserialize < String , < schema :: __fields :: Query :: __typename as cynic :: schema :: Field > :: Type > > () ? . into_inner ()) ;
}
__FragmentDeriveField::filteredPosts => {
if filteredPosts.is_some() {
return Err(cynic::serde::de::Error::duplicate_field(
"filteredPosts",
));
}
filteredPosts = Some(__map.next_value()?);
filteredPosts = Some(__map.next_value::<Vec<BlogPostOutput>>()?);
}
__FragmentDeriveField::__Other => {
__map.next_value::<cynic::serde::de::IgnoredAny>()?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ impl cynic::QueryFragment for Film {
mut builder: cynic::queries::SelectionBuilder<'_, Self::SchemaType, Self::VariablesFields>,
) {
#![allow(unused_mut)]
let mut field_builder = builder . select_flattened_field :: < schema :: __fields :: Film :: producers , < Vec < String > as cynic :: schema :: IsScalar < Vec < String > >> :: SchemaType , < schema :: __fields :: Film :: producers as cynic :: schema :: Field > :: Type , > () ;
let mut field_builder = builder . select_flattened_field :: < schema :: __fields :: Film :: producers , < Vec < String > as cynic :: schema :: IsOutputScalar < Vec < String > >> :: SchemaType , < schema :: __fields :: Film :: producers as cynic :: schema :: Field > :: Type , > () ;
}
fn name() -> Option<std::borrow::Cow<'static, str>> {
Some(std::borrow::Cow::Borrowed("Film"))
Expand Down Expand Up @@ -52,11 +52,7 @@ impl<'de> cynic::serde::Deserialize<'de> for Film {
if producers.is_some() {
return Err(cynic::serde::de::Error::duplicate_field("producers"));
}
producers = Some(
__map
.next_value::<cynic::__private::Flattened<Vec<String>>>()?
.into_inner(),
);
producers = Some (__map . next_value :: < cynic :: __private :: Flattened < cynic :: __private :: ScalarDeserialize < Vec < String > , < schema :: __fields :: Film :: producers as cynic :: schema :: Field > :: Type > > > () ? . into_inner () . into_inner ()) ;
}
__FragmentDeriveField::__Other => {
__map.next_value::<cynic::serde::de::IgnoredAny>()?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl<'de> cynic::serde::Deserialize<'de> for MyQuery {
"filteredPosts",
));
}
filteredPosts = Some(__map.next_value()?);
filteredPosts = Some(__map.next_value::<Vec<BlogPostOutput>>()?);
}
__FragmentDeriveField::__Other => {
__map.next_value::<cynic::serde::de::IgnoredAny>()?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ impl cynic::QueryFragment for BlogPostOutput {
mut builder: cynic::queries::SelectionBuilder<'_, Self::SchemaType, Self::VariablesFields>,
) {
#![allow(unused_mut)]
let mut field_builder = builder . select_field :: < schema :: __fields :: BlogPost :: hasMetadata , < Option < bool > as cynic :: schema :: IsScalar < < schema :: __fields :: BlogPost :: hasMetadata as cynic :: schema :: Field > :: Type >> :: SchemaType > () ;
let mut field_builder = builder . select_field :: < schema :: __fields :: BlogPost :: hasMetadata , < Option < bool > as cynic :: schema :: IsOutputScalar < < schema :: __fields :: BlogPost :: hasMetadata as cynic :: schema :: Field > :: Type >> :: SchemaType > () ;
let mut field_builder = builder . select_field :: < schema :: __fields :: BlogPost :: author , < AuthorOutput as cynic :: QueryFragment > :: SchemaType > () ;
<AuthorOutput as cynic::QueryFragment>::query(field_builder.select_children());
}
Expand Down Expand Up @@ -59,13 +59,13 @@ impl<'de> cynic::serde::Deserialize<'de> for BlogPostOutput {
"hasMetadata",
));
}
has_metadata = Some(__map.next_value()?);
has_metadata = Some (__map . next_value :: < cynic :: __private :: ScalarDeserialize < Option < bool > , < schema :: __fields :: BlogPost :: hasMetadata as cynic :: schema :: Field > :: Type > > () ? . into_inner ()) ;
}
__FragmentDeriveField::author => {
if author.is_some() {
return Err(cynic::serde::de::Error::duplicate_field("author"));
}
author = Some(__map.next_value()?);
author = Some(__map.next_value::<AuthorOutput>()?);
}
__FragmentDeriveField::__Other => {
__map.next_value::<cynic::serde::de::IgnoredAny>()?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ impl cynic::QueryFragment for Film {
mut builder: cynic::queries::SelectionBuilder<'_, Self::SchemaType, Self::VariablesFields>,
) {
#![allow(unused_mut)]
let mut field_builder = builder . select_field :: < schema :: __fields :: Film :: releaseDate , < Option < String > as cynic :: schema :: IsScalar < < schema :: __fields :: Film :: releaseDate as cynic :: schema :: Field > :: Type >> :: SchemaType > () ;
let mut field_builder = builder . select_field :: < schema :: __fields :: Film :: releaseDate , < Option < String > as cynic :: schema :: IsOutputScalar < < schema :: __fields :: Film :: releaseDate as cynic :: schema :: Field > :: Type >> :: SchemaType > () ;
<FilmDetails as cynic::QueryFragment>::query(
builder
.inline_fragment()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl cynic::QueryFragment for Film {
.inline_fragment()
.select_children::<<FilmDetails as cynic::QueryFragment>::VariablesFields>(),
);
let mut field_builder = builder . select_field :: < schema :: __fields :: Film :: releaseDate , < Option < String > as cynic :: schema :: IsScalar < < schema :: __fields :: Film :: releaseDate as cynic :: schema :: Field > :: Type >> :: SchemaType > () ;
let mut field_builder = builder . select_field :: < schema :: __fields :: Film :: releaseDate , < Option < String > as cynic :: schema :: IsOutputScalar < < schema :: __fields :: Film :: releaseDate as cynic :: schema :: Field > :: Type >> :: SchemaType > () ;
}
fn name() -> Option<std::borrow::Cow<'static, str>> {
Some(std::borrow::Cow::Borrowed("Film"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl<'de> cynic::serde::Deserialize<'de> for MyQuery {
"filteredPosts",
));
}
filteredPosts = Some(__map.next_value()?);
filteredPosts = Some(__map.next_value::<Vec<BlogPostOutput>>()?);
}
__FragmentDeriveField::__Other => {
__map.next_value::<cynic::serde::de::IgnoredAny>()?;
Expand Down
19 changes: 19 additions & 0 deletions cynic-codegen/src/scalar_derive/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,25 @@ pub fn scalar_derive_impl(input: ScalarDeriveInput) -> Result<TokenStream, syn::
#[automatically_derived]
impl #impl_generics cynic::schema::IsScalar<#marker_ident> for #ident #ty_generics #where_clause {
type SchemaType = #marker_ident;

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: cynic::serde::Serializer
{
cynic::serde::Serialize::serialize(self, serializer)
}
}

#[automatically_derived]
impl #impl_generics cynic::schema::IsOutputScalar<#marker_ident> for #ident #ty_generics #where_clause {
type SchemaType = #marker_ident;

fn deserialize<'de, D>(deserializer: D) -> Result<Self, D::Error>
where
D: cynic::serde::Deserializer<'de>
{
<Self as cynic::serde::Deserialize>::deserialize(deserializer)
}
}

#[automatically_derived]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,22 @@ impl<'de> cynic::serde::Deserialize<'de> for DateTime {
#[automatically_derived]
impl cynic::schema::IsScalar<schema::DateTime> for DateTime {
type SchemaType = schema::DateTime;
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: cynic::serde::Serializer,
{
cynic::serde::Serialize::serialize(self, serializer)
}
}
#[automatically_derived]
impl cynic::schema::IsOutputScalar<schema::DateTime> for DateTime {
type SchemaType = schema::DateTime;
fn deserialize<'de, D>(deserializer: D) -> Result<Self, D::Error>
where
D: cynic::serde::Deserializer<'de>,
{
<Self as cynic::serde::Deserialize>::deserialize(deserializer)
}
}
#[automatically_derived]
impl schema::variable::Variable for DateTime {
Expand Down
Loading
Loading