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
use std::fmt;

use crate::{ArgumentsDefinition, InputValueDefinition, StringValue};

/// The `DirectiveDefinition` type represents a Directive definition.
///
/// *DirectiveDefinition*:
///     Description? **directive @** Name Arguments Definition? **repeatable**? **on** DirectiveLocations
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/October2021/#sec-Type-System.Directives).
///
/// ### Example
/// ```rust
/// use apollo_encoder::DirectiveDefinition;
/// use indoc::indoc;
///
/// let mut directive = DirectiveDefinition::new("infer".to_string());
/// directive.description("Infer field types\nfrom field values.".to_string());
/// directive.location("OBJECT".to_string());
/// directive.location("FIELD_DEFINITION".to_string());
/// directive.location("INPUT_FIELD_DEFINITION".to_string());
///
/// assert_eq!(
///     directive.to_string(),
///     r#""""
/// Infer field types
/// from field values.
/// """
/// directive @infer on OBJECT | FIELD_DEFINITION | INPUT_FIELD_DEFINITION
/// "#
/// );
/// ```
#[derive(Debug, Clone)]
pub struct DirectiveDefinition {
    // Name must return a String.
    name: String,
    // Description may return a String or null.
    description: Option<StringValue>,
    // Args returns a Vector of __InputValue representing the arguments this
    // directive accepts.
    args: ArgumentsDefinition,
    // Locations returns a List of __DirectiveLocation representing the valid
    // locations this directive may be placed.
    locations: Vec<String>,
    // If the directive is repeatable
    repeatable: bool,
}

impl DirectiveDefinition {
    /// Create a new instance of Directive definition.
    pub fn new(name: String) -> Self {
        Self {
            name,
            description: None,
            args: ArgumentsDefinition::new(),
            locations: Vec::new(),
            repeatable: false,
        }
    }

    /// Set the Directive's description.
    pub fn description(&mut self, description: String) {
        self.description = Some(StringValue::Top {
            source: description,
        });
    }

    /// Add a location where this Directive can be used.
    pub fn location(&mut self, location: String) {
        self.locations.push(location);
    }

    /// Add an argument to this Directive.
    pub fn arg(&mut self, arg: InputValueDefinition) {
        self.args.input_value(arg);
    }

    /// Set the Directive's repeatable
    pub fn repeatable(&mut self) {
        self.repeatable = true;
    }
}

impl fmt::Display for DirectiveDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(description) = &self.description {
            writeln!(f, "{description}")?;
        }
        write!(f, "directive @{}", self.name)?;

        if !self.args.input_values.is_empty() {
            write!(f, "{}", self.args)?;
        }

        if self.repeatable {
            write!(f, " repeatable")?;
        }

        for (i, location) in self.locations.iter().enumerate() {
            match i {
                0 => write!(f, " on {location}")?,
                _ => write!(f, " | {location}")?,
            }
        }

        // append a new line at the end
        writeln!(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Type_;
    use pretty_assertions::assert_eq;

    #[test]
    fn it_encodes_directives_for_a_single_location() {
        let mut directive = DirectiveDefinition::new("infer".to_string());
        directive.description("Infer field types from field values.".to_string());
        directive.location("OBJECT".to_string());

        assert_eq!(
            directive.to_string(),
            r#""Infer field types from field values."
directive @infer on OBJECT
"#
        );
    }

    #[test]
    fn it_encodes_directives_for_multiple_location() {
        let mut directive = DirectiveDefinition::new("infer".to_string());
        directive.description("Infer field types\nfrom field values.".to_string());
        directive.location("OBJECT".to_string());
        directive.location("FIELD_DEFINITION".to_string());
        directive.location("INPUT_FIELD_DEFINITION".to_string());

        assert_eq!(
            directive.to_string(),
            r#""""
Infer field types
from field values.
"""
directive @infer on OBJECT | FIELD_DEFINITION | INPUT_FIELD_DEFINITION
"#
        );
    }

    #[test]
    fn it_encodes_directives_with_arguments() {
        let mut directive = DirectiveDefinition::new("infer".to_string());
        directive.description("Infer field types from field values.".to_string());
        directive.location("OBJECT".to_string());

        let ty_1 = Type_::NamedType {
            name: "SpaceProgram".to_string(),
        };

        let ty_2 = Type_::List { ty: Box::new(ty_1) };
        let arg = InputValueDefinition::new("cat".to_string(), ty_2);
        directive.arg(arg);

        assert_eq!(
            directive.to_string(),
            r#""Infer field types from field values."
directive @infer(cat: [SpaceProgram]) on OBJECT
"#
        );
    }

    #[test]
    fn it_encodes_directives_with_arguments_with_description() {
        let mut directive = DirectiveDefinition::new("infer".to_string());
        directive.description("Infer field types from field values.".to_string());
        directive.location("OBJECT".to_string());

        let ty_1 = Type_::NamedType {
            name: "SpaceProgram".to_string(),
        };

        let ty_2 = Type_::List { ty: Box::new(ty_1) };
        let mut arg = InputValueDefinition::new("cat".to_string(), ty_2);
        arg.description("Space Program for flying cats".to_string());
        directive.arg(arg);

        assert_eq!(
            directive.to_string(),
            r#""Infer field types from field values."
directive @infer(
    "Space Program for flying cats"
    cat: [SpaceProgram]
  ) on OBJECT
"#
        );
    }
}