async-graphql/src/base.rs

246 lines
6.7 KiB
Rust
Raw Normal View History

2020-03-19 09:20:12 +00:00
use crate::registry::Registry;
use crate::{
2020-05-20 00:18:28 +00:00
registry, Context, ContextSelectionSet, FieldResult, InputValueResult, Positioned, QueryError,
Result, Value,
};
2020-05-20 00:18:28 +00:00
use async_graphql_parser::query::Field;
2020-03-02 00:24:49 +00:00
use std::borrow::Cow;
2020-03-25 03:39:28 +00:00
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
2020-03-01 10:54:34 +00:00
2020-03-09 10:05:52 +00:00
/// Represents a GraphQL type
2020-03-20 03:56:08 +00:00
///
/// All GraphQL types implement this trait, such as `Scalar`, `Object`, `Union` ...
2020-03-19 09:20:12 +00:00
pub trait Type {
2020-03-09 10:05:52 +00:00
/// Type the name.
2020-03-03 03:48:00 +00:00
fn type_name() -> Cow<'static, str>;
2020-03-09 10:05:52 +00:00
/// Qualified typename.
2020-03-03 11:15:18 +00:00
fn qualified_type_name() -> String {
format!("{}!", Self::type_name())
}
/// Introspection type name
///
2020-04-03 01:31:58 +00:00
/// Is the return value of field `__typename`, the interface and union should return the current type, and the others return `Type::type_name`.
fn introspection_type_name(&self) -> Cow<'static, str> {
Self::type_name()
}
2020-03-09 10:05:52 +00:00
/// Create type information in the registry and return qualified typename.
2020-03-03 11:15:18 +00:00
fn create_type_info(registry: &mut registry::Registry) -> String;
2020-03-03 03:48:00 +00:00
}
2020-03-09 10:05:52 +00:00
/// Represents a GraphQL input value
2020-03-19 09:20:12 +00:00
pub trait InputValueType: Type + Sized {
/// Parse from `Value`None represent undefined.
fn parse(value: Option<Value>) -> InputValueResult<Self>;
/// Convert to `Value` for introspection
fn to_value(&self) -> Value;
2020-03-03 03:48:00 +00:00
}
2020-03-09 10:05:52 +00:00
/// Represents a GraphQL output value
2020-03-03 03:48:00 +00:00
#[async_trait::async_trait]
2020-03-19 09:20:12 +00:00
pub trait OutputValueType: Type {
2020-03-20 03:56:08 +00:00
/// Resolve an output value to `serde_json::Value`.
2020-05-20 00:18:28 +00:00
async fn resolve(
&self,
ctx: &ContextSelectionSet<'_>,
field: &Positioned<Field>,
) -> Result<serde_json::Value>;
2020-03-03 03:48:00 +00:00
}
2020-03-25 03:39:28 +00:00
#[allow(missing_docs)]
pub type BoxFieldFuture<'a> =
Pin<Box<dyn Future<Output = Result<(String, serde_json::Value)>> + 'a + Send>>;
2020-03-09 10:05:52 +00:00
/// Represents a GraphQL object
2020-03-06 15:58:43 +00:00
#[async_trait::async_trait]
2020-03-19 09:20:12 +00:00
pub trait ObjectType: OutputValueType {
/// This function returns true of type `EmptyMutation` only
2020-03-09 10:05:52 +00:00
#[doc(hidden)]
2020-03-05 09:06:14 +00:00
fn is_empty() -> bool {
2020-03-19 09:20:12 +00:00
false
2020-03-05 09:06:14 +00:00
}
2020-03-06 15:58:43 +00:00
2020-03-09 10:05:52 +00:00
/// Resolves a field value and outputs it as a json value `serde_json::Value`.
async fn resolve_field(&self, ctx: &Context<'_>) -> Result<serde_json::Value>;
2020-03-25 03:39:28 +00:00
/// Collect the fields with the `name` inline object
fn collect_inline_fields<'a>(
&'a self,
name: &str,
ctx: &ContextSelectionSet<'a>,
futures: &mut Vec<BoxFieldFuture<'a>>,
) -> Result<()>
where
Self: Send + Sync + Sized,
{
if name == Self::type_name().as_ref()
2020-04-22 07:03:41 +00:00
|| ctx
.schema_env
2020-04-22 07:03:41 +00:00
.registry
.implements
.get(Self::type_name().as_ref())
.map(|ty| ty.contains(name))
2020-04-22 07:03:41 +00:00
.unwrap_or_default()
2020-04-22 06:59:14 +00:00
{
crate::collect_fields(ctx, self, futures)
} else {
Ok(())
}
2020-03-25 03:39:28 +00:00
}
2020-04-09 14:03:09 +00:00
/// Query entities with params
async fn find_entity(&self, ctx: &Context<'_>, _params: &Value) -> Result<serde_json::Value> {
Err(QueryError::EntityNotFound.into_error(ctx.position()))
2020-04-09 14:03:09 +00:00
}
2020-03-05 09:06:14 +00:00
}
2020-03-03 03:48:00 +00:00
2020-03-09 10:05:52 +00:00
/// Represents a GraphQL input object
2020-03-19 09:20:12 +00:00
pub trait InputObjectType: InputValueType {}
2020-03-03 03:48:00 +00:00
2020-03-09 10:05:52 +00:00
/// Represents a GraphQL scalar
///
/// You can implement the trait to create a custom scalar.
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
///
/// struct MyInt(i32);
///
/// #[Scalar]
/// impl ScalarType for MyInt {
/// fn parse(value: Value) -> InputValueResult<Self> {
2020-03-09 10:05:52 +00:00
/// if let Value::Int(n) = value {
/// Ok(MyInt(n as i32))
2020-03-09 10:05:52 +00:00
/// } else {
/// Err(InputValueError::ExpectedType(value))
2020-03-09 10:05:52 +00:00
/// }
/// }
///
/// fn to_value(&self) -> Value {
/// Value::Int(self.0)
2020-03-09 10:05:52 +00:00
/// }
/// }
/// ```
pub trait ScalarType: Sized + Send {
2020-03-09 10:05:52 +00:00
/// Parse a scalar value, return `Some(Self)` if successful, otherwise return `None`.
fn parse(value: Value) -> InputValueResult<Self>;
2020-03-08 12:35:36 +00:00
2020-03-09 10:05:52 +00:00
/// Checks for a valid scalar value.
///
/// Implementing this function can find incorrect input values during the verification phase, which can improve performance.
fn is_valid(_value: &Value) -> bool {
true
2020-03-08 12:35:36 +00:00
}
/// Convert the scalar to `Value`.
fn to_value(&self) -> Value;
2020-03-01 10:54:34 +00:00
}
2020-03-19 09:20:12 +00:00
impl<T: Type + Send + Sync> Type for &T {
fn type_name() -> Cow<'static, str> {
T::type_name()
}
fn create_type_info(registry: &mut Registry) -> String {
T::create_type_info(registry)
}
}
2020-03-01 10:54:34 +00:00
#[async_trait::async_trait]
2020-03-19 09:20:12 +00:00
impl<T: OutputValueType + Send + Sync> OutputValueType for &T {
2020-03-21 01:32:13 +00:00
#[allow(clippy::trivially_copy_pass_by_ref)]
2020-05-20 00:18:28 +00:00
async fn resolve(
&self,
ctx: &ContextSelectionSet<'_>,
field: &Positioned<Field>,
) -> Result<serde_json::Value> {
T::resolve(*self, ctx, field).await
2020-03-01 10:54:34 +00:00
}
}
impl<T: Type + Send + Sync> Type for Box<T> {
fn type_name() -> Cow<'static, str> {
T::type_name()
}
fn create_type_info(registry: &mut Registry) -> String {
T::create_type_info(registry)
}
}
#[async_trait::async_trait]
impl<T: OutputValueType + Send + Sync> OutputValueType for Box<T> {
#[allow(clippy::trivially_copy_pass_by_ref)]
2020-04-25 06:57:01 +00:00
#[allow(clippy::borrowed_box)]
2020-05-20 00:18:28 +00:00
async fn resolve(
&self,
ctx: &ContextSelectionSet<'_>,
field: &Positioned<Field>,
) -> Result<serde_json::Value> {
T::resolve(&*self, ctx, field).await
}
}
impl<T: Type + Send + Sync> Type for Arc<T> {
fn type_name() -> Cow<'static, str> {
T::type_name()
}
fn create_type_info(registry: &mut Registry) -> String {
T::create_type_info(registry)
}
}
#[async_trait::async_trait]
impl<T: OutputValueType + Send + Sync> OutputValueType for Arc<T> {
#[allow(clippy::trivially_copy_pass_by_ref)]
2020-05-20 00:18:28 +00:00
async fn resolve(
&self,
ctx: &ContextSelectionSet<'_>,
field: &Positioned<Field>,
) -> Result<serde_json::Value> {
T::resolve(&*self, ctx, field).await
}
}
2020-05-03 14:32:37 +00:00
impl<T: Type> Type for FieldResult<T> {
fn type_name() -> Cow<'static, str> {
T::type_name()
}
fn qualified_type_name() -> String {
T::qualified_type_name()
}
fn create_type_info(registry: &mut registry::Registry) -> String {
2020-05-03 15:00:20 +00:00
T::create_type_info(registry)
2020-05-03 14:32:37 +00:00
}
}
#[async_trait::async_trait]
impl<T: OutputValueType + Sync> OutputValueType for FieldResult<T> {
async fn resolve(
&self,
2020-05-03 14:32:37 +00:00
ctx: &ContextSelectionSet<'_>,
2020-05-20 00:18:28 +00:00
field: &Positioned<Field>,
2020-05-06 02:02:25 +00:00
) -> crate::Result<serde_json::Value> {
match self {
2020-05-20 00:18:28 +00:00
Ok(value) => Ok(OutputValueType::resolve(value, ctx, field).await?),
2020-05-03 14:32:37 +00:00
Err(err) => Err(err.clone().into_error_with_path(
2020-05-20 00:18:28 +00:00
field.position(),
2020-05-03 14:32:37 +00:00
match &ctx.path_node {
Some(path) => path.to_json(),
2020-05-20 00:18:28 +00:00
None => Vec::new(),
2020-05-03 14:32:37 +00:00
},
)),
}
}
}