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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
use std::fmt::{self, Write as _};

use crate::{Directive, SelectionSet};

/// The FragmentDefinition type represents a fragment definition
///
/// *FragmentDefinition*:
///     fragment FragmentName TypeCondition Directives? SelectionSet
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/October2021/#FragmentDefinition).
///
/// ### Example
/// ```rust
/// use apollo_encoder::{Field, FragmentDefinition, Selection, SelectionSet, TypeCondition};
/// use indoc::indoc;
///
/// let selections = vec![Selection::Field(Field::new(String::from("myField")))];
/// let mut selection_set = SelectionSet::new();
/// selections
///     .into_iter()
///     .for_each(|s| selection_set.selection(s));
/// let mut fragment_def = FragmentDefinition::new(
///     String::from("myFragment"),
///     TypeCondition::new(String::from("User")),
///     selection_set,
/// );
///
/// assert_eq!(
///     fragment_def.to_string(),
///     indoc! {r#"
///         fragment myFragment on User {
///           myField
///         }
///     "#}
/// );
/// ```
#[derive(Debug, Clone)]
pub struct FragmentDefinition {
    name: String,
    type_condition: TypeCondition,
    directives: Vec<Directive>,
    selection_set: SelectionSet,
}

impl FragmentDefinition {
    /// Create an instance of FragmentDefinition.
    pub fn new(name: String, type_condition: TypeCondition, selection_set: SelectionSet) -> Self {
        Self {
            name,
            type_condition,
            selection_set,
            directives: Vec::new(),
        }
    }

    /// Add a directive.
    pub fn directive(&mut self, directive: Directive) {
        self.directives.push(directive)
    }
}

impl fmt::Display for FragmentDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let indent_level = 0;
        write!(f, "fragment {} {}", self.name, self.type_condition)?;
        for directive in &self.directives {
            write!(f, " {directive}")?;
        }
        write!(
            f,
            " {}",
            self.selection_set.format_with_indent(indent_level)
        )?;

        Ok(())
    }
}

/// The FragmentSpread type represents a named fragment used in a selection set.
///
/// *FragmentSpread*:
///     ... FragmentName Directives?
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/October2021/#FragmentSpread).
///
/// ### Example
/// ```rust
/// use apollo_encoder::FragmentSpread;
///
/// let fragment = FragmentSpread::new(String::from("myFragment"));
/// assert_eq!(fragment.to_string(), r#"...myFragment"#);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct FragmentSpread {
    name: String,
    directives: Vec<Directive>,
}

impl FragmentSpread {
    /// Create a new instance of FragmentSpread
    pub fn new(name: String) -> Self {
        Self {
            name,
            directives: Vec::new(),
        }
    }

    /// Add a directive.
    pub fn directive(&mut self, directive: Directive) {
        self.directives.push(directive)
    }
}

impl fmt::Display for FragmentSpread {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "...{}", self.name)?;
        for directive in &self.directives {
            write!(f, " {directive}")?;
        }

        Ok(())
    }
}

/// The InlineFragment type represents an inline fragment in a selection set that could be used as a field
///
/// *InlineFragment*:
///     ... TypeCondition? Directives? SelectionSet
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/October2021/#sec-Inline-Fragments).
///
/// ### Example
/// ```rust
/// use apollo_encoder::{Field, InlineFragment, Selection, SelectionSet, TypeCondition};
/// use indoc::indoc;
///
/// let selections = vec![Selection::Field(Field::new(String::from("myField")))];
/// let mut selection_set = SelectionSet::new();
/// selections
///     .into_iter()
///     .for_each(|s| selection_set.selection(s));
///
/// let mut inline_fragment = InlineFragment::new(selection_set);
/// inline_fragment.type_condition(Some(TypeCondition::new(String::from("User"))));
///
/// assert_eq!(
///     inline_fragment.to_string(),
///     indoc! {r#"
///         ... on User {
///           myField
///         }
///     "#}
/// );
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct InlineFragment {
    type_condition: Option<TypeCondition>,
    directives: Vec<Directive>,
    selection_set: SelectionSet,
    pub(crate) indent_level: usize,
}

impl InlineFragment {
    /// Create an instance of InlineFragment
    pub fn new(selection_set: SelectionSet) -> Self {
        Self {
            selection_set,
            type_condition: Option::default(),
            directives: Vec::new(),
            indent_level: 0,
        }
    }

    /// Add a directive.
    pub fn directive(&mut self, directive: Directive) {
        self.directives.push(directive)
    }

    /// Set the inline fragment's type condition.
    pub fn type_condition(&mut self, type_condition: Option<TypeCondition>) {
        self.type_condition = type_condition;
    }

