use serde::{Deserialize, Serialize};
use std::fmt;
use uuid::Uuid;
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WrappedUuid(pub Uuid);
impl WrappedUuid {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn from_uuid(ulid: Uuid) -> Self {
Self(ulid)
}
}
impl From<Uuid> for WrappedUuid {
fn from(uuid: Uuid) -> Self {
WrappedUuid(uuid)
}
}
impl fmt::Display for WrappedUuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
pub mod graphql {
use std::str::FromStr;
use super::*;
use async_graphql::{InputValueError, InputValueResult, Scalar, ScalarType, Value};
#[Scalar]
impl ScalarType for WrappedUuid {
fn parse(value: Value) -> InputValueResult<Self> {
if let Value::String(s) = &value {
let uuid =
Uuid::from_str(s).map_err(|err| InputValueError::custom(err.to_string()))?;
Ok(WrappedUuid(uuid))
} else {
Err(InputValueError::expected_type(value))
}
}
fn to_value(&self) -> Value {
Value::String(self.0.to_string())
}
}
}