102 lines
2.3 KiB
Rust
102 lines
2.3 KiB
Rust
|
use std::borrow::Cow;
|
||
|
|
||
|
use crate::{
|
||
|
registry, ContextSelectionSet, OutputValueType, Positioned, ServerResult, Type, Value,
|
||
|
};
|
||
|
use async_graphql_parser::types::Field;
|
||
|
|
||
|
impl<'a, T> Type for Cow<'a, T>
|
||
|
where
|
||
|
T: Type + ToOwned + ?Sized + Send + Sync,
|
||
|
{
|
||
|
fn type_name() -> Cow<'static, str> {
|
||
|
T::type_name()
|
||
|
}
|
||
|
|
||
|
fn create_type_info(registry: &mut registry::Registry) -> String {
|
||
|
<T as Type>::create_type_info(registry)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#[async_trait::async_trait]
|
||
|
impl<'a, T> OutputValueType for Cow<'a, T>
|
||
|
where
|
||
|
T: OutputValueType + ToOwned + ?Sized + Send + Sync,
|
||
|
<T as ToOwned>::Owned: Send + Sync,
|
||
|
{
|
||
|
async fn resolve(
|
||
|
&self,
|
||
|
ctx: &ContextSelectionSet<'_>,
|
||
|
field: &Positioned<Field>,
|
||
|
) -> ServerResult<Value> {
|
||
|
self.as_ref().resolve(ctx, field).await
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#[cfg(test)]
|
||
|
mod test {
|
||
|
use crate::*;
|
||
|
use std::borrow::Cow;
|
||
|
|
||
|
#[async_std::test]
|
||
|
async fn test_cow_type() {
|
||
|
struct Query11 {
|
||
|
obj: MyObj,
|
||
|
}
|
||
|
|
||
|
#[derive(SimpleObject, Clone)]
|
||
|
#[graphql(internal)]
|
||
|
struct MyObj {
|
||
|
a: i32,
|
||
|
b: i32,
|
||
|
}
|
||
|
|
||
|
#[Object(internal)]
|
||
|
impl Query11 {
|
||
|
async fn value1(&self) -> Cow<'_, str> {
|
||
|
Cow::Borrowed("abc")
|
||
|
}
|
||
|
|
||
|
async fn value2(&self) -> Cow<'_, str> {
|
||
|
Cow::Owned("def".to_string())
|
||
|
}
|
||
|
|
||
|
async fn obj1(&self) -> Cow<'_, MyObj> {
|
||
|
Cow::Borrowed(&self.obj)
|
||
|
}
|
||
|
|
||
|
async fn obj2(&self) -> Cow<'_, MyObj> {
|
||
|
Cow::Owned(MyObj { a: 300, b: 400 })
|
||
|
}
|
||
|
}
|
||
|
|
||
|
let query = r#"{
|
||
|
value1
|
||
|
value2
|
||
|
obj1 {
|
||
|
a b
|
||
|
}
|
||
|
obj2 {
|
||
|
a b
|
||
|
}
|
||
|
}"#;
|
||
|
let schema = Schema::new(
|
||
|
Query11 {
|
||
|
obj: MyObj { a: 100, b: 200 },
|
||
|
},
|
||
|
EmptyMutation,
|
||
|
EmptySubscription,
|
||
|
);
|
||
|
|
||
|
assert_eq!(
|
||
|
schema.execute(query).await.into_result().unwrap().data,
|
||
|
value!({
|
||
|
"value1": "abc",
|
||
|
"value2": "def",
|
||
|
"obj1": {"a": 100, "b": 200},
|
||
|
"obj2": {"a": 300, "b": 400},
|
||
|
})
|
||
|
);
|
||
|
}
|
||
|
}
|