async-graphql/src/base.rs

258 lines
7.2 KiB
Rust
Raw Normal View History

use crate::parser::Pos;
2020-03-19 09:20:12 +00:00
use crate::registry::Registry;
use crate::{
registry, Context, ContextSelectionSet, FieldResult, InputValueResult, Positioned, QueryError,
Result, Value, ID,
};
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-20 03:56:08 +00:00
/// Returns a `GlobalID` that is unique among all types.
fn global_id(id: ID) -> ID {
2020-05-10 13:58:56 +00:00
base64::encode(format!("{}:{}", Self::type_name(), *id)).into()
2020-03-20 03:56:08 +00:00
}
/// Parse `GlobalID`.
fn from_global_id(id: ID) -> Option<ID> {
2020-03-21 01:32:13 +00:00
let v: Vec<&str> = id.splitn(2, ':').collect();
2020-03-20 03:56:08 +00:00
if v.len() != 2 {
return None;
2020-03-20 03:56:08 +00:00
}
if v[0] != Self::type_name() {
return None;
2020-03-20 03:56:08 +00:00
}
Some(v[1].to_string().into())
2020-03-20 03:56:08 +00:00
}
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 {
2020-03-20 03:56:08 +00:00
/// Parse from `Value`
fn parse(value: &Value) -> InputValueResult<Self>;
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`.
async fn resolve(&self, ctx: &ContextSelectionSet<'_>, pos: Pos) -> 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,
2020-05-10 02:59:51 +00:00
name: &Positioned<String>,
ctx: &ContextSelectionSet<'a>,
futures: &mut Vec<BoxFieldFuture<'a>>,
) -> Result<()>
where
Self: Send + Sync + Sized,
{
if name.as_str() == Self::type_name().as_ref()
2020-04-22 07:03:41 +00:00
|| ctx
.registry
.implements
.get(Self::type_name().as_ref())
.map(|ty| ty.contains(name.as_str()))
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 {
2020-03-09 10:05:52 +00:00
/// fn type_name() -> &'static str {
/// "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)
2020-03-09 10:05:52 +00:00
/// }
/// }
///
2020-03-25 03:39:28 +00:00
/// fn to_json(&self) -> Result<serde_json::Value> {
/// Ok(self.0.into())
2020-03-09 10:05:52 +00:00
/// }
/// }
/// ```
pub trait ScalarType: Sized + Send {
2020-03-09 10:05:52 +00:00
/// The type name of a scalar.
2020-03-01 10:54:34 +00:00
fn type_name() -> &'static str;
2020-03-08 12:35:36 +00:00
2020-03-09 10:05:52 +00:00
/// The description of a scalar.
2020-03-03 11:15:18 +00:00
fn description() -> Option<&'static str> {
None
}
2020-03-08 12:35:36 +00:00
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.
///
/// The default implementation is to try to parse it, and in some cases you can implement this on your own to improve performance.
2020-03-08 12:35:36 +00:00
fn is_valid(value: &Value) -> bool {
match Self::parse(value) {
Ok(_) => true,
_ => false,
}
2020-03-08 12:35:36 +00:00
}
2020-03-09 10:05:52 +00:00
/// Convert the scalar value to json value.
2020-03-25 03:39:28 +00:00
fn to_json(&self) -> Result<serde_json::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)]
async fn resolve(&self, ctx: &ContextSelectionSet<'_>, pos: Pos) -> Result<serde_json::Value> {
T::resolve(*self, ctx, pos).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)]
async fn resolve(&self, ctx: &ContextSelectionSet<'_>, pos: Pos) -> Result<serde_json::Value> {
T::resolve(&*self, ctx, pos).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)]
async fn resolve(&self, ctx: &ContextSelectionSet<'_>, pos: Pos) -> Result<serde_json::Value> {
T::resolve(&*self, ctx, pos).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<'_>,
pos: Pos,
2020-05-06 02:02:25 +00:00
) -> crate::Result<serde_json::Value> {
match self {
2020-05-03 14:32:37 +00:00
Ok(value) => Ok(OutputValueType::resolve(value, ctx, pos).await?),
Err(err) => Err(err.clone().into_error_with_path(
pos,
match &ctx.path_node {
Some(path) => path.to_json(),
None => serde_json::Value::Null,
},
)),
}
}
}