async_graphql_relay/
lib.rs1#![forbid(unsafe_code)]
5#![warn(missing_docs)]
6
7use std::{any::Any, fmt, marker::PhantomData, str::FromStr};
8
9use async_graphql::{Error, InputValueError, InputValueResult, Scalar, ScalarType, Value};
10
11pub use async_graphql_relay_derive::*;
12use uuid::Uuid;
13
14pub trait RelayNodeInterface
17where
18 Self: Sized,
19{
20 fn fetch_node(
23 ctx: RelayContext,
24 relay_id: String,
25 ) -> impl std::future::Future<Output = Result<Self, Error>> + Send;
26}
27
28pub trait RelayNodeStruct {
32 const ID_SUFFIX: &'static str;
35}
36
37pub trait RelayNode: RelayNodeStruct {
40 type TNode: RelayNodeInterface;
42
43 fn get(
46 ctx: RelayContext,
47 id: RelayNodeID<Self>,
48 ) -> impl std::future::Future<Output = Result<Option<Self::TNode>, Error>> + Send;
49}
50
51#[derive(Clone, PartialEq, Eq)]
53pub struct RelayNodeID<T: RelayNode + ?Sized>(Uuid, PhantomData<T>);
54
55impl<T: RelayNode> RelayNodeID<T> {
56 pub fn new(uuid: Uuid) -> Self {
58 RelayNodeID(uuid, PhantomData)
59 }
60
61 pub fn new_from_relay_id(relay_id: String) -> Result<Self, Error> {
63 if relay_id.len() < 32 {
64 return Err(Error::new("Invalid id provided to node query!"));
65 }
66 let (id, _) = relay_id.split_at(32);
67 let uuid = Uuid::parse_str(id)
68 .map_err(|_err| Error::new("Invalid id provided to node query!"))?;
69 Ok(RelayNodeID(uuid, PhantomData))
70 }
71
72 pub fn new_from_str(uuid: &str) -> Result<Self, uuid::Error> {
74 Ok(Self::new(Uuid::from_str(uuid)?))
75 }
76
77 pub fn to_uuid(&self) -> Uuid {
80 self.0
81 }
82}
83
84impl<T: RelayNode> From<&RelayNodeID<T>> for String {
85 fn from(id: &RelayNodeID<T>) -> Self {
86 format!("{}{}", id.0.simple(), T::ID_SUFFIX)
87 }
88}
89
90impl<T: RelayNode> std::fmt::Display for RelayNodeID<T> {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 write!(f, "{}", String::from(self))
93 }
94}
95
96impl<T: RelayNode> fmt::Debug for RelayNodeID<T> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 f.debug_tuple("RelayNodeID").field(&self.0).finish()
99 }
100}
101
102#[Scalar]
103impl<T: RelayNode + Send + Sync> ScalarType for RelayNodeID<T> {
104 fn parse(value: Value) -> InputValueResult<Self> {
105 match value {
106 Value::String(s) => Ok(RelayNodeID::<T>::new_from_str(&s)?),
107 _ => Err(InputValueError::expected_type(value)),
108 }
109 }
110
111 fn to_value(&self) -> Value {
112 Value::String(String::from(self))
113 }
114}
115
116pub struct RelayContext(Box<dyn Any + Sync + Send>);
119
120impl RelayContext {
121 pub fn new<T: Any + Sync + Send>(data: T) -> Self {
123 Self(Box::new(data))
124 }
125
126 pub fn nil() -> Self {
128 let nil: Option<()> = None;
129 Self(Box::new(nil))
130 }
131
132 pub fn get<T: Any + Sync + Send>(&self) -> Option<&T> {
134 match self.0.downcast_ref::<T>() {
135 Some(v) => Some(v),
136 _ => None,
137 }
138 }
139}
140
141#[cfg(feature = "sea-orm")]
142impl<T: RelayNode> From<RelayNodeID<T>> for sea_orm::Value {
143 fn from(source: RelayNodeID<T>) -> Self {
144 sea_orm::Value::Uuid(Some(Box::new(source.to_uuid())))
145 }
146}
147
148#[cfg(feature = "sea-orm")]
149impl<T: RelayNode> sea_orm::TryGetable for RelayNodeID<T> {
150 fn try_get_by<I: sea_orm::ColIdx>(
151 res: &sea_orm::QueryResult,
152 index: I,
153 ) -> Result<Self, sea_orm::TryGetError> {
154 let val: Uuid = res.try_get_by(index).map_err(sea_orm::TryGetError::DbErr)?;
155 Ok(RelayNodeID::<T>::new(val))
156 }
157}
158
159#[cfg(feature = "sea-orm")]
160impl<T: RelayNode> sea_orm::sea_query::Nullable for RelayNodeID<T> {
161 fn null() -> sea_orm::Value {
162 sea_orm::Value::Uuid(None)
163 }
164}
165
166#[cfg(feature = "sea-orm")]
167impl<T: RelayNode> sea_orm::sea_query::ValueType for RelayNodeID<T> {
168 fn try_from(v: sea_orm::Value) -> Result<Self, sea_orm::sea_query::ValueTypeErr> {
169 match v {
170 sea_orm::Value::Uuid(Some(x)) => Ok(RelayNodeID::<T>::new(*x)),
171 _ => Err(sea_orm::sea_query::ValueTypeErr),
172 }
173 }
174
175 fn type_name() -> String {
176 stringify!(Uuid).to_owned()
177 }
178
179 fn column_type() -> sea_orm::sea_query::ColumnType {
180 sea_orm::sea_query::ColumnType::Uuid
181 }
182
183 fn array_type() -> sea_orm::sea_query::ArrayType {
184 sea_orm::sea_query::ArrayType::Uuid
185 }
186}
187
188#[cfg(feature = "sea-orm")]
189impl<T: RelayNode> sea_orm::TryFromU64 for RelayNodeID<T> {
190 fn try_from_u64(_: u64) -> Result<Self, sea_orm::DbErr> {
191 Err(sea_orm::DbErr::Exec(sea_orm::error::RuntimeErr::Internal(
192 format!(
193 "{} cannot be converted from u64",
194 std::any::type_name::<T>()
195 ),
196 )))
197 }
198}
199
200#[cfg(feature = "serde")]
201impl<T: RelayNode> serde::Serialize for RelayNodeID<T> {
202 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
203 where
204 S: serde::Serializer,
205 {
206 serializer.serialize_str(&self.to_string())
207 }
208}
209
210