async-graphql/src/look_ahead.rs

347 lines
8.2 KiB
Rust
Raw Normal View History

2020-10-15 06:38:10 +00:00
use std::collections::HashMap;
2022-04-19 04:25:11 +00:00
use crate::{
parser::types::{Field, FragmentDefinition, Selection, SelectionSet},
Context, Name, Positioned, SelectionField,
};
2020-05-14 14:13:28 +00:00
2020-09-13 07:02:14 +00:00
/// A selection performed by a query.
2020-05-14 14:13:28 +00:00
pub struct Lookahead<'a> {
fragments: &'a HashMap<Name, Positioned<FragmentDefinition>>,
fields: Vec<&'a Field>,
context: &'a Context<'a>,
2020-05-14 14:13:28 +00:00
}
impl<'a> Lookahead<'a> {
pub(crate) fn new(
fragments: &'a HashMap<Name, Positioned<FragmentDefinition>>,
field: &'a Field,
context: &'a Context<'a>,
) -> Self {
2020-09-13 07:02:14 +00:00
Self {
fragments,
fields: vec![field],
context,
2020-09-13 07:02:14 +00:00
}
}
2022-04-19 04:25:11 +00:00
/// Get the field of the selection set with the specified name. This will
/// ignore aliases.
2020-09-13 07:02:14 +00:00
///
2022-04-19 04:25:11 +00:00
/// For example, calling `.field("a")` on `{ a { b } }` will return a
/// lookahead that represents `{ b }`.
2021-12-30 02:16:49 +00:00
#[must_use]
2020-09-06 05:38:31 +00:00
pub fn field(&self, name: &str) -> Self {
let mut fields = Vec::new();
for field in &self.fields {
2022-04-08 01:34:37 +00:00
filter(&mut fields, self.fragments, &field.selection_set.node, name)
}
2020-09-06 05:38:31 +00:00
Self {
fragments: self.fragments,
fields,
context: self.context,
2020-05-14 14:13:28 +00:00
}
}
/// Returns true if field exists otherwise return false.
#[inline]
pub fn exists(&self) -> bool {
!self.fields.is_empty()
2020-05-14 14:13:28 +00:00
}
2021-09-10 05:21:56 +00:00
2022-04-19 04:25:11 +00:00
/// Get the `SelectionField`s for each of the fields covered by this
/// `Lookahead`.
2021-09-28 03:50:27 +00:00
///
2022-04-19 04:25:11 +00:00
/// There will be multiple fields in situations where the same field is
/// queried twice.
2021-09-10 05:21:56 +00:00
pub fn selection_fields(&self) -> Vec<SelectionField<'a>> {
self.fields
.iter()
.map(|field| SelectionField {
fragments: self.fragments,
field,
context: self.context,
})
.collect()
}
2020-05-14 14:13:28 +00:00
}
impl<'a> From<SelectionField<'a>> for Lookahead<'a> {
fn from(selection_field: SelectionField<'a>) -> Self {
Lookahead {
fragments: selection_field.fragments,
fields: vec![selection_field.field],
context: selection_field.context,
}
}
}
/// Convert a slice of `SelectionField`s to a `Lookahead`.
2022-04-19 04:25:11 +00:00
/// Assumes all `SelectionField`s are from the same query and thus have the same
/// fragments.
///
2021-07-15 04:03:33 +00:00
/// Fails if either no `SelectionField`s were provided.
impl<'a> TryFrom<&[SelectionField<'a>]> for Lookahead<'a> {
type Error = ();
fn try_from(selection_fields: &[SelectionField<'a>]) -> Result<Self, Self::Error> {
if selection_fields.is_empty() {
Err(())
} else {
Ok(Lookahead {
fragments: selection_fields[0].fragments,
fields: selection_fields
.iter()
.map(|selection_field| selection_field.field)
.collect(),
context: selection_fields[0].context,
2021-07-15 04:03:33 +00:00
})
}
}
}
fn filter<'a>(
fields: &mut Vec<&'a Field>,
fragments: &'a HashMap<Name, Positioned<FragmentDefinition>>,
2020-05-14 14:13:28 +00:00
selection_set: &'a SelectionSet,
name: &str,
) {
for item in &selection_set.items {
match &item.node {
2020-05-14 14:13:28 +00:00
Selection::Field(field) => {
2020-09-06 05:38:31 +00:00
if field.node.name.node == name {
fields.push(&field.node)
2020-05-14 14:13:28 +00:00
}
}
2022-04-08 01:34:37 +00:00
Selection::InlineFragment(fragment) => {
filter(fields, fragments, &fragment.node.selection_set.node, name)
}
Selection::FragmentSpread(spread) => {
if let Some(fragment) = fragments.get(&spread.node.fragment_name.node) {
2022-04-08 01:34:37 +00:00
filter(fields, fragments, &fragment.node.selection_set.node, name)
}
2020-05-14 14:13:28 +00:00
}
}
}
2020-05-14 14:13:28 +00:00
}
#[cfg(test)]
mod tests {
use crate::*;
#[tokio::test]
2020-05-14 14:13:28 +00:00
async fn test_look_ahead() {
#[derive(SimpleObject)]
#[graphql(internal)]
2020-05-14 14:13:28 +00:00
struct Detail {
c: i32,
d: i32,
}
#[derive(SimpleObject)]
#[graphql(internal)]
2020-05-14 14:13:28 +00:00
struct MyObj {
a: i32,
b: i32,
detail: Detail,
}
struct Query;
#[Object(internal)]
2020-05-14 14:13:28 +00:00
impl Query {
async fn obj(&self, ctx: &Context<'_>, n: i32) -> MyObj {
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()
&& ctx.look_ahead().field("detail").field("d").exists()
{
2020-05-14 14:13:28 +00:00
// 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);
2020-05-14 14:13:28 +00:00
} else {
// This query doesn't have `a`
assert_eq!(n, 4);
2020-05-14 14:13:28 +00:00
}
MyObj {
a: 0,
b: 0,
detail: Detail { c: 0, d: 0 },
}
}
}
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
2020-11-30 08:17:32 +00:00
assert!(schema
2020-05-14 14:13:28 +00:00
.execute(
r#"{
obj(n: 1) {
a
}
}"#,
)
.await
2020-11-30 08:17:32 +00:00
.is_ok());
2020-05-14 14:13:28 +00:00
2020-11-30 08:17:32 +00:00
assert!(schema
2020-05-14 14:13:28 +00:00
.execute(
r#"{
obj(n: 1) {
k:a
}
}"#,
)
.await
2020-11-30 08:17:32 +00:00
.is_ok());
2020-05-14 14:13:28 +00:00
assert!(schema
.execute(
r#"{
obj(n: 3) {
detail {
c
}
}
}"#,
)
.await
.is_ok());
2020-11-30 08:17:32 +00:00
assert!(schema
2020-05-14 14:13:28 +00:00
.execute(
r#"{
obj(n: 2) {
detail {
d
}
2020-05-14 14:13:28 +00:00
detail {
c
}
}
}"#,
)
.await
2020-11-30 08:17:32 +00:00
.is_ok());
2020-05-14 14:13:28 +00:00
2020-11-30 08:17:32 +00:00
assert!(schema
2020-05-14 14:13:28 +00:00
.execute(
r#"{
obj(n: 4) {
2020-05-14 14:13:28 +00:00
b
}
}"#,
)
.await
2020-11-30 08:17:32 +00:00
.is_ok());
2020-05-14 14:13:28 +00:00
2020-11-30 08:17:32 +00:00
assert!(schema
2020-05-14 14:13:28 +00:00
.execute(
r#"{
obj(n: 1) {
... {
a
}
}
}"#,
)
.await
2020-11-30 08:17:32 +00:00
.is_ok());
2020-05-14 14:13:28 +00:00
assert!(schema
.execute(
r#"{
obj(n: 3) {
... {
detail {
c
}
}
}
}"#,
)
.await
.is_ok());
2020-11-30 08:17:32 +00:00
assert!(schema
2020-05-14 14:13:28 +00:00
.execute(
r#"{
obj(n: 2) {
... {
detail {
d
}
2020-05-14 14:13:28 +00:00
detail {
c
}
}
}
}"#,
)
.await
2020-11-30 08:17:32 +00:00
.is_ok());
2020-05-14 14:13:28 +00:00
2020-11-30 08:17:32 +00:00
assert!(schema
2020-05-14 14:13:28 +00:00
.execute(
r#"{
obj(n: 1) {
... A
}
}
fragment A on MyObj {
a
}"#,
)
.await
2020-11-30 08:17:32 +00:00
.is_ok());
2020-05-14 14:13:28 +00:00
assert!(schema
.execute(
r#"{
obj(n: 3) {
... A
}
}
fragment A on MyObj {
detail {
c
}
}"#,
)
.await
.is_ok());
2020-11-30 08:17:32 +00:00
assert!(schema
2020-05-14 14:13:28 +00:00
.execute(
r#"{
obj(n: 2) {
... A
... B
2020-05-14 14:13:28 +00:00
}
}
fragment A on MyObj {
detail {
d
}
}
fragment B on MyObj {
2020-05-14 14:13:28 +00:00
detail {
c
}
}"#,
)
.await
2020-11-30 08:17:32 +00:00
.is_ok());
2020-05-14 14:13:28 +00:00
}
}