async-graphql/src/scalars/id.rs

73 lines
1.4 KiB
Rust
Raw Normal View History

use crate::{Result, ScalarType, Value};
use async_graphql_derive::Scalar;
2020-03-01 16:59:04 +00:00
use std::ops::{Deref, DerefMut};
2020-03-09 10:05:52 +00:00
/// ID scalar
///
/// The input is a string or integer, and the output is a string.
2020-03-01 16:59:04 +00:00
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub struct ID(String);
2020-03-20 03:56:08 +00:00
impl std::fmt::Display for ID {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
2020-03-01 16:59:04 +00:00
impl Deref for ID {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ID {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
2020-03-17 09:26:59 +00:00
impl From<String> for ID {
fn from(value: String) -> Self {
ID(value)
}
}
impl<'a> From<&'a str> for ID {
fn from(value: &'a str) -> Self {
ID(value.to_string())
}
}
impl From<usize> for ID {
fn from(value: usize) -> Self {
ID(value.to_string())
}
}
2020-04-10 02:20:43 +00:00
impl PartialEq<&str> for ID {
fn eq(&self, other: &&str) -> bool {
self.0.as_str() == *other
}
}
#[Scalar(internal)]
impl ScalarType for ID {
2020-03-01 16:59:04 +00:00
fn type_name() -> &'static str {
"ID"
}
2020-03-04 02:38:07 +00:00
fn parse(value: &Value) -> Option<Self> {
2020-03-01 16:59:04 +00:00
match value {
2020-03-03 11:15:18 +00:00
Value::Int(n) => Some(ID(n.as_i64().unwrap().to_string())),
2020-03-04 02:38:07 +00:00
Value::String(s) => Some(ID(s.clone())),
2020-03-03 11:15:18 +00:00
_ => None,
2020-03-01 16:59:04 +00:00
}
}
2020-03-25 03:39:28 +00:00
fn to_json(&self) -> Result<serde_json::Value> {
Ok(self.0.clone().into())
2020-03-01 16:59:04 +00:00
}
}