From 74ce2171b899d9ebe6de970823da74293bc58371 Mon Sep 17 00:00:00 2001 From: sunli Date: Thu, 7 May 2020 11:05:27 +0800 Subject: [PATCH] Add uuid::Uuid, usize to ID type conversion. #54 --- src/scalars/id.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/scalars/id.rs b/src/scalars/id.rs index e0e795ac..a2cf55fe 100644 --- a/src/scalars/id.rs +++ b/src/scalars/id.rs @@ -1,10 +1,13 @@ use crate::{Result, ScalarType, Value}; use async_graphql_derive::Scalar; +use std::convert::TryInto; +use std::num::ParseIntError; use std::ops::{Deref, DerefMut}; +use uuid::Uuid; /// ID scalar /// -/// The input is a string or integer, and the output is a string. +/// The input is a `&str`, `String`, `usize` or `uuid::UUID`, and the output is a string. #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)] pub struct ID(String); @@ -34,6 +37,12 @@ impl From for ID { } } +impl Into for ID { + fn into(self) -> String { + self.0 + } +} + impl<'a> From<&'a str> for ID { fn from(value: &'a str) -> Self { ID(value.to_string()) @@ -46,6 +55,28 @@ impl From for ID { } } +impl TryInto for ID { + type Error = ParseIntError; + + fn try_into(self) -> std::result::Result { + self.0.parse() + } +} + +impl From for ID { + fn from(uuid: Uuid) -> ID { + ID(uuid.to_string()) + } +} + +impl TryInto for ID { + type Error = uuid::Error; + + fn try_into(self) -> std::result::Result { + Uuid::parse_str(&self.0) + } +} + impl PartialEq<&str> for ID { fn eq(&self, other: &&str) -> bool { self.0.as_str() == *other