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

Changed Lookahead to support multiple fields #574

Merged
merged 2 commits into from
Jul 15, 2021
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

- Add binary types to `ConstValue` and `Value`. [#569](https://github.com/async-graphql/async-graphql/issues/569)
- Changed Lookahead to support multiple fields. [#574](https://github.com/async-graphql/async-graphql/issues/547)

## [2.9.8] 2021-07-12

Expand Down
120 changes: 95 additions & 25 deletions src/look_ahead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{Name, Positioned, SelectionField};
/// A selection performed by a query.
pub struct Lookahead<'a> {
fragments: &'a HashMap<Name, Positioned<FragmentDefinition>>,
field: Option<&'a Field>,
fields: Vec<&'a Field>,
}

impl<'a> Lookahead<'a> {
Expand All @@ -16,63 +16,68 @@ impl<'a> Lookahead<'a> {
) -> Self {
Self {
fragments,
field: Some(field),
fields: vec![field],
}
}

/// Get the first subfield of the selection set with the specified name. This will ignore
/// Get the field of the selection set with the specified name. This will ignore
/// aliases.
///
/// For example, calling `.field("a")` on `{ a { b } }` will return a lookahead that
/// represents `{ b }`.
pub fn field(&self, name: &str) -> Self {
let mut fields = Vec::new();
for field in &self.fields {
filter(&mut fields, self.fragments, &field.selection_set.node, name)
}

Self {
fragments: self.fragments,
field: self
.field
.and_then(|field| find(self.fragments, &field.selection_set.node, name)),
fields,
}
}

/// Returns true if field exists otherwise return false.
#[inline]
pub fn exists(&self) -> bool {
self.field.is_some()
!self.fields.is_empty()
}
}

impl<'a> From<SelectionField<'a>> for Lookahead<'a> {
fn from(selection_field: SelectionField<'a>) -> Self {
Lookahead {
fragments: selection_field.fragments,
field: Some(selection_field.field),
fields: vec![selection_field.field],
}
}
}

fn find<'a>(
fn filter<'a>(
fields: &mut Vec<&'a Field>,
fragments: &'a HashMap<Name, Positioned<FragmentDefinition>>,
selection_set: &'a SelectionSet,
name: &str,
) -> Option<&'a Field> {
selection_set
.items
.iter()
.find_map(|item| match &item.node {
) {
for item in &selection_set.items {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've done this imperatively. Tried doing this with iterators but I'm pretty sure you need to use a Box<dyn Iterator> because it's recursive. Happy to change if there's a better way though.

// doing this imperatively is a bit nasty, but using iterators would
// require a boxed return type (I believe) as its recusive
match &item.node {
Selection::Field(field) => {
if field.node.name.node == name {
Some(&field.node)
} else {
None
fields.push(&field.node)
}
}
Selection::InlineFragment(fragment) => {
find(fragments, &fragment.node.selection_set.node, name)
filter(fields, fragments, &fragment.node.selection_set.node, name)
}
Selection::FragmentSpread(spread) => {
if let Some(fragment) = fragments.get(&spread.node.fragment_name.node) {
filter(fields, fragments, &fragment.node.selection_set.node, name)
}
}
Selection::FragmentSpread(spread) => fragments
.get(&spread.node.fragment_name.node)
.and_then(|fragment| find(fragments, &fragment.node.selection_set.node, name)),
})
}
}
}

#[cfg(test)]
Expand Down Expand Up @@ -104,12 +109,17 @@ mod tests {
if ctx.look_ahead().field("a").exists() {
// This is a query like `obj { a }`
assert_eq!(n, 1);
} else if ctx.look_ahead().field("detail").field("c").exists() {
} else if ctx.look_ahead().field("detail").field("c").exists()
&& ctx.look_ahead().field("detail").field("d").exists()
{
// This is a query like `obj { detail { c } }`
assert_eq!(n, 2);
} else if ctx.look_ahead().field("detail").field("c").exists() {
// This is a query like `obj { detail { c } }`
assert_eq!(n, 3);
} else {
// This query doesn't have `a`
assert_eq!(n, 3);
assert_eq!(n, 4);
}
MyObj {
a: 0,
Expand Down Expand Up @@ -143,10 +153,27 @@ mod tests {
.await
.is_ok());

assert!(schema
.execute(
r#"{
obj(n: 3) {
detail {
c
}
}
}"#,
)
.await
.is_ok());

assert!(schema
.execute(
r#"{
obj(n: 2) {
detail {
d
}

detail {
c
}
Expand All @@ -159,7 +186,7 @@ mod tests {
assert!(schema
.execute(
r#"{
obj(n: 3) {
obj(n: 4) {
b
}
}"#,
Expand All @@ -180,11 +207,30 @@ mod tests {
.await
.is_ok());

assert!(schema
.execute(
r#"{
obj(n: 3) {
... {
detail {
c
}
}
}
}"#,
)
.await
.is_ok());

assert!(schema
.execute(
r#"{
obj(n: 2) {
... {
detail {
d
}

detail {
c
}
Expand All @@ -210,15 +256,39 @@ mod tests {
.await
.is_ok());

assert!(schema
.execute(
r#"{
obj(n: 3) {
... A
}
}

fragment A on MyObj {
detail {
c
}
}"#,
)
.await
.is_ok());

assert!(schema
.execute(
r#"{
obj(n: 2) {
... A
... B
}
}

fragment A on MyObj {
detail {
d
}
}

fragment B on MyObj {
detail {
c
}
Expand Down