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
use std::fmt;
use crate::{Directive, Type_, Value};
/// The VariableDefinition type represents a variable definition
///
/// *VariableDefinition*:
/// VariableName : Type DefaultValue? Directives?
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/October2021/#sec-Language.Variables).
///
/// ### Example
/// ```rust
/// use apollo_encoder::{Type_, Value, VariableDefinition};
///
/// let mut variable = VariableDefinition::new(
/// String::from("my_var"),
/// Type_::NamedType {
/// name: String::from("MyType"),
/// },
/// );
/// variable.default_value(Value::Object(vec![
/// (String::from("first"), Value::Int(25)),
/// (String::from("second"), Value::String(String::from("test"))),
/// ]));
///
/// assert_eq!(
/// variable.to_string(),
/// String::from(r#"$my_var: MyType = { first: 25, second: "test" }"#)
/// );
/// ```
#[derive(Debug, Clone)]
pub struct VariableDefinition {
variable: String,
ty: Type_,
default_value: Option<Value>,
directives: Vec<Directive>,
}
impl VariableDefinition {
/// Create an instance of VariableDefinition
pub fn new(variable: String, ty: Type_) -> Self {
Self {
variable,
ty,
default_value: Option::default(),
directives: Vec::new(),
}
}
/// Set a default value to the variable
pub fn default_value(&mut self, default_value: Value) {
self.default_value = Some(default_value);
}
/// Add a directive
pub fn directive(&mut self, directive: Directive) {
self.directives.push(directive);
}
}
impl fmt::Display for VariableDefinition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "${}: {}", self.variable, self.ty)?;
if let Some(default_value) = &self.default_value {
write!(f, " = {default_value}")?;
}
for directive in &self.directives {
write!(f, " {directive}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_encodes_variable_definition() {
let mut variable = VariableDefinition::new(
String::from("my_var"),
Type_::NamedType {
name: String::from("MyType"),
},
);
variable.default_value(Value::Object(vec![
(String::from("first"), Value::Int(25)),
(String::from("second"), Value::String(String::from("test"))),
]));
assert_eq!(
variable.to_string(),
String::from(r#"$my_var: MyType = { first: 25, second: "test" }"#)
);
}
}