    /// Should be used everywhere in this crate isntead of the Display implementation
    /// Display implementation is only useful as a public api
    pub(crate) fn format_with_indent(&self, indent_level: usize) -> String {
        let mut text = String::from("...");

        if let Some(type_condition) = &self.type_condition {
            let _ = write!(text, " {type_condition}");
        }
        for directive in &self.directives {
            let _ = write!(text, " {directive}");
        }

        let _ = write!(
            text,
            " {}",
            self.selection_set.format_with_indent(indent_level),
        );

        text
    }
}

// This impl is only useful when we generate only an InlineFragment
// If it's used from a parent element, we call `format_with_indent`
impl fmt::Display for InlineFragment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let indent_level = 0;
        write!(f, "{}", self.format_with_indent(indent_level))
    }
}

/// The TypeCondition type represents where a fragment could be applied
///
/// *TypeCondition*:
///     on NamedType
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/October2021/#TypeCondition).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeCondition {
    name: String,
}

impl TypeCondition {
    /// Create an instance of TypeCondition
    pub fn new(name: String) -> Self {
        Self { name }
    }
}

impl fmt::Display for TypeCondition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "on {}", self.name)
    }
}

#[cfg(test)]
mod tests {
    use indoc::indoc;

    use crate::{field::Field, Argument, Selection, Value};

    use super::*;

    #[test]
    fn it_encodes_simple_inline_fragment() {
        let selections = vec![Selection::Field(Field::new(String::from("myField")))];
        let mut selection_set = SelectionSet::new();
        selections
            .into_iter()
            .for_each(|s| selection_set.selection(s));

        let mut inline_fragment = InlineFragment::new(selection_set);
        inline_fragment.type_condition(Some(TypeCondition::new(String::from("User"))));

        assert_eq!(
            inline_fragment.to_string(),
            indoc! {r#"
                ... on User {
                  myField
                }
            "#}
        );
    }

    #[test]
    fn it_encodes_simple_fragment_spread() {
        let fragment = FragmentSpread::new(String::from("myFragment"));

        assert_eq!(fragment.to_string(), indoc! {r#"...myFragment"#});
    }

    #[test]
    fn it_encodes_deeper_inline_fragment() {
        let another_nested_field_bis = Field::new(String::from("anotherNestedBisField"));

        let mut another_nested_field = Field::new(String::from("anotherNestedField"));
        let mut selection_set = SelectionSet::new();
        selection_set.selection(Selection::Field(another_nested_field_bis));
        another_nested_field.selection_set(selection_set.into());

        let mut selection_set = SelectionSet::new();
        selection_set.selection(Selection::Field(another_nested_field.clone()));
        another_nested_field.selection_set(selection_set.into());

        let nested_selections = vec![
            Selection::Field(Field::new(String::from("nestedField"))),
            Selection::Field(another_nested_field),
        ];
        let mut nested_selection_set = SelectionSet::new();
        nested_selections
            .into_iter()
            .for_each(|s| nested_selection_set.selection(s));

        let other_inline_fragment = InlineFragment::new(nested_selection_set);
        let selections = vec![
            Selection::Field(Field::new(String::from("myField"))),
            Selection::FragmentSpread(FragmentSpread::new(String::from("myFragment"))),
            Selection::InlineFragment(other_inline_fragment),
        ];
        let mut selection_set = SelectionSet::new();
        selections
            .into_iter()
            .for_each(|s| selection_set.selection(s));

        let mut inline_fragment = InlineFragment::new(selection_set);
        inline_fragment.type_condition(Some(TypeCondition::new(String::from("User"))));

        assert_eq!(
            inline_fragment.to_string(),
            indoc! {r#"
                ... on User {
                  myField
                  ...myFragment
                  ... {
                    nestedField
                    anotherNestedField {
                      anotherNestedField {
                        anotherNestedBisField
                      }
                    }
                  }
                }
            "#}
        );
    }

    #[test]
    fn it_encodes_fragment_definition() {
        let selections = vec![Selection::Field(Field::new(String::from("myField")))];
        let mut selection_set = SelectionSet::new();
        selections
            .into_iter()
            .for_each(|s| selection_set.selection(s));
        let mut fragment_def = FragmentDefinition::new(
            String::from("myFragment"),
            TypeCondition::new(String::from("User")),
            selection_set,
        );
        let mut directive = Directive::new(String::from("myDirective"));
        directive.arg(Argument::new(String::from("first"), Value::Int(5)));
        fragment_def.directive(directive);

        assert_eq!(
            fragment_def.to_string(),
            indoc! {r#"
                fragment myFragment on User @myDirective(first: 5) {
                  myField
                }
            "#}
        );
    }
}