From b61281b63a1771d8a8ce2ea0af265f79ef668cd4 Mon Sep 17 00:00:00 2001 From: Michael Macias Date: Wed, 18 Jan 2017 03:35:25 -0600 Subject: [PATCH] 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. --- src/types/scalars.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/types/scalars.rs b/src/types/scalars.rs index 0b541523..9730f212 100644 --- a/src/types/scalars.rs +++ b/src/types/scalars.rs @@ -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 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 GraphQLType for EmptyMutation { registry.build_object_type::(&[]).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); + } +}