apollo_encoder/
directive.rs

1use std::fmt;
2
3use crate::Argument;
4
5/// The `Directive` type represents a Directive, it provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
6///
7/// *Directive*:
8///     @ Name Arguments?
9///
10/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/October2021/#sec-Language.Directives).
11///
12/// ### Example
13/// ```rust
14/// use apollo_encoder::{Argument, Directive, Value};
15///
16/// let mut directive = Directive::new(String::from("myDirective"));
17/// directive.arg(Argument::new(String::from("first"), Value::Int(5)));
18///
19/// assert_eq!(directive.to_string(), "@myDirective(first: 5)");
20/// ```
21#[derive(Debug, PartialEq, Clone)]
22pub struct Directive {
23    name: String,
24    args: Vec<Argument>,
25}
26
27impl Directive {
28    /// Create an instance of Directive
29    pub fn new(name: String) -> Self {
30        Self {
31            name,
32            args: Vec::new(),
33        }
34    }
35
36    /// Add an argument to the directive
37    pub fn arg(&mut self, arg: Argument) {
38        self.args.push(arg);
39    }
40}
41
42impl fmt::Display for Directive {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "@{}", self.name)?;
45
46        if !self.args.is_empty() {
47            for (i, arg) in self.args.iter().enumerate() {
48                match i {
49                    0 => write!(f, "({arg}")?,
50                    _ => write!(f, ", {arg}")?,
51                }
52            }
53            write!(f, ")")?;
54        }
55
56        Ok(())
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use crate::Value;
63
64    use super::*;
65
66    #[test]
67    fn it_encodes_directive() {
68        let mut directive = Directive::new(String::from("myDirective"));
69        directive.arg(Argument::new(String::from("first"), Value::Int(5)));
70
71        assert_eq!(directive.to_string(), "@myDirective(first: 5)");
72    }
73}