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
use cynic::{serde_json::Value, DecodeError, Scalar, SerializableArgument, SerializeError}; use crate::{Int64Scalar, UInt64Scalar}; impl Scalar for Int64Scalar { fn decode(value: &Value) -> Result<Self, DecodeError> { match value { Value::String(string) => { let integer: i64 = string .parse() .map_err(|_| DecodeError::Other(format!("Invalid value {}", value)))?; Ok(Self(integer)) } _ => Err(DecodeError::IncorrectType( "String".to_owned(), format!("Invalid value {}", value), )), } } fn encode(&self) -> Result<Value, SerializeError> { Ok(Value::String(self.0.to_string())) } } impl SerializableArgument for Int64Scalar { fn serialize(&self) -> Result<Value, SerializeError> { Ok(Value::String(self.0.to_string())) } } impl Scalar for UInt64Scalar { fn decode(value: &Value) -> Result<Self, DecodeError> { match value { Value::String(string) => { let integer: u64 = string .parse() .map_err(|_| DecodeError::Other(format!("Invalid value {}", value)))?; Ok(Self(integer)) } _ => Err(DecodeError::IncorrectType( "String".to_owned(), format!("Invalid value {}", value), )), } } fn encode(&self) -> Result<Value, SerializeError> { Ok(Value::String(self.0.to_string())) } } impl SerializableArgument for UInt64Scalar { fn serialize(&self) -> Result<Value, SerializeError> { Ok(Value::String(self.0.to_string())) } } #[cfg(test)] mod tests { use super::*; use std::io; #[test] fn with_i64() -> io::Result<()> { assert_eq!( Int64Scalar(i64::MAX) .encode() .map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?, Value::String("9223372036854775807".to_owned()) ); assert_eq!( Int64Scalar::decode(&Value::String("9223372036854775807".to_owned())) .map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?, Int64Scalar(i64::MAX) ); assert_eq!( Int64Scalar(i64::MAX) .serialize() .map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?, Value::String("9223372036854775807".to_owned()) ); Ok(()) } #[test] fn with_u64() -> io::Result<()> { assert_eq!( UInt64Scalar(u64::MAX) .encode() .map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?, Value::String("18446744073709551615".to_owned()) ); assert_eq!( UInt64Scalar::decode(&Value::String("18446744073709551615".to_owned())) .map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?, UInt64Scalar(u64::MAX) ); assert_eq!( UInt64Scalar(u64::MAX) .serialize() .map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?, Value::String("18446744073709551615".to_owned()) ); Ok(()) } }