async-graphql/src/base.rs

63 lines
1.6 KiB
Rust
Raw Normal View History

2020-03-03 03:48:00 +00:00
use crate::{schema, ContextSelectionSet, Result};
2020-03-01 10:54:34 +00:00
use graphql_parser::query::Value;
2020-03-02 00:24:49 +00:00
use std::borrow::Cow;
2020-03-01 10:54:34 +00:00
2020-03-03 03:48:00 +00:00
#[doc(hidden)]
pub trait GQLType {
fn type_name() -> Cow<'static, str>;
fn create_type_info(registry: &mut schema::Registry) -> String;
}
#[doc(hidden)]
pub trait GQLInputValue: GQLType + Sized {
fn parse(value: Value) -> Result<Self>;
fn parse_from_json(value: serde_json::Value) -> Result<Self>;
}
#[doc(hidden)]
#[async_trait::async_trait]
pub trait GQLOutputValue: GQLType {
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value>;
}
#[doc(hidden)]
pub trait GQLObject: GQLOutputValue {}
#[doc(hidden)]
pub trait GQLInputObject: GQLInputValue {}
2020-03-01 13:35:39 +00:00
pub trait Scalar: Sized + Send {
2020-03-01 10:54:34 +00:00
fn type_name() -> &'static str;
fn parse(value: Value) -> Result<Self>;
2020-03-01 16:52:05 +00:00
fn parse_from_json(value: serde_json::Value) -> Result<Self>;
2020-03-02 00:24:49 +00:00
fn to_json(&self) -> Result<serde_json::Value>;
2020-03-01 10:54:34 +00:00
}
2020-03-01 13:35:39 +00:00
impl<T: Scalar> GQLType for T {
2020-03-02 00:24:49 +00:00
fn type_name() -> Cow<'static, str> {
Cow::Borrowed(T::type_name())
2020-03-01 10:54:34 +00:00
}
2020-03-03 03:48:00 +00:00
fn create_type_info(registry: &mut schema::Registry) -> String {
registry.create_type(T::type_name(), |_| schema::Type::Scalar)
}
2020-03-01 10:54:34 +00:00
}
2020-03-01 13:35:39 +00:00
impl<T: Scalar> GQLInputValue for T {
2020-03-01 10:54:34 +00:00
fn parse(value: Value) -> Result<Self> {
T::parse(value)
}
2020-03-01 16:52:05 +00:00
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
T::parse_from_json(value)
}
2020-03-01 10:54:34 +00:00
}
#[async_trait::async_trait]
2020-03-02 00:24:49 +00:00
impl<T: Scalar + Sync> GQLOutputValue for T {
async fn resolve(&self, _: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
T::to_json(self)
2020-03-01 10:54:34 +00:00
}
}