Implement traits for ID to make it usable outside its module

ID is a named tuple with a private String field. This prevents any
creation of an ID outside its own module. Traits, such as conversion and
dereference, are added to make ID usable without exposing its inner
field.
This commit is contained in:
Michael Macias 2017-01-18 03:35:25 -06:00
parent 907d78d41b
commit b61281b63a

View file

@ -1,4 +1,6 @@
use std::convert::From;
use std::marker::PhantomData;
use std::ops::Deref;
use ast::{InputValue, Selection, FromInputValue, ToInputValue};
use value::Value;
@ -11,8 +13,23 @@ use types::base::GraphQLType;
/// An ID as defined by the GraphQL specification
///
/// Represented as a string, but can be converted _to_ from an integer as well.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ID(String);
impl From<String> for ID {
fn from(s: String) -> ID {
ID(s)
}
}
impl Deref for ID {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
graphql_scalar!(ID as "ID" {
resolve(&self) -> Value {
Value::string(&self.0)
@ -156,3 +173,21 @@ impl<T> GraphQLType for EmptyMutation<T> {
registry.build_object_type::<Self>(&[]).into_meta()
}
}
#[cfg(test)]
mod tests {
use super::ID;
#[test]
fn test_id_from_string() {
let actual = ID::from(String::from("foo"));
let expected = ID(String::from("foo"));
assert_eq!(actual, expected);
}
#[test]
fn test_id_deref() {
let id = ID(String::from("foo"));
assert_eq!(id.len(), 3);
}
}