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
use std::fmt::{self, Display};
/// Convenience Type_ implementation used when creating a Field.
/// Can be a `NamedType`, a `NonNull` or a `List`.
///
/// This enum is resposible for encoding creating values such as `String!`, `[[[[String]!]!]!]!`, etc.
///
/// ### Example
/// ```rust
/// use apollo_encoder::{Type_};
///
/// let field_ty = Type_::NamedType {
/// name: "String".to_string(),
/// };
///
/// let list = Type_::List {
/// ty: Box::new(field_ty),
/// };
///
/// let non_null = Type_::NonNull { ty: Box::new(list) };
///
/// assert_eq!(non_null.to_string(), "[String]!");
/// ```
#[derive(Debug, PartialEq, Clone)]
pub enum Type_ {
/// The Non-Null field type.
NonNull {
/// Null inner type.
ty: Box<Type_>,
},
/// The List field type.
List {
/// List inner type.
ty: Box<Type_>,
},
/// The Named field type.
NamedType {
/// NamedType type.
name: String,
},
}
impl Display for Type_ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Type_::List { ty } => {
write!(f, "[{ty}]")
}
Type_::NonNull { ty } => {
write!(f, "{ty}!")
}
Type_::NamedType { name } => write!(f, "{name}"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn encodes_simple_field_value() {
let field_ty = Type_::NamedType {
name: "String".to_string(),
};
assert_eq!(field_ty.to_string(), "String");
}
#[test]
fn encodes_list_field_value() {
let field_ty = Type_::NamedType {
name: "String".to_string(),
};
let list = Type_::List {
ty: Box::new(field_ty),
};
assert_eq!(list.to_string(), "[String]");
}
#[test]
fn encodes_non_null_list_field_value() {
let field_ty = Type_::NamedType {
name: "String".to_string(),
};
let list = Type_::List {
ty: Box::new(field_ty),
};
let non_null = Type_::NonNull { ty: Box::new(list) };
assert_eq!(non_null.to_string(), "[String]!");
}
#[test]
fn encodes_non_null_list_non_null_list_field_value() {
let field_ty = Type_::NamedType {
name: "String".to_string(),
};
let list = Type_::List {
ty: Box::new(field_ty),
};
let non_null = Type_::NonNull { ty: Box::new(list) };
let list_2 = Type_::List {
ty: Box::new(non_null),
};
let non_null_2 = Type_::NonNull {
ty: Box::new(list_2),
};
assert_eq!(non_null_2.to_string(), "[[String]!]!");
}
}