use serde::{Deserialize, Serialize};
use std::fmt;
use ulid::Ulid;
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WrappedUlid(pub Ulid);
impl WrappedUlid {
pub fn new() -> Self {
Self(Ulid::new())
}
pub fn from_uuid(ulid: Ulid) -> Self {
Self(ulid)
}
}
impl From<Ulid> for WrappedUlid {
fn from(uuid: Ulid) -> Self {
WrappedUlid(uuid)
}
}
impl fmt::Display for WrappedUlid {
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 WrappedUlid {
fn parse(value: Value) -> InputValueResult<Self> {
if let Value::String(s) = &value {
let id =
Ulid::from_str(s).map_err(|err| InputValueError::custom(err.to_string()))?;
Ok(WrappedUlid(id))
} else {
Err(InputValueError::expected_type(value))
}
}
fn to_value(&self) -> Value {
Value::String(self.0.to_string())
}
}
}