1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use super::ValidationRule;
use crate::ast::{visit_document, OperationVisitor, OperationVisitorContext};
use crate::static_graphql::query::*;
use crate::validation::utils::{ValidationError, ValidationErrorContext};

/// Lone Anonymous Operation
///
/// A GraphQL document is only valid if when it contains an anonymous operation
/// (the query short-hand) that it contains only that one operation definition.
///
/// https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation
pub struct LoneAnonymousOperation;

impl LoneAnonymousOperation {
    pub fn new() -> Self {
        LoneAnonymousOperation
    }
}

impl<'a> OperationVisitor<'a, ValidationErrorContext> for LoneAnonymousOperation {
    fn enter_document(
        &mut self,
        _: &mut OperationVisitorContext,
        user_context: &mut ValidationErrorContext,
        document: &Document,
    ) {
        let operations_count = document
            .definitions
            .iter()
            .filter(|n| match n {
                Definition::Operation(OperationDefinition::SelectionSet(_)) => true,
                Definition::Operation(OperationDefinition::Query(_)) => true,
                Definition::Operation(OperationDefinition::Mutation(_)) => true,
                Definition::Operation(OperationDefinition::Subscription(_)) => true,
                _ => false,
            })
            .count();

        for definition in &document.definitions {
            match definition {
                Definition::Operation(OperationDefinition::SelectionSet(_)) => {
                    if operations_count > 1 {
                        user_context.report_error(ValidationError {
                            message: "This anonymous operation must be the only defined operation."
                                .to_string(),
                            locations: vec![],
                        })
                    }
                }
                Definition::Operation(OperationDefinition::Query(query)) => {
                    if query.name == None && operations_count > 1 {
                        user_context.report_error(ValidationError {
                            message: "This anonymous operation must be the only defined operation."
                                .to_string(),
                            locations: vec![query.position.clone()],
                        })
                    }
                }
                Definition::Operation(OperationDefinition::Mutation(mutation)) => {
                    if mutation.name == None && operations_count > 1 {
                        user_context.report_error(ValidationError {
                            message: "This anonymous operation must be the only defined operation."
                                .to_string(),
                            locations: vec![mutation.position.clone()],
                        })
                    }
                }
                Definition::Operation(OperationDefinition::Subscription(subscription)) => {
                    if subscription.name == None && operations_count > 1 {
                        user_context.report_error(ValidationError {
                            message: "This anonymous operation must be the only defined operation."
                                .to_string(),
                            locations: vec![subscription.position.clone()],
                        })
                    }
                }
                _ => {}
            };
        }
    }
}

impl ValidationRule for LoneAnonymousOperation {
    fn validate<'a>(
        &self,
        ctx: &'a mut OperationVisitorContext,
        error_collector: &mut ValidationErrorContext,
    ) {
        visit_document(
            &mut LoneAnonymousOperation::new(),
            &ctx.operation,
            ctx,
            error_collector,
        );
    }
}

#[test]
fn no_operations() {
    use crate::validation::test_utils::*;

    let mut plan = create_plan_from_rule(Box::new(LoneAnonymousOperation {}));
    let errors = test_operation_with_schema(
        "fragment fragA on Type {
          field
        }",
        TEST_SCHEMA,
        &mut plan,
    );

    assert_eq!(get_messages(&errors).len(), 0);
}

#[test]
fn one_anon_operation() {
    use crate::validation::test_utils::*;

    let mut plan = create_plan_from_rule(Box::new(LoneAnonymousOperation {}));
    let errors = test_operation_with_schema(
        "{
          field
        }",
        TEST_SCHEMA,
        &mut plan,
    );

    assert_eq!(get_messages(&errors).len(), 0);
}

#[test]
fn mutiple_named() {
    use crate::validation::test_utils::*;

    let mut plan = create_plan_from_rule(Box::new(LoneAnonymousOperation {}));
    let errors = test_operation_with_schema(
        "query Foo {
          field
        }
        query Bar {
          field
        }",
        TEST_SCHEMA,
        &mut plan,
    );

    assert_eq!(get_messages(&errors).len(), 0);
}

#[test]
fn anon_operation_with_fragment() {
    use crate::validation::test_utils::*;

    let mut plan = create_plan_from_rule(Box::new(LoneAnonymousOperation {}));
    let errors = test_operation_with_schema(
        "{
          ...Foo
        }
        fragment Foo on Type {
          field
        }",
        TEST_SCHEMA,
        &mut plan,
    );

    assert_eq!(get_messages(&errors).len(), 0);
}

#[test]
fn multiple_anon_operations() {
    use crate::validation::test_utils::*;

    let mut plan = create_plan_from_rule(Box::new(LoneAnonymousOperation {}));
    let errors = test_operation_with_schema(
        "{
          fieldA
        }
        {
          fieldB
        }",
        TEST_SCHEMA,
        &mut plan,
    );

    let messages = get_messages(&errors);
    assert_eq!(messages.len(), 2);
    assert_eq!(
        messages,
        vec![
            "This anonymous operation must be the only defined operation.",
            "This anonymous operation must be the only defined operation."
        ]
    );
}

#[test]
fn anon_operation_with_mutation() {
    use crate::validation::test_utils::*;

    let mut plan = create_plan_from_rule(Box::new(LoneAnonymousOperation {}));
    let errors = test_operation_with_schema(
        "{
          fieldA
        }
        mutation Foo {
          fieldB
        }",
        TEST_SCHEMA,
        &mut plan,
    );

    let messages = get_messages(&errors);
    assert_eq!(messages.len(), 1);
    assert_eq!(
        messages,
        vec!["This anonymous operation must be the only defined operation."]
    );
}

#[test]
fn anon_operation_with_subscription() {
    use crate::validation::test_utils::*;

    let mut plan = create_plan_from_rule(Box::new(LoneAnonymousOperation {}));
    let errors = test_operation_with_schema(
        "{
          fieldA
        }
        subscription Foo {
          fieldB
        }",
        TEST_SCHEMA,
        &mut plan,
    );

    let messages = get_messages(&errors);
    assert_eq!(messages.len(), 1);
    assert_eq!(
        messages,
        vec!["This anonymous operation must be the only defined operation."]
    );
}